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
115e8ef3966200dcd66e4b3d50775c07d454ec10
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/special_functions/exp_deriv.lean
be948bb1a5f98a805ccf403613a56223ecb5b462
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
10,782
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 analysis.calculus.inverse import analysis.complex.real_deriv import analysis.special_functions.exp /-! # Complex and real exponential In this file we prove that `complex.exp` and `real.exp` are infinitely smooth functions. ## Tags exp, derivative -/ noncomputable theory open filter asymptotics set function open_locale classical 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.of_bound (∥exp x∥) _).trans_is_o (is_o_pow_id this), filter_upwards [metric.ball_mem_nhds (0 : ℂ) zero_lt_one], simp only [metric.mem_ball, dist_zero_right, normed_field.norm_pow], exact λ z hz, exp_bound_sq x z hz.le, end lemma differentiable_exp : differentiable ℂ exp := λx, (has_deriv_at_exp x).differentiable_at lemma differentiable_at_exp {x : ℂ} : differentiable_at ℂ exp x := differentiable_exp x @[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 [iterate_succ_apply, deriv_exp, iter_deriv_exp n] lemma times_cont_diff_exp : ∀ {n}, times_cont_diff ℂ n exp := begin refine times_cont_diff_all_iff_nat.2 (λ n, _), induction n with n ihn, { exact times_cont_diff_zero.2 continuous_exp }, { rw times_cont_diff_succ_iff_deriv, use differentiable_exp, rwa deriv_exp } end lemma has_strict_deriv_at_exp (x : ℂ) : has_strict_deriv_at exp (exp x) x := times_cont_diff_exp.times_cont_diff_at.has_strict_deriv_at' (has_deriv_at_exp x) le_rfl lemma has_strict_fderiv_at_exp_real (x : ℂ) : has_strict_fderiv_at exp (exp x • (1 : ℂ →L[ℝ] ℂ)) x := (has_strict_deriv_at_exp x).complex_to_real_fderiv lemma is_open_map_exp : is_open_map exp := open_map_of_strict_deriv has_strict_deriv_at_exp exp_ne_zero end complex section variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} lemma has_strict_deriv_at.cexp (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x := (complex.has_strict_deriv_at_exp (f x)).comp x hf lemma has_deriv_at.cexp (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x := (complex.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.cexp (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') s x := (complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cexp (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.exp (f x)) s x = complex.exp (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cexp.deriv_within hxs @[simp] lemma deriv_cexp (hc : differentiable_at ℂ f x) : deriv (λx, complex.exp (f x)) x = complex.exp (f x) * (deriv f x) := hc.has_deriv_at.cexp.deriv end section variables {f : ℝ → ℂ} {f' : ℂ} {x : ℝ} {s : set ℝ} open complex lemma has_strict_deriv_at.cexp_real (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, exp (f x)) (exp (f x) * f') x := (has_strict_fderiv_at_exp_real (f x)).comp_has_strict_deriv_at x h lemma has_deriv_at.cexp_real (h : has_deriv_at f f' x) : has_deriv_at (λ x, exp (f x)) (exp (f x) * f') x := (has_strict_fderiv_at_exp_real (f x)).has_fderiv_at.comp_has_deriv_at x h lemma has_deriv_within_at.cexp_real (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, exp (f x)) (exp (f x) * f') s x := (has_strict_fderiv_at_exp_real (f x)).has_fderiv_at.comp_has_deriv_within_at x h end section variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E} {s : set E} lemma has_strict_fderiv_at.cexp (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') x := (complex.has_strict_deriv_at_exp (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_within_at.cexp (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') s x := (complex.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf lemma has_fderiv_at.cexp (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') x := has_fderiv_within_at_univ.1 $ hf.has_fderiv_within_at.cexp lemma differentiable_within_at.cexp (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.exp (f x)) s x := hf.has_fderiv_within_at.cexp.differentiable_within_at @[simp] lemma differentiable_at.cexp (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.exp (f x)) x := hc.has_fderiv_at.cexp.differentiable_at lemma differentiable_on.cexp (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.exp (f x)) s := λx h, (hc x h).cexp @[simp] lemma differentiable.cexp (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.exp (f x)) := λx, (hc x).cexp lemma times_cont_diff.cexp {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.exp (f x)) := complex.times_cont_diff_exp.comp h lemma times_cont_diff_at.cexp {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.exp (f x)) x := complex.times_cont_diff_exp.times_cont_diff_at.comp x hf lemma times_cont_diff_on.cexp {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.exp (f x)) s := complex.times_cont_diff_exp.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.cexp {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.exp (f x)) s x := complex.times_cont_diff_exp.times_cont_diff_at.comp_times_cont_diff_within_at x hf end namespace real variables {x y z : ℝ} lemma has_strict_deriv_at_exp (x : ℝ) : has_strict_deriv_at exp (exp x) x := (complex.has_strict_deriv_at_exp x).real_of_complex lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x := (complex.has_deriv_at_exp x).real_of_complex lemma times_cont_diff_exp {n} : times_cont_diff ℝ n exp := complex.times_cont_diff_exp.real_of_complex lemma differentiable_exp : differentiable ℝ exp := λx, (has_deriv_at_exp x).differentiable_at lemma differentiable_at_exp : differentiable_at ℝ exp x := differentiable_exp x @[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 [iterate_succ_apply, deriv_exp, iter_deriv_exp n] end real section /-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} lemma has_strict_deriv_at.exp (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x := (real.has_strict_deriv_at_exp (f x)).comp x hf lemma has_deriv_at.exp (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x := (real.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.exp (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.exp (f x)) (real.exp (f x) * f') s x := (real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf lemma deriv_within_exp (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.exp (f x)) s x = real.exp (f x) * (deriv_within f s x) := hf.has_deriv_within_at.exp.deriv_within hxs @[simp] lemma deriv_exp (hc : differentiable_at ℝ f x) : deriv (λx, real.exp (f x)) x = real.exp (f x) * (deriv f x) := hc.has_deriv_at.exp.deriv end section /-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable function, for standalone use and use with `simp`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ} {x : E} {s : set E} lemma times_cont_diff.exp {n} (hf : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.exp (f x)) := real.times_cont_diff_exp.comp hf lemma times_cont_diff_at.exp {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.exp (f x)) x := real.times_cont_diff_exp.times_cont_diff_at.comp x hf lemma times_cont_diff_on.exp {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.exp (f x)) s := real.times_cont_diff_exp.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.exp {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.exp (f x)) s x := real.times_cont_diff_exp.times_cont_diff_at.comp_times_cont_diff_within_at x hf lemma has_fderiv_within_at.exp (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.exp (f x)) (real.exp (f x) • f') s x := (real.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf lemma has_fderiv_at.exp (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.exp (f x)) (real.exp (f x) • f') x := (real.has_deriv_at_exp (f x)).comp_has_fderiv_at x hf lemma has_strict_fderiv_at.exp (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.exp (f x)) (real.exp (f x) • f') x := (real.has_strict_deriv_at_exp (f x)).comp_has_strict_fderiv_at x hf lemma differentiable_within_at.exp (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.exp (f x)) s x := hf.has_fderiv_within_at.exp.differentiable_within_at @[simp] lemma differentiable_at.exp (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.exp (f x)) x := hc.has_fderiv_at.exp.differentiable_at lemma differentiable_on.exp (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.exp (f x)) s := λ x h, (hc x h).exp @[simp] lemma differentiable.exp (hc : differentiable ℝ f) : differentiable ℝ (λx, real.exp (f x)) := λ x, (hc x).exp lemma fderiv_within_exp (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.exp (f x)) s x = real.exp (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.exp.fderiv_within hxs @[simp] lemma fderiv_exp (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.exp (f x)) x = real.exp (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.exp.fderiv end
45fdc9e587722132dffc0d57346908b28308bbe3
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/data/quot.lean
6c7f35343a55f3bfe062bf2a1ebc5d6ea18099b5
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,117
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import logic.relator /-! # Quotient types This module extends the core library's treatment of quotient types (`init.data.quot`). ## Tags quotient -/ variables {α : Sort*} {β : Sort*} namespace setoid lemma ext {α : Sort*} : ∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t | ⟨r, _⟩ ⟨p, _⟩ eq := have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b, by subst this end setoid namespace quot variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*} local notation `⟦`:max a `⟧` := quot.mk _ a instance [inhabited α] : inhabited (quot ra) := ⟨⟦default _⟧⟩ /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb := quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa, quot.induction_on qb $ λ b, calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _) == f a₁ b : by simp [heq_self_iff_true] ... == f a₂ b : ca pa ... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp [heq_self_iff_true] /-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)` to a map `quot ra → quot rb`. -/ protected def map (f : α → β) (h : (ra ⇒ rb) f f) : quot ra → quot rb := quot.lift (λ x, ⟦f x⟧) $ assume x y (h₁ : ra x y), quot.sound $ h h₁ /-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/ protected def map_right {ra' : α → α → Prop} (h : ∀a₁ a₂, ra a₁ a₂ → ra' a₁ a₂) : quot ra → quot ra' := quot.map id h /-- weaken the relation of a quotient -/ def factor {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : quot r → quot s := quot.lift (quot.mk s) (λ x y rxy, quot.sound (h x y rxy)) lemma factor_mk_eq {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : factor r s h ∘ quot.mk _ = quot.mk _ := rfl variables {γ : Sort*} {r : α → α → Prop} {s : β → β → Prop} /-- **Alias** of `quot.lift_beta`. -/ lemma lift_mk (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) (a : α) : quot.lift f h (quot.mk r a) = f a := quot.lift_beta f h a @[simp] lemma lift_on_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : quot.lift_on (quot.mk r a) f h = f a := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β`. -/ attribute [reducible, elab_as_eliminator] protected def lift₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (q₁ : quot r) (q₂ : quot s) : γ := quot.lift (λ a, quot.lift (f a) (hr a)) (λ a₁ a₂ ha, funext (λ q, quot.induction_on q (λ b, hs a₁ a₂ b ha))) q₁ q₂ @[simp] lemma lift₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (a : α) (b : β) : quot.lift₂ f hr hs (quot.mk r a) (quot.mk s b) = f a b := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` and applies it. -/ attribute [reducible, elab_as_eliminator] protected def lift_on₂ (p : quot r) (q : quot s) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : γ := quot.lift₂ f hr hs p q @[simp] lemma lift_on₂_mk (a : α) (b : β) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift_on₂ (quot.mk r a) (quot.mk s b) f hr hs = f a b := rfl variables {t : γ → γ → Prop} /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` wih values in a quotient of `γ`. -/ protected def map₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (q₁ : quot r) (q₂ : quot s) : quot t := quot.lift₂ (λ a b, quot.mk t $ f a b) (λ a b₁ b₂ hb, quot.sound (hr a b₁ b₂ hb)) (λ a₁ a₂ b ha, quot.sound (hs a₁ a₂ b ha)) q₁ q₂ @[simp] lemma map₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (a : α) (b : β) : quot.map₂ f hr hs (quot.mk r a) (quot.mk s b) = quot.mk t (f a b) := rfl attribute [elab_as_eliminator] protected lemma induction_on₂ {δ : quot r → quot s → Prop} (q₁ : quot r) (q₂ : quot s) (h : ∀ a b, δ (quot.mk r a) (quot.mk s b)) : δ q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, h a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected lemma induction_on₃ {δ : quot r → quot s → quot t → Prop} (q₁ : quot r) (q₂ : quot s) (q₃ : quot t) (h : ∀ a b c, δ (quot.mk r a) (quot.mk s b) (quot.mk t c)) : δ q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, h a₁ a₂ a₃) q₃) q₂) q₁ end quot namespace quotient variables [sa : setoid α] [sb : setoid β] variables {φ : quotient sa → quotient sb → Sort*} instance [inhabited α] : inhabited (quotient sa) := ⟨⟦default _⟧⟩ /-- Induction on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quot.hrec_on₂ qa qb f (λ _ _ _ p, c _ _ _ _ p (setoid.refl _)) (λ _ _ _ p, c _ _ _ _ (setoid.refl _) p) /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient sa → quotient sb := quot.map f h @[simp] lemma map_mk (f : α → β) (h : ((≈) ⇒ (≈)) f f) (x : α) : quotient.map f h (⟦x⟧ : quotient sa) = (⟦f x⟧ : quotient sb) := rfl variables {γ : Sort*} [sc : setoid γ] /-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements to a function `f : quotient sa → quotient sb → quotient sc`. Useful to define binary operations on quotients. -/ protected def map₂ (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient sa → quotient sb → quotient sc := quotient.lift₂ (λ x y, ⟦f x y⟧) (λ x₁ y₁ x₂ y₂ h₁ h₂, quot.sound $ h h₁ h₂) end quotient lemma quot.eq {α : Type*} {r : α → α → Prop} {x y : α} : quot.mk r x = quot.mk r y ↔ eqv_gen r x y := ⟨quot.exact r, quot.eqv_gen_sound⟩ @[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := ⟨quotient.exact, quotient.sound⟩ theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} : (∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) := ⟨assume h x, h _, assume h a, a.induction_on h⟩ @[simp] lemma quotient.lift_mk [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift f h (quotient.mk x) = f x := rfl @[simp] lemma quotient.lift_on_mk [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift_on (quotient.mk x) f h = f x := rfl @[simp] theorem quotient.lift_on₂_mk {α : Sort*} {β : Sort*} [setoid α] (f : α → α → β) (h : ∀ (a₁ a₂ b₁ b₂ : α), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x y : α) : quotient.lift_on₂ (quotient.mk x) (quotient.mk y) f h = f x y := rfl /-- `quot.mk r` is a surjective function. -/ lemma surjective_quot_mk (r : α → α → Prop) : function.surjective (quot.mk r) := quot.exists_rep /-- `quotient.mk` is a surjective function. -/ lemma surjective_quotient_mk (α : Sort*) [s : setoid α] : function.surjective (quotient.mk : α → quotient s) := quot.exists_rep /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast @[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a := quotient.exact (quotient.out_eq _) instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) := { r := λ a b, ∀ i, a i ≈ b i, iseqv := ⟨ λ a i, setoid.refl _, λ a b h i, setoid.symm (h _), λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ } /-- Given a function `f : Π i, quotient (S i)`, returns the class of functions `Π i, α i` sending each `i` to an element of the class `f i`. -/ noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : Π i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := ⟦λ i, (f i).out⟧ theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [Π i, setoid (α i)] (f : Π i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ := quotient.sound $ λ i, quotient.mk_out _ lemma nonempty_quotient_iff (s : setoid α) : nonempty (quotient s) ↔ nonempty α := ⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩ /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true) theorem true_equivalence : @equivalence α (λ _ _, true) := ⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩ namespace trunc /-- Constructor for `trunc α` -/ def mk (a : α) : trunc α := quot.mk _ a instance [inhabited α] : inhabited (trunc α) := ⟨mk (default _)⟩ /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β := quot.lift f (λ a b _, c a b) theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind protected theorem lift_mk (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl /-- Lift a constant function on `q : trunc α`. -/ @[reducible, elab_as_eliminator] protected def lift_on (q : trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_eliminator] protected theorem induction_on {β : trunc α → Prop} (q : trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q attribute [elab_as_eliminator] protected theorem induction_on₂ {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁) protected theorem eq (a b : trunc α) : a = b := trunc.induction_on₂ a b (λ x y, quot.sound trivial) instance : subsingleton (trunc α) := ⟨trunc.eq⟩ /-- The `bind` operator for the `trunc` monad. -/ def bind (q : trunc α) (f : α → trunc β) : trunc β := trunc.lift_on q f (λ a b, trunc.eq _ _) /-- A function `f : α → β` defines a function `map f : trunc α → trunc β`. -/ def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f) instance : monad trunc := { pure := @trunc.mk, bind := @trunc.bind } instance : is_lawful_monad trunc := { id_map := λ α q, trunc.eq _ _, pure_bind := λ α β q f, rfl, bind_assoc := λ α β γ x f g, trunc.eq _ _ } variable {C : trunc α → Sort*} /-- Recursion/induction principle for `trunc`. -/ @[reducible, elab_as_eliminator] protected def rec (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : trunc α) : C q := quot.rec f (λ a b _, h a b) q /-- A version of `trunc.rec` taking `q : trunc α` as the first argument. -/ @[reducible, elab_as_eliminator] protected def rec_on (q : trunc α) (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := trunc.rec f h q /-- A version of `trunc.rec_on` assuming the codomain is a `subsingleton`. -/ @[reducible, elab_as_eliminator] protected def rec_on_subsingleton [∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q := trunc.rec f (λ a b, subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ noncomputable def out : trunc α → α := quot.out @[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _ end trunc theorem nonempty_of_trunc (q : trunc α) : nonempty α := let ⟨a, _⟩ := q.exists_rep in ⟨a⟩ namespace quotient variables {γ : Sort*} {φ : Sort*} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} /- Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules -/ /-- A version of `quotient.mk` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a /-- `quotient.mk'` is a surjective function. -/ lemma surjective_quotient_mk' : function.surjective (quotient.mk' : α → quotient s₁) := quot.exists_rep /-- A version of `quotient.lift_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator, reducible] protected def lift_on' (q : quotient s₁) (f : α → φ) (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h @[simp] protected lemma lift_on'_mk' (f : α → φ) (h) (x : α) : quotient.lift_on' (@quotient.mk' _ s₁ x) f h = f x := rfl /-- A version of `quotient.lift_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator, reducible] protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := quotient.lift_on₂ q₁ q₂ f h @[simp] protected lemma lift_on₂'_mk' (f : α → β → γ) (h) (a : α) (b : β) : quotient.lift_on₂' (@quotient.mk' _ s₁ a) (@quotient.mk' _ s₂ b) f h = f a b := rfl /-- A version of `quotient.ind` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma ind' {p : quotient s₁ → Prop} (h : ∀ a, p (quotient.mk' a)) (q : quotient s₁) : p q := quotient.ind h q /-- A version of `quotient.ind₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma ind₂' {p : quotient s₁ → quotient s₂ → Prop} (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) (q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ := quotient.ind₂ h q₁ q₂ /-- A version of `quotient.induction_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h /-- A version of `quotient.induction_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ := quotient.induction_on₂ q₁ q₂ h /-- A version of `quotient.induction_on₃` taking `{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ := quotient.induction_on₃ q₁ q₂ q₃ h /-- A version of `quotient.rec_on_subsingleton` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected def rec_on_subsingleton' {φ : quotient s₁ → Sort*} [h : ∀ a, subsingleton (φ ⟦a⟧)] (q : quotient s₁) (f : Π a, φ (quotient.mk' a)) : φ q := quotient.rec_on_subsingleton q f /-- Recursion on a `quotient` argument `a`, result type depends on `⟦a⟧`. -/ protected def hrec_on' {φ : quotient s₁ → Sort*} (qa : quotient s₁) (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) : φ qa := quot.hrec_on qa f c @[simp] lemma hrec_on'_mk' {φ : quotient s₁ → Sort*} (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) (x : α) : (quotient.mk' x).hrec_on' f c = f x := rfl /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂' {φ : quotient s₁ → quotient s₂ → Sort*} (qa : quotient s₁) (qb : quotient s₂) (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quotient.hrec_on₂ qa qb f c @[simp] lemma hrec_on₂'_mk' {φ : quotient s₁ → quotient s₂ → Sort*} (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) (x : α) (qb : quotient s₂) : (quotient.mk' x).hrec_on₂' qb f c = qb.hrec_on' (f x) (λ b₁ b₂, c _ _ _ _ (setoid.refl _)) := rfl /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map' (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ := quot.map f h @[simp] lemma map'_mk' (f : α → β) (h) (x : α) : (quotient.mk' x : quotient s₁).map' f h = (quotient.mk' (f x) : quotient s₂) := rfl /-- A version of `quotient.map₂` using curly braces and unification. -/ protected def map₂' (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ → quotient s₃ := quotient.map₂ f h @[simp] lemma map₂'_mk' (f : α → β → γ) (h) (x : α) : (quotient.mk' x : quotient s₁).map₂' f h = (quotient.map' (f x) (h (setoid.refl x)) : quotient s₂ → quotient s₃) := rfl lemma exact' {a b : α} : (quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b := quotient.exact lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b := quotient.sound @[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b := quotient.eq /-- A version of `quotient.out` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ noncomputable def out' (a : quotient s₁) : α := quotient.out a @[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a := quotient.exact (quotient.out_eq _) end quotient
5d09fddda5e10b1ed213f04051a518a03bbbe55e
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/polynomial.lean
70f0068effaceed526a037010ca2eb3bd66c9023
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
97,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, Johannes Hölzl, Jens Wagemaker Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring. -/ import data.finsupp algebra.gcd_domain ring_theory.euclidean_domain tactic.ring ring_theory.multiplicity /-- `polynomial α` is the type of univariate polynomials over `α`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from α is called `C`. -/ def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α open finsupp finset lattice namespace polynomial universes u v variables {α : Type u} {β : Type v} {a b : α} {m n : ℕ} section comm_semiring variables [comm_semiring α] [decidable_eq α] {p q r : polynomial α} instance : has_zero (polynomial α) := finsupp.has_zero instance : has_one (polynomial α) := finsupp.has_one instance : has_add (polynomial α) := finsupp.has_add instance : has_mul (polynomial α) := finsupp.has_mul instance : comm_semiring (polynomial α) := finsupp.comm_semiring instance : decidable_eq (polynomial α) := finsupp.decidable_eq def polynomial.has_coe_to_fun : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun local attribute [instance] finsupp.comm_semiring polynomial.has_coe_to_fun @[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl /-- `C a` is the constant polynomial `a`. -/ def C (a : α) : polynomial α := single 0 a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial α := single 1 1 /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial α) := p.to_fun @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial α) = f := rfl instance [has_repr α] : has_repr (polynomial α) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ theorem ext {p q : polynomial α} : p = q ↔ ∀ n, coeff p n = coeff q n := ⟨λ h n, h ▸ rfl, finsupp.ext⟩ /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial α) : with_bot ℕ := p.support.sup some def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0 lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] lemma sum_C_mul_X_eq (p : polynomial α) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _) @[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by simpa only [C, single_zero], h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X], h_add _ _ this hp) @[simp] lemma C_0 : C (0 : α) = 0 := single_zero @[simp] lemma C_1 : C (1 : α) = 1 := rfl @[simp] lemma C_mul : C (a * b) = C a * C b := (@single_mul_single _ _ _ _ _ _ 0 0 a b).symm @[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add instance C.is_semiring_hom : is_semiring_hom (C : α → polynomial α) := ⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩ @[simp] lemma C_pow : C (a ^ n) = C a ^ n := is_semiring_hom.map_pow _ _ _ lemma nat_cast_eq_C (n : ℕ) : (n : polynomial α) = C n := by refine (nat.eq_cast (λ n, C (n : α)) _ _ _ n).symm; simp section coeff lemma apply_eq_coeff : p n = coeff p n := rfl @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial α) n = 0 := rfl @[simp] lemma coeff_one_zero (n : ℕ) : coeff (1 : polynomial α) 0 = 1 := rfl @[simp] lemma coeff_add (p q : polynomial α) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by simp [coeff, eq_comm, C, single]; congr @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := rfl @[simp] lemma coeff_X_one : coeff (X : polynomial α) 1 = 1 := rfl @[simp] lemma coeff_X_zero : coeff (X : polynomial α) 0 = 0 := rfl lemma coeff_X : coeff (X : polynomial α) n = if 1 = n then 1 else 0 := rfl @[simp] lemma coeff_C_mul_X (x : α) (k n : ℕ) : coeff (C x * X^k : polynomial α) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [single, eq_comm, coeff]; congr lemma coeff_sum [comm_semiring β] [decidable_eq β] (n : ℕ) (f : ℕ → α → polynomial β) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply lemma coeff_single : coeff (single n a) m = if n = m then a else 0 := rfl @[simp] lemma coeff_C_mul (p : polynomial α) : coeff (C a * p) n = a * coeff p n := begin conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, coeff_sum] }, rw [mul_def, C, sum_single_index], { simp [coeff_single, finsupp.mul_sum, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, simp end @[simp] lemma coeff_one (n : ℕ) : coeff (1 : polynomial α) n = if 0 = n then 1 else 0 := rfl @[simp] lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial α) n = if n = k then 1 else 0 := by simpa only [C_1, one_mul] using coeff_C_mul_X (1:α) k n lemma coeff_mul (p q : polynomial α) (n : ℕ) : coeff (p * q) n = (nat.antidiagonal n).sum (λ x, coeff p x.1 * coeff q x.2) := have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0 → a.1 + a.2 = n, from λ a ha, by_contradiction (λ h, absurd (eq.refl (0 : α)) (by rwa if_neg h at ha)), calc coeff (p * q) n = sum (p.support) (λ a, sum (q.support) (λ b, ite (a + b = n) (coeff p a * coeff q b) 0)) : by simp only [finsupp.mul_def, coeff_sum, coeff_single]; refl ... = (p.support.product q.support).sum (λ v : ℕ × ℕ, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0) : by rw sum_product ... = (nat.antidiagonal n).sum (λ x, coeff p x.1 * coeff q x.2) : begin refine sum_bij_ne_zero (λ x _ _, x) (λ x _ hx, nat.mem_antidiagonal.2 (hite x hx)) (λ _ _ _ _ _ _ h, h) (λ x h₁ h₂, ⟨x, _, _, rfl⟩) _, { rw [mem_product, mem_support_iff, mem_support_iff], exact ⟨ne_zero_of_mul_ne_zero_right h₂, ne_zero_of_mul_ne_zero_left h₂⟩ }, { rw nat.mem_antidiagonal at h₁, rwa [if_pos h₁] }, { intros x h hx, rw [if_pos (hite x hx)] } end theorem coeff_mul_X_pow (p : polynomial α) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end theorem coeff_mul_X (p : polynomial α) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial α} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext.2 $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext.1 H (k+n) end coeff lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ section eval₂ variables [semiring β] variables (f : α → β) (x : β) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial α) : β := p.sum (λ e a, f a * x ^ e) variables [is_semiring_hom f] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [map_one f, one_mul, pow_one] @[simp] lemma eval₂_zero : (0 : polynomial α).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [map_zero f, zero_mul]) (λ _ _ _, by rw [map_add f, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial α).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } end eval₂ section eval₂ variables [comm_semiring β] variables (f : α → β) [is_semiring_hom f] (x : β) open is_semiring_hom @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, map_mul f, pow_add], { simp only [mul_assoc, mul_left_comm] }, { rw [map_zero f, zero_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ lemma eval₂_sum (p : polynomial α) (g : ℕ → α → polynomial α) (x : β) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) end eval₂ section eval variable {x : α} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : α → polynomial α → α := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial α).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval_sum (p : polynomial α) (f : ℕ → α → polynomial α) (x : α) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval₂_hom [comm_semiring β] (f : α → β) [is_semiring_hom f] (x : α) : p.eval₂ f (f x) = f (p.eval x) := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, eval_pow, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0 instance : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma coeff_zero_eq_eval_zero (p : polynomial α) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) end eval section comp def comp (p q : polynomial α) : polynomial α := p.eval₂ C q lemma eval₂_comp [comm_semiring β] (f : α → β) [is_semiring_hom f] {x : β} : (p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) := show (p.sum (λ e a, C a * q ^ e)).eval₂ f x = p.eval₂ f (eval₂ f x q), by simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_sum]; refl lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _ @[simp] lemma comp_X : p.comp X = p := begin refine polynomial.ext.2 (λ n, _), rw [comp, eval₂], conv in (C _ * _) { rw ← single_eq_C_mul_X }, rw finsupp.sum_single end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← sum_hom (@C α _ _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial α) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial α) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial α) p = 1 := by rw [← C_1, C_comp] instance : is_semiring_hom (λ q : polynomial α, q.comp p) := by unfold comp; apply_instance @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ end comp section map variables [comm_semiring β] [decidable_eq β] variables (f : α → β) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial α → polynomial β := eval₂ (C ∘ f) X variables [is_semiring_hom f] @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial α).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial α).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← finset.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, is_semiring_hom.map_mul f], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map {γ : Type*} [comm_semiring γ] [decidable_eq γ] (g : β → γ) [is_semiring_hom g] (p : polynomial α) : (p.map f).map g = p.map (λ x, g (f x)) := polynomial.ext.2 (by simp [coeff_map]) lemma eval₂_map {γ : Type*} [comm_semiring γ] (g : β → γ) [is_semiring_hom g] (x : γ) : (p.map f).eval₂ g x = p.eval₂ (λ y, g (f y)) x := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) lemma eval_map (x : β) : (p.map f).eval x = p.eval₂ f x := eval₂_map _ _ _ @[simp] lemma map_id : p.map id = p := by simp [id, polynomial.ext, coeff_map] end map /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial α) : α := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial α) := leading_coeff p = (1 : α) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial α) = 0 := rfl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma nat_degree_eq_of_degree_eq_some {p : polynomial α} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [comm_semiring β] [decidable_eq β] {q : polynomial β} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end @[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial α) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial α) = 0 := by simp [nat_cast_eq_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin refine polynomial.ext.2 (λ n, _), cases n, { refl }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p := sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h) lemma degree_sum_le [decidable_eq β] (s : finset β) (f : β → polynomial α) : degree (s.sum f) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p) | 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ _ _ n a } end @[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial α) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _ lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial α) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = (nat.antidiagonal (nat_degree p + nat_degree q)).sum (λ x, coeff p x.1 * coeff q x.2) : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul_eq' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = add_monoid.smul n (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, add_monoid.zero_smul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁] lemma nat_degree_pow_eq' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow_eq' h, degree_eq_nat_degree hp0, ← with_bot.coe_smul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial α) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : α) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (degree q) : add_le_add' degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (nat_degree q) : add_le_add_left' (add_monoid.smul_le_smul_of_le_right (@degree_le_nat_degree _ _ _ q) n) ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_smul, add_monoid.smul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] : degree (p.map f) ≤ degree p := if h : p.map f = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) : (∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma degree_map_eq_of_leading_coeff_ne_zero [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma degree_map_eq_of_injective [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hf : function.injective f) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma monic_map [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hp : monic p) : monic (p.map f) := if h : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by erw [monic, leading_coeff, nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), coeff_map, ← leading_coeff, show _ = _, from hp, is_semiring_hom.map_one f] lemma zero_le_degree_iff {p : polynomial α} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial @[simp] lemma coeff_mul_X_zero (p : polynomial α) : coeff (p * X) 0 = 0 := by rw [coeff_mul, nat.antidiagonal_zero]; simp only [polynomial.coeff_X_zero, finset.insert_empty_eq_singleton, finset.sum_singleton, mul_zero] end comm_semiring instance subsingleton [subsingleton α] [comm_semiring α] : subsingleton (polynomial α) := ⟨λ _ _, polynomial.ext.2 (λ _, subsingleton.elim _ _)⟩ section comm_semiring variables [decidable_eq α] [comm_semiring α] {p q r : polynomial α} lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : α) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := polynomial.ext.2 (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : α) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial α) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:α) n theorem degree_X_le : degree (X : polynomial α) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:α) 1 lemma degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α) {f : α → β} [is_semiring_hom f] (hf : function.injective f) : degree (p.map f) = degree p := degree_map_eq_of_injective _ hf lemma nat_degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α) {f : α → β} [is_semiring_hom f] (hf : function.injective f) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' _ hf) theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, @subsingleton.elim _ (subsingleton_of_zero_eq_one α $ H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : α) : monic (X + C x) := pow_one (X : polynomial α) ▸ monic_X_pow_add degree_C_le theorem degree_le_iff_coeff_zero (f : polynomial α) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem nat_degree_le_of_degree_le {p : polynomial α} {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end theorem leading_coeff_mul_X_pow {p : polynomial α} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (assume H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (assume H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : α) = 1 then by haveI := subsingleton_of_zero_eq_one _ h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : α) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul_eq' hpnr0, nat_degree_pow_eq' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_ge_one_right' (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section nonzero_comm_semiring variables [nonzero_comm_semiring α] [decidable_eq α] {p q : polynomial α} instance : nonzero_comm_semiring (polynomial α) := { zero_ne_one := λ (h : (0 : polynomial α) = 1), @zero_ne_one α _ $ calc (0 : α) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_semiring } @[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) := degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial α) = 1 := begin unfold X degree single finsupp.support, rw if_neg (zero_ne_one).symm, refl end lemma X_ne_zero : (X : polynomial α) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial α) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl @[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) := by simpa only [monic, leading_coeff_zero] using zero_ne_one lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero α _ _ (h₁ ▸ h) end nonzero_comm_semiring section comm_semiring variables [decidable_eq α] [comm_semiring α] {p q : polynomial α} /-- `dix_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial α) : polynomial α := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm, apply_eq_coeff], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial α) : div_X p * X + C (p.coeff 0) = p := polynomial.ext.2 $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : α) : div_X (C a) = 0 := polynomial.ext.2 $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := polynomial.ext.2 $ by simp [div_X] def nonzero_comm_semiring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_semiring α := { zero_ne_one := λ h01 : 0 = 1, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero], ..show comm_semiring α, by apply_instance } lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul_eq' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp0; exact calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne lattice.bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial α) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul_eq' this]; exact add_le_add' (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw div_X_mul_X_add @[elab_as_eliminator] def rec_on_horner {M : polynomial α → Sort*} : Π (p : polynomial α), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial α → Prop} (p : polynomial α) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, not_lt.2 (@lattice.bot_le ( ℕ) _ _)] using h0')) h0 end comm_semiring section comm_ring variables [comm_ring α] [decidable_eq α] {p q : polynomial α} instance : comm_ring (polynomial α) := finsupp.comm_ring instance : has_scalar α (polynomial α) := finsupp.has_scalar -- TODO if this becomes a semimodule then the below lemma could be proved for semimodules instance : module α (polynomial α) := finsupp.module ℕ α -- TODO -- this is OK for semimodules @[simp] lemma coeff_smul (p : polynomial α) (r : α) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply -- TODO -- this is OK for semimodules lemma C_mul' (a : α) (f : polynomial α) : C a * f = a • f := ext.2 $ λ n, coeff_C_mul f variable (α) def lcoeff (n : ℕ) : polynomial α →ₗ α := { to_fun := λ f, coeff f n, add := λ f g, coeff_add f g n, smul := λ r p, coeff_smul p r n } variable {α} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial α) : lcoeff α n f = coeff f n := rfl instance C.is_ring_hom : is_ring_hom (@C α _ _) := by apply is_ring_hom.of_semiring lemma int_cast_eq_C (n : ℤ) : (n : polynomial α) = C n := congr_fun (int.eq_cast' _).symm n @[simp] lemma C_neg : C (-a) = -C a := is_ring_hom.map_neg C @[simp] lemma C_sub : C (a - b) = C a - C b := is_ring_hom.map_sub C instance eval₂.is_ring_hom {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : α} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma map_sub {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial α) = 0 := by simp [int_cast_eq_C] @[simp] lemma coeff_neg (p : polynomial α) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial α) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma eval₂_neg {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (-p).eval₂ f x = -p.eval₂ f x := is_ring_hom.map_neg _ @[simp] lemma eval₂_sub {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := is_ring_hom.map_sub _ @[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α}, monic q → polynomial α × polynomial α | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial α), p = 0, from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma div_mod_by_monic_unique {f g} (q r : polynomial α) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial α))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul_eq']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01α : (0 : α) ≠ 1, from mt (congr_arg f) (by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (ne_zero_of_monic_of_zero_ne_one hq h01α) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ @[simp] lemma mod_by_monic_one (p : polynomial α) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero monic_one).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial α) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end theorem monic_X_sub_C (x : α) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) theorem degree_mod_by_monic_le (p : polynomial α) {q : polynomial α} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial α) = 1 := (by rw [← C_0, ← C_1, hq]); rw [eq_zero_of_zero_eq_one _ this (p %ₘ q), eq_zero_of_zero_eq_one _ this q]; exact le_refl _) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] def nonzero_comm_ring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_ring α := { zero := 0, one := 1, zero_ne_one := λ h01, h $ by rw [← one_mul p, ← one_mul q, ← C_1, ← h01, C_0, zero_mul, zero_mul], ..show comm_ring α, by apply_instance } end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] [decidable_eq α] {p q : polynomial α} instance : nonzero_comm_ring (polynomial α) := { ..polynomial.nonzero_comm_semiring, ..polynomial.comm_ring } @[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X α], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : degree ((X : polynomial α) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial α) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial α) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : α) : (X : polynomial α) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial α) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn; exact dec_trivial) end nonzero_comm_ring section comm_ring variables [comm_ring α] [decidable_eq α] {p q : polynomial α} @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : α) = 1 then by letI := subsingleton_of_zero_eq_one α h0; exact subsingleton.elim _ _ else by letI : nonzero_comm_ring α := nonzero_comm_ring.of_ne h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial α) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity def decidable_dvd_monic (p : polynomial α) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) local attribute [instance, priority 0] classical.dec lemma multiplicity_X_sub_C_finite (a : α) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : α) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact h0 (subsingleton.elim _ _)), by letI : nonzero_comm_ring α := { zero_ne_one := this, ..show comm_ring α, by apply_instance }; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 def root_multiplicity (a : α) (p : polynomial α) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial α) (a : α) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial α) (a : α) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial α) (a : α) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial α} (a : α) (hp : p ≠ 0) : (p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 := begin letI : nonzero_comm_ring α := nonzero_comm_ring.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) _ hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring section integral_domain variables [integral_domain α] [decidable_eq α] {p q : polynomial α} @[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) : degree (p ^ n) = add_monoid.smul n (degree p) := by induction n; [simp only [pow_zero, degree_one, add_monoid.zero_smul], simp only [*, pow_succ, succ_smul, degree_mul_eq]] @[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; [simp only [pow_zero, leading_coeff_one], simp only [*, pow_succ, leading_coeff_mul]] instance : integral_domain (polynomial α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma nat_degree_mul_eq (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_eq] @[simp] lemma nat_degree_pow_eq (p : polynomial α) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow_eq' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0), ∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial α) : finset α := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : (roots ((X : polynomial α) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial α) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial α) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ noncomputable def nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : finset α := by letI := classical.prop_decidable; exact roots ((X : polynomial α) ^ n - C a) @[simp] lemma mem_nth_roots {α : Type*} [integral_domain α] {n : ℕ} (hn : 0 < n) {a x : α} : x ∈ nth_roots n a ↔ x ^ n = a := by letI := classical.prop_decidable; rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : (nth_roots n a).card ≤ n := by letI := classical.prop_decidable; exact if hn : n = 0 then if h : (X : polynomial α) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← @C_1 α _ _, ← @is_ring_hom.map_sub _ _ _ _ (@C α _ _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa [← apply_eq_coeff, ← finsupp.mem_support_iff], dsimp [apply_eq_coeff], refine coeff_eq_zero_of_degree_lt _, rw [degree_mul_eq, degree_C this, degree_pow_eq, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_smul, add_monoid.smul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], exact (mul_lt_mul_right (nat.pos_of_ne_zero hqd0)).2 (lt_of_le_of_ne (with_bot.coe_le_coe.1 (by rw ← degree_eq_nat_degree hp0; exact le_sup hbs)) hbp) end (by rw [finsupp.mem_support_iff, apply_eq_coeff, ← leading_coeff, ne.def, leading_coeff_eq_zero, classical.not_not]; simp {contextual := tt}) ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow_eq], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial α) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul_eq hp0 hq0, eq_comm, add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial α)) : degree (u : polynomial α) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial α)) : nat_degree (u : polynomial α) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma coeff_coe_units_zero_ne_zero (u : units (polynomial α)) : coeff (u : polynomial α) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : α} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul_eq, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) end integral_domain section field variables [discrete_field α] {p q : polynomial α} instance : vector_space α (polynomial α) := finsupp.vector_space _ _ lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact (hp $ is_unit.map' C $ is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))) lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := ⟨mt is_unit_iff_dvd_one.1 (λ ⟨q, hq⟩, absurd (congr_arg degree hq) (λ h, have degree q = 0, by rw [degree_one, degree_mul_eq, hp1, eq_comm, nat.with_bot.add_eq_zero_iff] at h; exact h.2, by simp [degree_mul_eq, this, degree_one, hp1] at h; exact absurd h dec_trivial)), λ q r hpqr, begin have := congr_arg degree hpqr, rw [hp1, degree_mul_eq, eq_comm, nat.with_bot.add_eq_one_iff] at this, rw [is_unit_iff_degree_eq_zero, is_unit_iff_degree_eq_zero]; tautology end⟩ lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial α) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial α) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial α) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial α) := ⟨div⟩ instance : has_mod (polynomial α) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial α) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} lemma degree_div_le (p q : polynomial α) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [discrete_field β] (p : polynomial α) (f : α → β) [is_field_hom f] : degree (p.map f) = degree p := degree_map_eq_of_injective _ (is_field_hom.injective f) @[simp] lemma nat_degree_map [discrete_field β] (f : α → β) [is_field_hom f] : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [discrete_field β] (f : α → β) [is_field_hom f] : leading_coeff (p.map f) = f (leading_coeff p) := by simp [leading_coeff, coeff_map f] lemma map_div [discrete_field β] (f : α → β) [is_field_hom f] : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [is_field_hom.map_inv f, leading_coeff, coeff_map f] lemma map_mod [discrete_field β] (f : α → β) [is_field_hom f] : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← is_field_hom.map_inv f, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] @[simp] lemma map_eq_zero [discrete_field β] (f : α → β) [is_field_hom f] : p.map f = 0 ↔ p = 0 := by simp [polynomial.ext, is_field_hom.map_eq_zero f, coeff_map] lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial α)) (n : ℕ) : ((↑u : polynomial α).coeff n)⁻¹ = ((↑u⁻¹ : polynomial α).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end instance : normalization_domain (polynomial α) := { norm_unit := λ p, if hp0 : p = 0 then 1 else ⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rw [← C_mul, inv_mul_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0, by rw [← C_mul, mul_inv_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0,⟩, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ p q hp0 hq0, begin rw [dif_neg hp0, dif_neg hq0, dif_neg (mul_ne_zero hp0 hq0)], apply units.ext, show C (leading_coeff (p * q))⁻¹ = C (leading_coeff p)⁻¹ * C (leading_coeff q)⁻¹, rw [leading_coeff_mul, mul_inv', C_mul, mul_comm] end, norm_unit_coe_units := λ u, have hu : degree ↑u⁻¹ = 0, from degree_eq_zero_of_is_unit ⟨u⁻¹, rfl⟩, begin apply units.ext, rw [dif_neg (units.coe_ne_zero u)], conv_rhs {rw eq_C_of_degree_eq_zero hu}, refine C_inj.2 _, rw [← nat_degree_eq_of_degree_eq_some hu, leading_coeff, coeff_inv_units], simp end, ..polynomial.integral_domain } lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := show leading_coeff (p * ↑(dite _ _ _)) = 1, by rw dif_neg hp0; exact monic_mul_leading_coeff_inv hp0 lemma coe_norm_unit (hp : p ≠ 0) : (norm_unit p : polynomial α) = C p.leading_coeff⁻¹ := show ↑(dite _ _ _) = C p.leading_coeff⁻¹, by rw dif_neg hp; refl end field section derivative variables [comm_semiring α] [decidable_eq α] /-- `derivative p` formal derivative of the polynomial `p` -/ def derivative (p : polynomial α) : polynomial α := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial α) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1), apply_eq_coeff], { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one] }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul] }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { intro H, rw [not_mem_support_iff.1 H, zero_mul, zero_mul] } end @[simp] lemma derivative_zero : derivative (0 : polynomial α) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : α) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp only [zero_mul, C_0]; refl @[simp] lemma derivative_C {a : α} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:α) * X ^ 0, by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero], derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial α) = 1 := suffices derivative (C (1:α) * X^1) = C (1 * (1:ℕ)) * X ^ 0, by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero], derivative_monomial 1 1 @[simp] lemma derivative_one : derivative (1 : polynomial α) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial α} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] instance : is_add_monoid_hom (derivative : polynomial α → polynomial α) := { map_add := λ _ _, derivative_add, map_zero := derivative_zero } @[simp] lemma derivative_sum {s : finset β} {f : β → polynomial α} : derivative (s.sum f) = s.sum (λb, derivative (f b)) := (finset.sum_hom derivative).symm @[simp] lemma derivative_mul {f g : polynomial α} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end lemma derivative_eval (p : polynomial α) (x : α) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp [derivative, eval_sum, eval_pow] end derivative section domain variables [integral_domain α] [decidable_eq α] lemma mem_support_derivative [char_zero α] (p : polynomial α) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : α) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [coeff_derivative, apply_eq_coeff, mem_support_iff, ne.def, mul_eq_zero], by rw [nat.cast_eq_zero]; simp only [nat.succ_ne_zero, or_false] @[simp] lemma degree_derivative_eq [char_zero α] (p : polynomial α) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring Maybe use data.nat.choose to prove it. -/ def pow_add_expansion {α : Type*} [comm_semiring α] (x y : α) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, rw [_root_.pow_succ, hz], existsi (x*z + (n+1)*x^n+z*y), simp [_root_.pow_succ], ring end variables [comm_ring α] [decidable_eq α] private def poly_binom_aux1 (x y : α) (e : ℕ) (a : α) : {k : α // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr, ext, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc] def binom_expansion (f : polynomial α) (x y : α) : {k : α // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw derivative_eval, symmetry, apply finsupp.sum_mul }, { symmetry, apply finsupp.sum_mul } end def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z : α // x^i - y^i = z*(x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases pow_sub_pow_factor with z hz, existsi z*x + y^(k+1), rw [_root_.pow_succ x, _root_.pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)), ←mul_sub x, hz], simp only [_root_.pow_succ], ring end def eval_sub_factor (f : polynomial α) (x y : α) : {z : α // f.eval x - f.eval y = z*(x - y)} := begin existsi f.sum (λ a b, b * (pow_sub_pow_factor x y).val), unfold eval eval₂, rw [←finsupp.sum_sub], have : finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val) * (x - y) = finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val * (x - y)), { apply finsupp.sum_mul }, rw this, congr, ext e a, rw [mul_assoc, ←(pow_sub_pow_factor x y).property], simp [left_distrib] end end identities end polynomial
14c948009b8d9dcd660adaaa7dc3943f188ffa20
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/opposites.lean
3f7d83c7630a6b184cda8be18e1ec7225aa8329f
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
7,226
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 category_theory.products import category_theory.types namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- The type of objects of the opposite of C (which should be a category). In order to avoid confusion between C and its opposite category, we set up the type of objects `opposite C` using the following pattern, which will be repeated later for the morphisms. 1. Define `opposite C := C`. 2. Define the isomorphisms `op : C → opposite C`, `unop : opposite C → C`. 3. Make the definition `opposite` irreducible. This has the following consequences. * `opposite C` and `C` are distinct types in the elaborator, so you must use `op` and `unop` explicitly to convert between them. * Both `unop (op X) = X` and `op (unop X) = X` are definitional equalities. Notably, every object of the opposite category is definitionally of the form `op X`, which greatly simplifies the definition of the structure of the opposite category, for example. (If Lean supported definitional eta equality for records, we could achieve the same goals using a structure with one field.) -/ def opposite (C : Type u₁) : Type u₁ := C -- Use a high right binding power (like that of postfix ⁻¹) so that, for example, -- `presheaf Cᵒᵖ` parses as `presheaf (Cᵒᵖ)` and not `(presheaf C)ᵒᵖ`. notation C `ᵒᵖ`:std.prec.max_plus := opposite C variables {C : Type u₁} def op (X : C) : Cᵒᵖ := X def unop (X : Cᵒᵖ) : C := X attribute [irreducible] opposite @[simp] lemma unop_op (X : C) : unop (op X) = X := rfl @[simp] lemma op_unop (X : Cᵒᵖ) : op (unop X) = X := rfl lemma op_inj : function.injective (@op C) := by { rintros _ _ ⟨ ⟩, refl } lemma unop_inj : function.injective (@unop C) := by { rintros _ _ ⟨ ⟩, refl } section has_hom variables [𝒞 : has_hom.{v₁} C] include 𝒞 /-- The hom types of the opposite of a category (or graph). As with the objects, we'll make this irreducible below. Use `f.op` and `f.unop` to convert between morphisms of C and morphisms of Cᵒᵖ. -/ instance has_hom.opposite : has_hom Cᵒᵖ := { hom := λ X Y, unop Y ⟶ unop X } def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f attribute [irreducible] has_hom.opposite lemma has_hom.hom.op_inj {X Y : C} : function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg has_hom.hom.unop H lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg has_hom.hom.op H @[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl @[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl end has_hom variables [𝒞 : category.{v₁} C] include 𝒞 instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } -- TODO this is an equivalence namespace functor section variables {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒟 variables {C D} protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } @[simp] lemma op_obj (F : C ⥤ D) (X : Cᵒᵖ) : (F.op).obj X = op (F.obj (unop X)) := rfl @[simp] lemma op_map (F : C ⥤ D) {X Y : Cᵒᵖ} (f : X ⟶ Y) : (F.op).map f = (F.map f.unop).op := rfl protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } @[simp] lemma unop_obj (F : Cᵒᵖ ⥤ Dᵒᵖ) (X : C) : (F.unop).obj X = unop (F.obj (op X)) := rfl @[simp] lemma unop_map (F : Cᵒᵖ ⥤ Dᵒᵖ) {X Y : C} (f : X ⟶ Y) : (F.unop).map f = (F.map f.op).unop := rfl variables (C D) definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, has_hom.hom.unop_inj $ eq.symm (α.unop.naturality f.unop) } } @[simp] lemma op_hom.obj (F : (C ⥤ D)ᵒᵖ) : (op_hom C D).obj F = (unop F).op := rfl @[simp] lemma op_hom.map_app {F G : (C ⥤ D)ᵒᵖ} (α : F ⟶ G) (X : Cᵒᵖ) : ((op_hom C D).map α).app X = (α.unop.app (unop X)).op := rfl definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, has_hom.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, has_hom.hom.op_inj $ eq.symm (α.naturality f.op) } } @[simp] lemma op_inv.obj (F : Cᵒᵖ ⥤ Dᵒᵖ) : (op_inv C D).obj F = op F.unop := rfl @[simp] lemma op_inv.map_app {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) (X : C) : (((op_inv C D).map α).unop).app X = (α.app (op X)).unop := rfl -- TODO show these form an equivalence instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { injectivity' := λ X Y f g h, has_hom.hom.unop_inj $ by simpa using injectivity F (has_hom.hom.op_inj h) } end section variable (C) /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ definition hom : Cᵒᵖ × C ⥤ Type v₁ := { obj := λ p, unop p.1 ⟶ p.2, map := λ X Y f, λ h, f.1.unop ≫ h ≫ f.2 } @[simp] lemma hom_obj (X : Cᵒᵖ × C) : (functor.hom C).obj X = (unop X.1 ⟶ X.2) := rfl @[simp] lemma hom_pairing_map {X Y : Cᵒᵖ × C} (f : X ⟶ Y) : (functor.hom C).map f = λ h, f.1.unop ≫ h ≫ f.2 := rfl end end functor omit 𝒞 instance opposite.has_one [has_one C] : has_one (Cᵒᵖ) := { one := op 1 } instance opposite.has_mul [has_mul C] : has_mul (Cᵒᵖ) := { mul := λ x y, op $ unop y * unop x } @[simp] lemma opposite.unop_one [has_one C] : unop (1 : Cᵒᵖ) = (1 : C) := rfl @[simp] lemma opposite.unop_mul [has_mul C] (xs ys : Cᵒᵖ) : unop (xs * ys) = (unop ys * unop xs : C) := rfl @[simp] lemma opposite.op_one [has_one C] : op (1 : C) = 1 := rfl @[simp] lemma opposite.op_mul [has_mul C] (xs ys : C) : op (xs * ys) = (op ys * op xs) := rfl instance opposite.monoid [monoid C] : monoid (Cᵒᵖ) := { one := op 1, mul := λ x y, op $ unop y * unop x, mul_one := by { intros, apply unop_inj, simp }, one_mul := by { intros, simp }, mul_assoc := by { intros, simp [mul_assoc], } } end category_theory
61f063013a3fda121e5a657fdc0f838fa98ac1d6
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/ResolveName.lean
098cbcdac0419c78c19ecc9d7dded975924fc611
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
9,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, Sebastian Ullrich -/ import Lean.Data.OpenDecl import Lean.Hygiene import Lean.Modifiers import Lean.Exception namespace Lean /-! We use aliases to implement the `export <id> (<id>+)` command. An `export A (x)` in the namespace `B` produces an alias `B.x ~> A.x`. -/ abbrev AliasState := SMap Name (List Name) abbrev AliasEntry := Name × Name def addAliasEntry (s : AliasState) (e : AliasEntry) : AliasState := match s.find? e.1 with | none => s.insert e.1 [e.2] | some es => if es.elem e.2 then s else s.insert e.1 (e.2 :: es) builtin_initialize aliasExtension : SimplePersistentEnvExtension AliasEntry AliasState ← registerSimplePersistentEnvExtension { name := `aliasesExt, addEntryFn := addAliasEntry, addImportedFn := fun es => mkStateFromImportedEntries addAliasEntry {} es |>.switch } /- Add alias `a` for `e` -/ @[export lean_add_alias] def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) def getAliasState (env : Environment) : AliasState := aliasExtension.getState env def getAliases (env : Environment) (a : Name) : List Name := match aliasExtension.getState env |>.find? a with | none => [] | some es => es -- slower, but only used in the pretty printer def getRevAliases (env : Environment) (e : Name) : List Name := (aliasExtension.getState env).fold (fun as a es => if List.contains es e then a :: as else as) [] /- Global name resolution -/ namespace ResolveName /- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/ private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name := let resolvedId := ns ++ id let resolvedIds := getAliases env resolvedId if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then resolvedId :: resolvedIds else -- Check whether environment contains the private version. That is, `_private.<module_name>.ns.id`. let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then resolvedIdPrv :: resolvedIds else resolvedIds /- Check surrounding namespaces -/ private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name | ns@(Name.str p _ _) => match resolveQualifiedName env ns id with | [] => resolveUsingNamespace env id p | resolvedIds => resolvedIds | _ => [] /- Check exact name -/ private def resolveExact (env : Environment) (id : Name) : Option Name := if id.isAtomic then none else let resolvedId := id.replacePrefix rootNamespace Name.anonymous if env.contains resolvedId then some resolvedId else -- We also allow `_root` when accessing private declarations. -- If we change our minds, we should just replace `resolvedId` with `id` let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then some resolvedIdPrv else none /- Check `OpenDecl`s -/ private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name | [], resolvedIds => resolvedIds | OpenDecl.simple ns exs :: openDecls, resolvedIds => if exs.elem id then resolveOpenDecls env id openDecls resolvedIds else let newResolvedIds := resolveQualifiedName env ns id resolveOpenDecls env id openDecls (newResolvedIds ++ resolvedIds) | OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds => let resolvedIds := if openedId == id then resolvedId :: resolvedIds else if openedId.isPrefixOf id then let candidate := id.replacePrefix openedId resolvedId if env.contains candidate then candidate :: resolvedIds else resolvedIds else resolvedIds resolveOpenDecls env id openDecls resolvedIds def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop (id : Name) (projs : List String) : List (Name × List String) := match id with | Name.str p s _ => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match resolveUsingNamespace env id ns with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map fun id => (id, projs) | [] => match resolveExact env id with | some newId => [(newId, projs)] | none => let resolvedIds := if env.contains id then [id] else [] let idPrv := mkPrivateName env id let resolvedIds := if env.contains idPrv then [idPrv] ++ resolvedIds else resolvedIds let resolvedIds := resolveOpenDecls env id openDecls resolvedIds let resolvedIds := getAliases env id ++ resolvedIds match resolvedIds with | _ :: _ => resolvedIds.eraseDups.map fun id => (id, projs) | [] => loop p (s::projs) | _ => [] loop extractionResult.name [] /- Namespace resolution -/ def resolveNamespaceUsingScope (env : Environment) (n : Name) : Name → Option Name | Name.anonymous => if env.isNamespace n then some n else none | ns@(Name.str p _ _) => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope env n p | _ => unreachable! def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → Option Name | [] => none | OpenDecl.simple ns [] :: ds => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingOpenDecls env n ds | _ :: ds => resolveNamespaceUsingOpenDecls env n ds /- Given a name `id` try to find namespace it refers to. The resolution procedure works as follows 1- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`, then return `s_1 . ... . s_i ++ n` if it is the name of an existing namespace. We search "backwards". 2- If `id` is the extact name of an existing namespace, then return `id` 3- Finally, for each command `open N`, return `N ++ n` if it is the name of an existing namespace. We search "backwards" again. That is, we try the most recent `open` command first. We only consider simple `open` commands. -/ def resolveNamespace? (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : Option Name := match resolveNamespaceUsingScope env id ns with | some n => some n | none => match resolveNamespaceUsingOpenDecls env id openDecls with | some n => some n | none => none end ResolveName class MonadResolveName (m : Type → Type) where getCurrNamespace : m Name getOpenDecls : m (List OpenDecl) export MonadResolveName (getCurrNamespace getOpenDecls) instance (m n) [MonadLift m n] [MonadResolveName m] : MonadResolveName n where getCurrNamespace := liftM (m:=m) getCurrNamespace getOpenDecls := liftM (m:=m) getOpenDecls /- Given a name `n`, return a list of possible interpretations. Each interpretation is a pair `(declName, fieldList)`, where `declName` is the name of a declaration in the current environment, and `fieldList` are (potential) field names. The pair is needed because in Lean `.` may be part of a qualified name or a field (aka dot-notation). As an example, consider the following definitions ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalName x` => `[(Foo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w])]` After `open Foo open Boo`, we have - `resolveGlobalName x` => `[(Foo.x, []), (Boo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w]), (Boo.x, [z, w])]` -/ def resolveGlobalName [Monad m] [MonadResolveName m] [MonadEnv m] (id : Name) : m (List (Name × List String)) := do return ResolveName.resolveGlobalName (← getEnv) (← getCurrNamespace) (← getOpenDecls) id def resolveNamespace [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Name) : m Name := do match ResolveName.resolveNamespace? (← getEnv) (← getCurrNamespace) (← getOpenDecls) id with | some ns => return ns | none => throwError s!"unknown namespace '{id}'" /- Similar to `resolveGlobalName`, but discard any candidate whose `fieldList` is not empty. -/ def resolveGlobalConst [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m (List Name) := do let cs ← resolveGlobalName n let cs := cs.filter fun (_, fieldList) => fieldList.isEmpty if cs.isEmpty then throwUnknownConstant n return cs.map (·.1) def resolveGlobalConstNoOverload [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m Name := do let cs ← resolveGlobalConst n match cs with | [c] => pure c | _ => throwError s!"ambiguous identifier '{mkConst n}', possible interpretations: {cs.map mkConst}" end Lean
8ce6254e4ee66d390b571d71f1c393dc60587c7d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/sigma/lex.lean
237453601e331891328a214db4b3772cdff5181b
[]
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
3,279
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.sigma.basic import Mathlib.Lean3Lib.init.meta.default universes u v namespace Mathlib namespace psigma inductive lex {α : Sort u} {β : α → Sort v} (r : α → α → Prop) (s : (a : α) → β a → β a → Prop) : psigma β → psigma β → Prop where | left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → lex r s (mk a₁ b₁) (mk a₂ b₂) | right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → lex r s (mk a b₁) (mk a b₂) def lex_accessible {α : Sort u} {β : α → Sort v} {r : α → α → Prop} {s : (a : α) → β a → β a → Prop} {a : α} (aca : acc r a) (acb : ∀ (a : α), well_founded (s a)) (b : β a) : acc (lex r s) (mk a b) := sorry def lex_wf {α : Sort u} {β : α → Sort v} {r : α → α → Prop} {s : (a : α) → β a → β a → Prop} (ha : well_founded r) (hb : ∀ (x : α), well_founded (s x)) : well_founded (lex r s) := well_founded.intro fun (_x : psigma fun (a : α) => β a) => sorry def lex_ndep {α : Sort u} {β : Sort v} (r : α → α → Prop) (s : β → β → Prop) : (psigma fun (a : α) => β) → (psigma fun (a : α) => β) → Prop := lex r fun (a : α) => s def lex_ndep_wf {α : Sort u} {β : Sort v} {r : α → α → Prop} {s : β → β → Prop} (ha : well_founded r) (hb : well_founded s) : well_founded (lex_ndep r s) := well_founded.intro fun (_x : psigma fun (a : α) => β) => sorry inductive rev_lex {α : Sort u} {β : Sort v} (r : α → α → Prop) (s : β → β → Prop) : (psigma fun (a : α) => β) → (psigma fun (a : α) => β) → Prop where | left : ∀ {a₁ a₂ : α} (b : β), r a₁ a₂ → rev_lex r s (mk a₁ b) (mk a₂ b) | right : ∀ (a₁ : α) {b₁ : β} (a₂ : α) {b₂ : β}, s b₁ b₂ → rev_lex r s (mk a₁ b₁) (mk a₂ b₂) def rev_lex_accessible {α : Sort u} {β : Sort v} {r : α → α → Prop} {s : β → β → Prop} {b : β} (acb : acc s b) (aca : ∀ (a : α), acc r a) (a : α) : acc (rev_lex r s) (mk a b) := sorry def rev_lex_wf {α : Sort u} {β : Sort v} {r : α → α → Prop} {s : β → β → Prop} (ha : well_founded r) (hb : well_founded s) : well_founded (rev_lex r s) := well_founded.intro fun (_x : psigma fun (a : α) => β) => sorry def skip_left (α : Type u) {β : Type v} (s : β → β → Prop) : (psigma fun (a : α) => β) → (psigma fun (a : α) => β) → Prop := rev_lex empty_relation s def skip_left_wf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : well_founded s) : well_founded (skip_left α s) := rev_lex_wf empty_wf hb def mk_skip_left {α : Type u} {β : Type v} {b₁ : β} {b₂ : β} {s : β → β → Prop} (a₁ : α) (a₂ : α) (h : s b₁ b₂) : skip_left α s (mk a₁ b₁) (mk a₂ b₂) := rev_lex.right a₁ a₂ h protected instance has_well_founded {α : Type u} {β : α → Type v} [s₁ : has_well_founded α] [s₂ : (a : α) → has_well_founded (β a)] : has_well_founded (psigma β) := has_well_founded.mk (lex has_well_founded.r fun (a : α) => has_well_founded.r) sorry
f7c791e97eabd5fd5b91135262c6a38137db05dd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/kernelMVarBug.lean
b2f7b770e0f2433eb739c915e0e7d07eed86aab5
[ "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
217
lean
-- This example used to produce -- `error: (kernel) declaration has metavariables` -- Because we were not registering postponed instance metavariables def f {α : Type u} (a : α) : α := let g a b := a + b g a a
aecfb1e46c35d335aa84b69a823d8c8cfb46d7c2
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/try_for1.lean
11ceab09addad7e4784b9f050c77b13e431b5d52
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
394
lean
meta def f : nat → nat | n := f (n + 1) vm_eval try_for 100 (f 10) vm_eval try_for 1000 (f 10) meta def mk : nat → list nat | 0 := [] | (n+1) := n :: mk n example : true := begin tactic.fail_if_success (guard(to_bool (try_for 1 ((mk 1000)^.length) = some 1000))), constructor end example : true := begin guard (try_for 100 ((mk 1000)^.length) = some 1000), constructor end
7bb6d0fc20775374431cd46025c3d35ed79ca90c
63abd62053d479eae5abf4951554e1064a4c45b4
/src/linear_algebra/affine_space/affine_subspace.lean
87bf749d9b091fada13ebf111db80955fc1e724f
[ "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
44,291
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import linear_algebra.affine_space.basic import linear_algebra.tensor_product import data.set.intervals.unordered_interval /-! # Affine spaces This file defines affine subspaces (over modules) and the affine span of a set of points. ## Main definitions * `affine_subspace k P` is the type of affine subspaces. Unlike affine spaces, affine subspaces are allowed to be empty, and lemmas that do not apply to empty affine subspaces have `nonempty` hypotheses. There is a `complete_lattice` structure on affine subspaces. * `affine_subspace.direction` gives the `submodule` spanned by the pairwise differences of points in an `affine_subspace`. There are various lemmas relating to the set of vectors in the `direction`, and relating the lattice structure on affine subspaces to that on their directions. * `affine_span` gives the affine subspace spanned by a set of points, with `vector_span` giving its direction. `affine_span` is defined in terms of `span_points`, which gives an explicit description of the points contained in the affine span; `span_points` itself should generally only be used when that description is required, with `affine_span` being the main definition for other purposes. Two other descriptions of the affine span are proved equivalent: it is the `Inf` of affine subspaces containing the points, and (if `[nontrivial k]`) it contains exactly those points that are affine combinations of points in the given set. ## Implementation notes `out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## TODO * Coercions from an `affine_subspace` to the subtype of its points, and a corresponding `affine_space` instance on that subtype in the case of a nonempty subspace. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ noncomputable theory open_locale big_operators classical affine open set section variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) := rfl /-- `vector_span` is monotone. -/ lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ := submodule.span_mono (vsub_self_mono h) variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) := by rw [vector_span_def, vsub_empty, submodule.span_empty] variables {P} /-- The `vector_span` of a single point is `⊥`. -/ @[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ := by simp [vector_span_def] /-- The `s -ᵥ s` lies within the `vector_span k s`. -/ lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k s := vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k s := λ p, mem_span_points k p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ h, h.mono (subset_span_points _ _) } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_assoc], use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) : p1 -ᵥ p2 ∈ vector_span k s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k s, { apply (vector_span k s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k s).smul_mem (-1 : k) hv2 }, refine (vector_span k s).add_mem _ hv1v2, exact vsub_mem_vector_span k hp1a hp2a end end /-- An `affine_subspace k P` is a subset of an `affine_space V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier → c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace submodule variables {k V : Type*} [ring k] [add_comm_group V] [module k V] /-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/ def to_affine_subspace (p : submodule k V) : affine_subspace k V := { carrier := p, smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ } end submodule namespace affine_subspace variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] include V instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k P) : s.direction = vector_span k (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : submodule k V := { carrier := (s : set P) -ᵥ s, zero_mem' := begin cases h with p hp, exact (vsub_self p) ▸ vsub_mem_vsub hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩, rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩, rw [←vadd_vsub_assoc], refine vsub_mem_vsub _ hp4, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩, rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub _ hp2, exact s.smul_vsub_vadd_mem c hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) : (s.direction : set V) = (s : set P) -ᵥ s := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set h], exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩, λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩ end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k hp1 hp2 /-- Adding a vector to a point in a subspace produces a point in the subspace if and only if the vector is in the direction. -/ lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s ↔ v ∈ s.direction := ⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩ /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ p) '' s := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, p2, hp1, hp2, rfl⟩, exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _)⟩ }, { rintros v ⟨p2, hp2, rfl⟩, exact ⟨p2, p, hp2, hp, rfl⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ) p '' s := begin ext v, rw [submodule.mem_coe, ←submodule.neg_mem_iff, ←submodule.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_right hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_left hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, congr, exact h end /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end /-- Two affine subspaces with nonempty intersection are equal if and only if their directions are equal. -/ lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction := ⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩ /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_assoc] end } /-- An affine subspace constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩ /-- An affine subspace constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine subspace constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine subspace constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) : span_points k s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k s ≤ s1.direction := vector_span_mono k h, rw submodule.le_def at hs, rw ←submodule.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace section affine_span variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k P := { carrier := span_points k s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3 ((vector_span k s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k s : set P) = span_points k s := rfl /-- A set is contained in its affine span. -/ lemma subset_affine_span (s : set P) : s ⊆ affine_span k s := subset_span_points k s /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩, rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, submodule.mem_coe], exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1 (vsub_mem_vector_span k hp2 hp4)) hv2 }, { exact vector_span_mono k (subset_span_points k s) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s := mem_span_points k p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space V P] include S instance : complete_lattice (affine_subspace k P) := { sup := λ s1 s2, affine_span k (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2, s2.smul_vsub_vadd_mem c (set.mem_bInter_iff.1 hp1 s2 hs2) (set.mem_bInter_iff.1 hp2 s2 hs2) (set.mem_bInter_iff.1 hp3 s2 hs2)), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_bInter, .. partial_order.lift (coe : affine_subspace k P → set P) (λ _ _, ext) } instance : inhabited (affine_subspace k P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If an affine subspace is nonempty and contained in another with the same direction, they are equal. -/ lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P} (hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) : s₁ = s₂ := let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩ variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h))) (Inf_le (subset_span_points k _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) := { choice := λ s _, affine_span k s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k _ variables {P} /-- The affine span of a single point, coerced to a set, contains just that point. -/ @[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} := begin ext x, rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _, direction_affine_span], simp end /-- A point is in the affine span of a single point if and only if they are equal. -/ @[simp] lemma mem_affine_span_singleton (p1 p2 : P) : p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 := by simp [←mem_coe] /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ := rfl variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty] variables {k V P} /-- A nonempty affine subspace is `⊤` if and only if its direction is `⊤`. -/ @[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ := begin split, { intro hd, rw ←direction_top k V P at hd, refine ext_of_direction_eq hd _, simp [h] }, { rintro rfl, simp } end /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp)) end /-- If two affine subspaces have a point in common, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := begin ext v, rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂, ←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff] end /-- If two affine subspaces have a point in their inf, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2 /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact vector_span_mono k h end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw submodule.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw submodule.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end /-- Coercing a subspace to a set then taking the affine span produces the original subspace. -/ @[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s := begin refine le_antisymm _ (subset_span_points _ _), rintros p ⟨p1, hp1, v, hv, rfl⟩, exact vadd_mem_of_mem_direction hv hp1 end end affine_subspace section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace set /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, p2, hp, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, p, hp2, hp, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k s : set P).nonempty ↔ s.nonempty := span_points_nonempty k s variables {k} /-- Suppose a set of vectors spans `V`. Then a point `p`, together with those vectors added to `p`, spans `P`. -/ lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P) (h : submodule.span k (set.range (coe : s → V)) = ⊤) : affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ := begin convert ext_of_direction_eq _ ⟨p, mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)), mem_top k V p⟩, rw [direction_affine_span, direction_top, vector_span_eq_span_vsub_set_right k ((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h], apply submodule.span_mono, rintros v ⟨v', rfl⟩, use (v' : V) +ᵥ p, simp end variables (k) /-- `affine_span` is monotone. -/ lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ := span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _)) /-- Taking the affine span of a set, adding a point and taking the span again produces the same results as adding the point to the set and taking the span. -/ lemma affine_span_insert_affine_span (p : P) (ps : set P) : affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) := by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe] /-- If a point is in the affine span of a set, adding it to that set does not change the affine span. -/ lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) : affine_span k (insert p ps) = affine_span k ps := begin rw ←mem_coe at h, rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe] end end affine_space' namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The direction of the sup of two nonempty affine subspaces is the sup of the two directions and of any one difference between points in the two subspaces. -/ lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) : (s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ submodule.span k {p2 -ᵥ p1} := begin refine le_antisymm _ _, { change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _, rw ←mem_coe at hp1, rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1), submodule.span_le], rintros v ⟨p3, hp3, rfl⟩, cases hp3, { rw [sup_assoc, sup_comm, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw zero_add }, { rw [sup_assoc, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1], rw [and_comm, zero_add], use rfl, rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup], use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1, submodule.mem_span_singleton_self _] } }, { refine sup_le (sup_direction_le _ _) _, rw [direction_eq_vector_span, vector_span_def], exact Inf_le_Inf (λ p hp, set.subset.trans (set.singleton_subset_iff.2 (vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2)) (mem_span_points k p1 _ (set.mem_union_left _ hp1)))) hp) } end /-- The direction of the span of the result of adding a point to a nonempty affine subspace is the sup of the direction of that subspace and of any one difference between that point and a point in the subspace. -/ lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) : (affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction := begin rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2], change (s ⊔ affine_span k {p2}).direction = _, rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span], simp end /-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a point `p` is in the span of `s` with `p2` added if and only if it is a multiple of `p2 -ᵥ p1` added to a point in `s`. -/ lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) : p ∈ affine_span k (insert p2 (s : set P)) ↔ ∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 := begin rw ←mem_coe at hp1, rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)), direction_affine_span_insert hp1, submodule.mem_sup], split, { rintros ⟨v1, hv1, v2, hv2, hp⟩, rw submodule.mem_span_singleton at hv1, rcases hv1 with ⟨r, rfl⟩, use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1], symmetry' at hp, rw [←sub_eq_zero_iff_eq, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp, rw [hp, vadd_assoc] }, { rintros ⟨r, p3, hp3, rfl⟩, use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw [vadd_vsub_assoc, add_comm] } end end affine_subspace
5f7a9e06d9fa62aadf49f12117aa8ebccd288834
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/number_theory/cyclotomic/primitive_roots.lean
34ba1d7be7705435b9b274570f407824900f8bcc
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
25,544
lean
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Best, Riccardo Brasca, Eric Rodriguez -/ import data.pnat.prime import algebra.is_prime_pow import number_theory.cyclotomic.basic import ring_theory.adjoin.power_basis import ring_theory.polynomial.cyclotomic.eval import ring_theory.norm /-! # Primitive roots in cyclotomic fields If `is_cyclotomic_extension {n} A B`, we define an element `zeta n A B : B` that is (under certain assumptions) a primitive `n`-root of unity in `B` and we study its properties. We also prove related theorems under the more general assumption of just being a primitive root, for reasons described in the implementation details section. ## Main definitions * `is_cyclotomic_extension.zeta n A B`: if `is_cyclotomic_extension {n} A B`, than `zeta n A B` is an element of `B` that plays the role of a primitive `n`-th root of unity. * `is_primitive_root.power_basis`: if `K` and `L` are fields such that `is_cyclotomic_extension {n} K L`, then `is_primitive_root.power_basis` gives a K-power basis for L given a primitive root `ζ`. * `is_primitive_root.embeddings_equiv_primitive_roots`: the equivalence between `L →ₐ[K] A` and `primitive_roots n A` given by the choice of `ζ`. ## Main results * `is_cyclotomic_extension.zeta_primitive_root`: `zeta n A B` is a primitive `n`-th root of unity. * `is_cyclotomic_extension.finrank`: if `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the `finrank` of a cyclotomic extension is `n.totient`. * `is_primitive_root.norm_eq_one`: if `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), the norm of a primitive root is `1` if `n ≠ 2`. * `is_primitive_root.sub_one_norm_eq_eval_cyclotomic`: if `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the norm of `ζ - 1` is `eval 1 (cyclotomic n ℤ)`, for a primitive root ζ. We also prove the analogous of this result for `zeta`. * `is_primitive_root.pow_sub_one_norm_prime_pow_ne_two` : if `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime, then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` `p ^ (k - s + 1) ≠ 2`. See the following lemmas for similar results. We also prove the analogous of this result for `zeta`. * `is_primitive_root.sub_one_norm_prime_ne_two` : if `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is an odd prime, then the norm of `ζ - 1` is `p`. We also prove the analogous of this result for `zeta`. * `is_primitive_root.embeddings_equiv_primitive_roots`: the equivalence between `L →ₐ[K] A` and `primitive_roots n A` given by the choice of `ζ`. ## Implementation details `zeta n A B` is defined as any primitive root of unity in `B`, that exists by definition. It is not true in general that it is a root of `cyclotomic n B`, but this holds if `is_domain B` and `ne_zero (↑n : B)`. `zeta n A B` is defined using `exists.some`, which means we cannot control it. For example, in normal mathematics, we can demand that `(zeta p ℤ ℤ[ζₚ] : ℚ(ζₚ))` is equal to `zeta p ℚ ℚ(ζₚ)`, as we are just choosing "an arbitrary primitive root" and we can internally specify that our choices agree. This is not the case here, and it is indeed impossible to prove that these two are equal. Therefore, whenever possible, we prove our results for any primitive root, and only at the "final step", when we need to provide an "explicit" primitive root, we use `zeta`. -/ open polynomial algebra finset finite_dimensional is_cyclotomic_extension nat pnat set universes u v w z variables {p n : ℕ+} (A : Type w) (B : Type z) (K : Type u) {L : Type v} (C : Type w) variables [comm_ring A] [comm_ring B] [algebra A B] [is_cyclotomic_extension {n} A B] section zeta namespace is_cyclotomic_extension variables (n) /-- If `B` is a `n`-th cyclotomic extension of `A`, then `zeta n A B` is a primitive root of unity in `B`. -/ noncomputable def zeta : B := (exists_prim_root A $ set.mem_singleton n : ∃ r : B, is_primitive_root r n).some /-- `zeta n A B` is a primitive `n`-th root of unity. -/ @[simp] lemma zeta_spec : is_primitive_root (zeta n A B) n := classical.some_spec (exists_prim_root A (set.mem_singleton n) : ∃ r : B, is_primitive_root r n) lemma aeval_zeta [is_domain B] [ne_zero ((n : ℕ) : B)] : aeval (zeta n A B) (cyclotomic n A) = 0 := begin rw [aeval_def, ← eval_map, ← is_root.def, map_cyclotomic, is_root_cyclotomic_iff], exact zeta_spec n A B end lemma zeta_is_root [is_domain B] [ne_zero ((n : ℕ) : B)] : is_root (cyclotomic n B) (zeta n A B) := by { convert aeval_zeta n A B, rw [is_root.def, aeval_def, eval₂_eq_eval_map, map_cyclotomic] } lemma zeta_pow : (zeta n A B) ^ (n : ℕ) = 1 := (zeta_spec n A B).pow_eq_one end is_cyclotomic_extension end zeta section no_order variables [field K] [comm_ring L] [is_domain L] [algebra K L] [is_cyclotomic_extension {n} K L] {ζ : L} (hζ : is_primitive_root ζ n) namespace is_primitive_root variable {C} /-- The `power_basis` given by a primitive root `η`. -/ @[simps] protected noncomputable def power_basis : power_basis K L := power_basis.map (algebra.adjoin.power_basis $ integral {n} K L ζ) $ (subalgebra.equiv_of_eq _ _ (is_cyclotomic_extension.adjoin_primitive_root_eq_top hζ)).trans subalgebra.top_equiv lemma power_basis_gen_mem_adjoin_zeta_sub_one : (hζ.power_basis K).gen ∈ adjoin K ({ζ - 1} : set L) := begin rw [power_basis_gen, adjoin_singleton_eq_range_aeval, alg_hom.mem_range], exact ⟨X + 1, by simp⟩ end /-- The `power_basis` given by `η - 1`. -/ @[simps] noncomputable def sub_one_power_basis : power_basis K L := (hζ.power_basis K).of_gen_mem_adjoin (is_integral_sub (is_cyclotomic_extension.integral {n} K L ζ) is_integral_one) (hζ.power_basis_gen_mem_adjoin_zeta_sub_one _) variables {K} (C) -- We are not using @[simps] to avoid a timeout. /-- The equivalence between `L →ₐ[K] C` and `primitive_roots n C` given by a primitive root `ζ`. -/ noncomputable def embeddings_equiv_primitive_roots (C : Type*) [comm_ring C] [is_domain C] [algebra K C] (hirr : irreducible (cyclotomic n K)) : (L →ₐ[K] C) ≃ primitive_roots n C := ((hζ.power_basis K).lift_equiv).trans { to_fun := λ x, begin haveI := is_cyclotomic_extension.ne_zero' n K L, haveI hn := ne_zero.of_no_zero_smul_divisors K C n, refine ⟨x.1, _⟩, cases x, rwa [mem_primitive_roots n.pos, ←is_root_cyclotomic_iff, is_root.def, ←map_cyclotomic _ (algebra_map K C), hζ.minpoly_eq_cyclotomic_of_irreducible hirr, ←eval₂_eq_eval_map, ←aeval_def] end, inv_fun := λ x, begin haveI := is_cyclotomic_extension.ne_zero' n K L, haveI hn := ne_zero.of_no_zero_smul_divisors K C n, refine ⟨x.1, _⟩, cases x, rwa [aeval_def, eval₂_eq_eval_map, hζ.power_basis_gen K, ←hζ.minpoly_eq_cyclotomic_of_irreducible hirr, map_cyclotomic, ←is_root.def, is_root_cyclotomic_iff, ← mem_primitive_roots n.pos] end, left_inv := λ x, subtype.ext rfl, right_inv := λ x, subtype.ext rfl } @[simp] lemma embeddings_equiv_primitive_roots_apply_coe (C : Type*) [comm_ring C] [is_domain C] [algebra K C] (hirr : irreducible (cyclotomic n K)) (φ : L →ₐ[K] C) : (hζ.embeddings_equiv_primitive_roots C hirr φ : C) = φ ζ := rfl end is_primitive_root namespace is_cyclotomic_extension variables {K} (L) /-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the `finrank` of a cyclotomic extension is `n.totient`. -/ lemma finrank (hirr : irreducible (cyclotomic n K)) : finrank K L = (n : ℕ).totient := begin haveI := is_cyclotomic_extension.ne_zero' n K L, rw [((zeta_spec n K L).power_basis K).finrank, is_primitive_root.power_basis_dim, ←(zeta_spec n K L).minpoly_eq_cyclotomic_of_irreducible hirr, nat_degree_cyclotomic] end end is_cyclotomic_extension end no_order section norm namespace is_primitive_root section comm_ring variables [comm_ring L] {ζ : L} (hζ : is_primitive_root ζ n) variables {K} [field K] [algebra K L] /-- This mathematically trivial result is complementary to `norm_eq_one` below. -/ lemma norm_eq_neg_one_pow (hζ : is_primitive_root ζ 2) [is_domain L] : norm K ζ = (-1) ^ finrank K L := by rw [hζ.eq_neg_one_of_two_right, show -1 = algebra_map K L (-1), by simp, algebra.norm_algebra_map] include hζ /-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), the norm of a primitive root is `1` if `n ≠ 2`. -/ lemma norm_eq_one [is_domain L] [is_cyclotomic_extension {n} K L] (hn : n ≠ 2) (hirr : irreducible (cyclotomic n K)) : norm K ζ = 1 := begin haveI := is_cyclotomic_extension.ne_zero' n K L, by_cases h1 : n = 1, { rw [h1, one_coe, one_right_iff] at hζ, rw [hζ, show 1 = algebra_map K L 1, by simp, algebra.norm_algebra_map, one_pow] }, { replace h1 : 2 ≤ n, { by_contra' h, exact h1 (pnat.eq_one_of_lt_two h) }, rw [← hζ.power_basis_gen K, power_basis.norm_gen_eq_coeff_zero_minpoly, hζ.power_basis_gen K, ← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, cyclotomic_coeff_zero _ h1, mul_one, hζ.power_basis_dim K, ← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, nat_degree_cyclotomic], exact (totient_even $ h1.lt_of_ne hn.symm).neg_one_pow } end /-- If `K` is linearly ordered, the norm of a primitive root is `1` if `n` is odd. -/ lemma norm_eq_one_of_linearly_ordered {K : Type*} [linear_ordered_field K] [algebra K L] (hodd : odd (n : ℕ)) : norm K ζ = 1 := begin have hz := congr_arg (norm K) ((is_primitive_root.iff_def _ n).1 hζ).1, rw [←(algebra_map K L).map_one , algebra.norm_algebra_map, one_pow, map_pow, ←one_pow ↑n] at hz, exact strict_mono.injective hodd.strict_mono_pow hz end lemma norm_of_cyclotomic_irreducible [is_domain L] [is_cyclotomic_extension {n} K L] (hirr : irreducible (cyclotomic n K)) : norm K ζ = ite (n = 2) (-1) 1 := begin split_ifs with hn, { unfreezingI {subst hn}, convert norm_eq_neg_one_pow hζ, erw [is_cyclotomic_extension.finrank _ hirr, totient_two, pow_one], all_goals { apply_instance } }, { exact hζ.norm_eq_one hn hirr } end end comm_ring section field variables [field L] {ζ : L} (hζ : is_primitive_root ζ n) variables {K} [field K] [algebra K L] include hζ /-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the norm of `ζ - 1` is `eval 1 (cyclotomic n ℤ)`. -/ lemma sub_one_norm_eq_eval_cyclotomic [is_cyclotomic_extension {n} K L] (h : 2 < (n : ℕ)) (hirr : irreducible (cyclotomic n K)) : norm K (ζ - 1) = ↑(eval 1 (cyclotomic n ℤ)) := begin haveI := is_cyclotomic_extension.ne_zero' n K L, let E := algebraic_closure L, obtain ⟨z, hz⟩ := is_alg_closed.exists_root _ (degree_cyclotomic_pos n E n.pos).ne.symm, apply (algebra_map K E).injective, letI := finite_dimensional {n} K L, letI := is_galois n K L, rw [norm_eq_prod_embeddings], conv_lhs { congr, skip, funext, rw [← neg_sub, alg_hom.map_neg, alg_hom.map_sub, alg_hom.map_one, neg_eq_neg_one_mul] }, rw [prod_mul_distrib, prod_const, card_univ, alg_hom.card, is_cyclotomic_extension.finrank L hirr, (totient_even h).neg_one_pow, one_mul], have : finset.univ.prod (λ (σ : L →ₐ[K] E), 1 - σ ζ) = eval 1 (cyclotomic' n E), { rw [cyclotomic', eval_prod, ← @finset.prod_attach E E, ← univ_eq_attach], refine fintype.prod_equiv (hζ.embeddings_equiv_primitive_roots E hirr) _ _ (λ σ, _), simp }, haveI : ne_zero ((n : ℕ) : E) := (ne_zero.of_no_zero_smul_divisors K _ (n : ℕ)), rw [this, cyclotomic', ← cyclotomic_eq_prod_X_sub_primitive_roots (is_root_cyclotomic_iff.1 hz), ← map_cyclotomic_int, (algebra_map K E).map_int_cast, ←int.cast_one, eval_int_cast_map, ring_hom.eq_int_cast, int.cast_id] end /-- If `is_prime_pow (n : ℕ)`, `n ≠ 2` and `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the norm of `ζ - 1` is `(n : ℕ).min_fac`. -/ lemma sub_one_norm_is_prime_pow (hn : is_prime_pow (n : ℕ)) [is_cyclotomic_extension {n} K L] (hirr : irreducible (cyclotomic (n : ℕ) K)) (h : n ≠ 2) : norm K (ζ - 1) = (n : ℕ).min_fac := begin have := (coe_lt_coe 2 _).1 (lt_of_le_of_ne (succ_le_of_lt (is_prime_pow.one_lt hn)) (function.injective.ne pnat.coe_injective h).symm), letI hprime : fact ((n : ℕ).min_fac.prime) := ⟨min_fac_prime (is_prime_pow.ne_one hn)⟩, rw [sub_one_norm_eq_eval_cyclotomic hζ this hirr], nth_rewrite 0 [← is_prime_pow.min_fac_pow_factorization_eq hn], obtain ⟨k, hk⟩ : ∃ k, ((n : ℕ).factorization) (n : ℕ).min_fac = k + 1 := exists_eq_succ_of_ne_zero (((n : ℕ).factorization.mem_support_to_fun (n : ℕ).min_fac).1 $ factor_iff_mem_factorization.2 $ (mem_factors (is_prime_pow.ne_zero hn)).2 ⟨hprime.out, min_fac_dvd _⟩), simp [hk, sub_one_norm_eq_eval_cyclotomic hζ this hirr], end omit hζ variable {A} lemma minpoly_sub_one_eq_cyclotomic_comp [algebra K A] [is_domain A] {ζ : A} [is_cyclotomic_extension {n} K A] (hζ : is_primitive_root ζ n) (h : irreducible (polynomial.cyclotomic n K)) : minpoly K (ζ - 1) = (cyclotomic n K).comp (X + 1) := begin haveI := is_cyclotomic_extension.ne_zero' n K A, rw [show ζ - 1 = ζ + (algebra_map K A (-1)), by simp [sub_eq_add_neg], minpoly.add_algebra_map (is_cyclotomic_extension.integral {n} K A ζ), hζ.minpoly_eq_cyclotomic_of_irreducible h], simp end local attribute [instance] is_cyclotomic_extension.finite_dimensional local attribute [instance] is_cyclotomic_extension.is_galois /-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime, then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` if `p ^ (k - s + 1) ≠ 2`. See the next lemmas for similar results. -/ lemma pow_sub_one_norm_prime_pow_ne_two {k s : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1))) [hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L] (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (hs : s ≤ k) (htwo : p ^ (k - s + 1) ≠ 2) : norm K (ζ ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) := begin have hirr₁ : irreducible (cyclotomic (p ^ (k - s + 1)) K) := cyclotomic_irreducible_pow_of_irreducible_pow hpri.1 (by linarith) hirr, rw ←pnat.pow_coe at hirr₁, let η := ζ ^ ((p : ℕ) ^ s) - 1, let η₁ : K⟮η⟯ := intermediate_field.adjoin_simple.gen K η, have hη : is_primitive_root (η + 1) (p ^ (k + 1 - s)), { rw [sub_add_cancel], refine is_primitive_root.pow (p ^ (k + 1)).pos hζ _, rw [pnat.pow_coe, ← pow_add, add_comm s, nat.sub_add_cancel (le_trans hs (nat.le_succ k))] }, haveI : is_cyclotomic_extension {p ^ (k - s + 1)} K K⟮η⟯, { suffices : is_cyclotomic_extension {p ^ (k - s + 1)} K K⟮η + 1⟯.to_subalgebra, { have H : K⟮η + 1⟯.to_subalgebra = K⟮η⟯.to_subalgebra, { simp only [intermediate_field.adjoin_simple_to_subalgebra_of_integral (is_cyclotomic_extension.integral {p ^ (k + 1)} K L _)], refine subalgebra.ext (λ x, ⟨λ hx, adjoin_le _ hx, λ hx, adjoin_le _ hx⟩), { simp only [set.singleton_subset_iff, set_like.mem_coe], exact subalgebra.add_mem _ (subset_adjoin (mem_singleton η)) (subalgebra.one_mem _) }, { simp only [set.singleton_subset_iff, set_like.mem_coe], nth_rewrite 0 [← add_sub_cancel η 1], refine subalgebra.sub_mem _ (subset_adjoin (mem_singleton _)) (subalgebra.one_mem _) } }, rw [H] at this, exact this }, rw [intermediate_field.adjoin_simple_to_subalgebra_of_integral (is_cyclotomic_extension.integral {p ^ (k + 1)} K L _)], have hη' : is_primitive_root (η + 1) ↑(p ^ (k + 1 - s)) := by simpa using hη, convert hη'.adjoin_is_cyclotomic_extension K, rw [nat.sub_add_comm hs] }, replace hη : is_primitive_root (η₁ + 1) ↑(p ^ (k - s + 1)), { apply coe_submonoid_class_iff.1, convert hη, rw [nat.sub_add_comm hs, pow_coe] }, rw [norm_eq_norm_adjoin K], { have H := hη.sub_one_norm_is_prime_pow _ hirr₁ htwo, swap, { rw [pnat.pow_coe], exact hpri.1.is_prime_pow.pow (nat.succ_ne_zero _) }, rw [add_sub_cancel] at H, rw [H, coe_coe], congr, { rw [pnat.pow_coe, nat.pow_min_fac, hpri.1.min_fac_eq], exact nat.succ_ne_zero _ }, have := finite_dimensional.finrank_mul_finrank K K⟮η⟯ L, rw [is_cyclotomic_extension.finrank L hirr, is_cyclotomic_extension.finrank K⟮η⟯ hirr₁, pnat.pow_coe, pnat.pow_coe, nat.totient_prime_pow hpri.out (k - s).succ_pos, nat.totient_prime_pow hpri.out k.succ_pos, mul_comm _ (↑p - 1), mul_assoc, mul_comm (↑p ^ (k.succ - 1))] at this, replace this := nat.eq_of_mul_eq_mul_left (tsub_pos_iff_lt.2 (nat.prime.one_lt hpri.out)) this, have Hex : k.succ - 1 = (k - s).succ - 1 + s, { simp only [nat.succ_sub_succ_eq_sub, tsub_zero], exact (nat.sub_add_cancel hs).symm }, rw [Hex, pow_add] at this, exact nat.eq_of_mul_eq_mul_left (pow_pos hpri.out.pos _) this }, all_goals { apply_instance } end /-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime, then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` if `p ≠ 2`. -/ lemma pow_sub_one_norm_prime_ne_two {k : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1))) [hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L] (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) {s : ℕ} (hs : s ≤ k) (hodd : p ≠ 2) : norm K (ζ ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) := begin refine hζ.pow_sub_one_norm_prime_pow_ne_two hirr hs (λ h, _), rw [← pnat.coe_inj, pnat.coe_bit0, pnat.one_coe, pnat.pow_coe, ← pow_one 2] at h, replace h := eq_of_prime_pow_eq (prime_iff.1 hpri.out) (prime_iff.1 nat.prime_two) ((k - s).succ_pos) h, rw [← pnat.one_coe, ← pnat.coe_bit0, pnat.coe_inj] at h, exact hodd h end /-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is an odd prime, then the norm of `ζ - 1` is `p`. -/ lemma sub_one_norm_prime_ne_two {k : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1))) [hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L] (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (h : p ≠ 2) : norm K (ζ - 1) = p := by simpa using hζ.pow_sub_one_norm_prime_ne_two hirr k.zero_le h /-- If `irreducible (cyclotomic p K)` (in particular for `K = ℚ`) and `p` is an odd prime, then the norm of `ζ - 1` is `p`. -/ lemma sub_one_norm_prime [hpri : fact (p : ℕ).prime] [hcyc : is_cyclotomic_extension {p} K L] (hζ: is_primitive_root ζ p) (hirr : irreducible (cyclotomic p K)) (h : p ≠ 2) : norm K (ζ - 1) = p := begin replace hirr : irreducible (cyclotomic (↑(p ^ (0 + 1)) : ℕ) K) := by simp [hirr], replace hζ : is_primitive_root ζ (↑(p ^ (0 + 1)) : ℕ) := by simp [hζ], haveI : is_cyclotomic_extension {p ^ (0 + 1)} K L := by simp [hcyc], simpa using sub_one_norm_prime_ne_two hζ hirr h end /-- If `irreducible (cyclotomic (2 ^ (k + 1)) K)` (in particular for `K = ℚ`), then the norm of `ζ ^ (2 ^ k) - 1` is `(-2) ^ (2 ^ k)`. -/ lemma pow_sub_one_norm_two {k : ℕ} (hζ : is_primitive_root ζ (2 ^ (k + 1))) [is_cyclotomic_extension {2 ^ (k + 1)} K L] (hirr : irreducible (cyclotomic (2 ^ (k + 1)) K)) : norm K (ζ ^ (2 ^ k) - 1) = (-2) ^ (2 ^ k) := begin have := hζ.pow_of_dvd (λ h, two_ne_zero (pow_eq_zero h)) (pow_dvd_pow 2 (le_succ k)), rw [nat.pow_div (le_succ k) zero_lt_two, nat.succ_sub (le_refl k), nat.sub_self, pow_one] at this, have H : (-1 : L) - (1 : L) = algebra_map K L (-2), { simp only [_root_.map_neg, map_bit0, _root_.map_one], ring }, replace hirr : irreducible (cyclotomic (2 ^ (k + 1) : ℕ+) K) := by simp [hirr], rw [this.eq_neg_one_of_two_right, H, algebra.norm_algebra_map, is_cyclotomic_extension.finrank L hirr, pow_coe, pnat.coe_bit0, one_coe, totient_prime_pow nat.prime_two (zero_lt_succ k), succ_sub_succ_eq_sub, tsub_zero, mul_one] end /-- If `irreducible (cyclotomic (2 ^ k) K)` (in particular for `K = ℚ`) and `k` is at least `2`, then the norm of `ζ - 1` is `2`. -/ lemma sub_one_norm_two {k : ℕ} (hζ : is_primitive_root ζ (2 ^ k)) (hk : 2 ≤ k) [H : is_cyclotomic_extension {2 ^ k} K L] (hirr : irreducible (cyclotomic (2 ^ k) K)) : norm K (ζ - 1) = 2 := begin have : 2 < (2 ^ k : ℕ+), { simp only [← coe_lt_coe, pnat.coe_bit0, one_coe, pow_coe], nth_rewrite 0 [← pow_one 2], exact pow_lt_pow one_lt_two (lt_of_lt_of_le one_lt_two hk) }, replace hirr : irreducible (cyclotomic (2 ^ k : ℕ+) K) := by simp [hirr], replace hζ : is_primitive_root ζ (2 ^ k : ℕ+) := by simp [hζ], obtain ⟨k₁, hk₁⟩ := exists_eq_succ_of_ne_zero ((lt_of_lt_of_le zero_lt_two hk).ne.symm), simpa [hk₁] using sub_one_norm_eq_eval_cyclotomic hζ this hirr, end /-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime, then the norm of `ζ ^ (p ^ s) - 1` is `p ^ (p ^ s)` if `1 ≤ k`. -/ lemma pow_sub_one_norm_prime_pow_of_one_le {k s : ℕ} (hζ : is_primitive_root ζ ↑(p ^ (k + 1))) [hpri : fact (p : ℕ).prime] [hcycl : is_cyclotomic_extension {p ^ (k + 1)} K L] (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (hs : s ≤ k) (hk : 1 ≤ k) : norm K (ζ ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) := begin by_cases htwo : p ^ (k - s + 1) = 2, { have hp : p = 2, { rw [← pnat.coe_inj, pnat.coe_bit0, pnat.one_coe, pnat.pow_coe, ← pow_one 2] at htwo, replace htwo := eq_of_prime_pow_eq (prime_iff.1 hpri.out) (prime_iff.1 nat.prime_two) (succ_pos _) htwo, rwa [show 2 = ((2 : ℕ+) : ℕ), by simp, pnat.coe_inj] at htwo }, replace hs : s = k, { rw [hp, ← pnat.coe_inj, pnat.pow_coe, pnat.coe_bit0, pnat.one_coe] at htwo, nth_rewrite 1 [← pow_one 2] at htwo, replace htwo := nat.pow_right_injective rfl.le htwo, rw [add_left_eq_self, nat.sub_eq_zero_iff_le] at htwo, refine le_antisymm hs htwo }, simp only [hs, hp, pnat.coe_bit0, one_coe, coe_coe, cast_bit0, cast_one, pow_coe] at ⊢ hζ hirr hcycl, haveI := hcycl, obtain ⟨k₁, hk₁⟩ := nat.exists_eq_succ_of_ne_zero (one_le_iff_ne_zero.1 hk), rw [hζ.pow_sub_one_norm_two hirr], rw [hk₁, pow_succ, pow_mul, neg_eq_neg_one_mul, mul_pow, neg_one_sq, one_mul, ← pow_mul, ← pow_succ] }, { exact hζ.pow_sub_one_norm_prime_pow_ne_two hirr hs htwo } end end field end is_primitive_root namespace is_cyclotomic_extension open is_primitive_root variables {K} (L) [field K] [field L] [algebra K L] /-- If `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), the norm of `zeta n K L` is `1` if `n` is odd. -/ lemma norm_zeta_eq_one [is_cyclotomic_extension {n} K L] (hn : n ≠ 2) (hirr : irreducible (cyclotomic n K)) : norm K (zeta n K L) = 1 := (zeta_spec n K L).norm_eq_one hn hirr /-- If `is_prime_pow (n : ℕ)`, `n ≠ 2` and `irreducible (cyclotomic n K)` (in particular for `K = ℚ`), then the norm of `zeta n K L - 1` is `(n : ℕ).min_fac`. -/ lemma is_prime_pow_norm_zeta_sub_one (hn : is_prime_pow (n : ℕ)) [is_cyclotomic_extension {n} K L] (hirr : irreducible (cyclotomic (n : ℕ) K)) (h : n ≠ 2) : norm K (zeta n K L - 1) = (n : ℕ).min_fac := (zeta_spec n K L).sub_one_norm_is_prime_pow hn hirr h /-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is a prime, then the norm of `(zeta (p ^ (k + 1)) K L) ^ (p ^ s) - 1` is `p ^ (p ^ s)` if `p ^ (k - s + 1) ≠ 2`. -/ lemma prime_ne_two_pow_norm_zeta_pow_sub_one {k : ℕ} [hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L] (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) {s : ℕ} (hs : s ≤ k) (htwo : p ^ (k - s + 1) ≠ 2) : norm K ((zeta (p ^ (k + 1)) K L) ^ ((p : ℕ) ^ s) - 1) = p ^ ((p : ℕ) ^ s) := (zeta_spec _ K L).pow_sub_one_norm_prime_pow_ne_two hirr hs htwo /-- If `irreducible (cyclotomic (p ^ (k + 1)) K)` (in particular for `K = ℚ`) and `p` is an odd prime, then the norm of `zeta (p ^ (k + 1)) K L - 1` is `p`. -/ lemma prime_ne_two_pow_norm_zeta_sub_one {k : ℕ} [hpri : fact (p : ℕ).prime] [is_cyclotomic_extension {p ^ (k + 1)} K L] (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (h : p ≠ 2) : norm K (zeta (p ^ (k + 1)) K L - 1) = p := (zeta_spec _ K L).sub_one_norm_prime_ne_two hirr h /-- If `irreducible (cyclotomic p K)` (in particular for `K = ℚ`) and `p` is an odd prime, then the norm of `zeta p K L - 1` is `p`. -/ lemma prime_ne_two_norm_zeta_sub_one [hpri : fact (p : ℕ).prime] [hcyc : is_cyclotomic_extension {p} K L] (hirr : irreducible (cyclotomic p K)) (h : p ≠ 2) : norm K (zeta p K L - 1) = p := (zeta_spec _ K L).sub_one_norm_prime hirr h /-- If `irreducible (cyclotomic (2 ^ k) K)` (in particular for `K = ℚ`) and `k` is at least `2`, then the norm of `zeta (2 ^ k) K L - 1` is `2`. -/ lemma two_pow_norm_zeta_sub_one {k : ℕ} (hk : 2 ≤ k) [is_cyclotomic_extension {2 ^ k} K L] (hirr : irreducible (cyclotomic (2 ^ k) K)) : norm K (zeta (2 ^ k) K L - 1) = 2 := sub_one_norm_two (zeta_spec (2 ^ k) K L) hk hirr end is_cyclotomic_extension end norm
b0c287f0f1d444a7f7a9788deb7a5d5a899dd688
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/data/buffer/basic.lean
ac2e1e1a183cb03c58d3bf843ea81e89a1665b87
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
1,825
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon Traversable instance for buffers. -/ import data.buffer data.array.lemmas import category.traversable.instances data.equiv.basic tactic.ext namespace buffer open function variables {α : Type*} variables {buf buf' : buffer α} variables {xs : list α} @[extensionality] lemma ext (h : to_list buf = to_list buf') : buf = buf' := begin cases buf with n buf, cases buf' with n' buf', simp [to_list,to_array] at h, have : n = n', { rw [← array.to_list_length buf,← array.to_list_length buf',h] }, subst n', have := array.to_list_to_array buf, have := array.to_list_to_array buf', rw h at *, congr, apply eq_of_heq, transitivity; [ symmetry, skip ]; assumption, end @[simp] lemma to_list_append_list : to_list (append_list buf xs) = to_list buf ++ xs := by induction xs generalizing buf; simp! [*]; cases buf; simp! [to_list,to_array] @[simp] lemma append_list_mk_buffer : append_list mk_buffer xs = array.to_buffer (list.to_array xs) := by ext 1 with x; simp [array.to_buffer,to_list,to_list_append_list]; induction xs; [refl,skip]; simp [to_array]; refl def list_equiv_buffer (α : Type*) : list α ≃ buffer α := begin refine { to_fun := list.to_buffer, inv_fun := buffer.to_list, .. }; simp [left_inverse,function.right_inverse], { intro x, induction x, refl, simp [list.to_buffer,append_list], rw ← x_ih, refl }, { intro x, cases x, simp [to_list,to_array,list.to_buffer], congr, simp, refl, apply array.to_list_to_array } end instance : traversable buffer := equiv.traversable list_equiv_buffer instance : is_lawful_traversable buffer := equiv.is_lawful_traversable list_equiv_buffer end buffer
a6488e5d97ff5bc69fa2d240f36921599b80bdf5
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/set/countable.lean
d34c75984800cc55030fb125ee04c3399daded6b
[ "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
8,072
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 Countable sets. -/ import data.equiv.list data.set.finite logic.function data.set.function noncomputable theory open function set encodable open classical (hiding some) open_locale classical universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace set /-- Countable sets A set is countable if there exists an encoding of the set into the natural numbers. An encoding is an injection with a partial inverse, which can be viewed as a constructive analogue of countability. (For the most part, theorems about `countable` will be classical and `encodable` will be constructive.) -/ def countable (s : set α) : Prop := nonempty (encodable s) lemma countable_iff_exists_injective {s : set α} : countable s ↔ ∃f:s → ℕ, injective f := ⟨λ ⟨h⟩, by exactI ⟨encode, encode_injective⟩, λ ⟨f, h⟩, ⟨⟨f, partial_inv f, partial_inv_left h⟩⟩⟩ lemma countable_iff_exists_inj_on {s : set α} : countable s ↔ ∃ f : α → ℕ, inj_on f s := countable_iff_exists_injective.trans ⟨λ ⟨f, hf⟩, ⟨λ a, if h : a ∈ s then f ⟨a, h⟩ else 0, λ a b as bs h, congr_arg subtype.val $ hf $ by simpa [as, bs] using h⟩, λ ⟨f, hf⟩, ⟨_, inj_on_iff_injective.1 hf⟩⟩ lemma countable_iff_exists_surjective [ne : nonempty α] {s : set α} : countable s ↔ ∃f:ℕ → α, s ⊆ range f := ⟨λ ⟨h⟩, by inhabit α; exactI ⟨λ n, ((decode s n).map subtype.val).iget, λ a as, ⟨encode (⟨a, as⟩ : s), by simp [encodek]⟩⟩, λ ⟨f, hf⟩, ⟨⟨ λ x, inv_fun f x.1, λ n, if h : f n ∈ s then some ⟨f n, h⟩ else none, λ ⟨x, hx⟩, begin have := inv_fun_eq (hf hx), dsimp at this ⊢, simp [this, hx] end⟩⟩⟩ /-- A non-empty set is countable iff there exists a surjection from the natural numbers onto the subtype induced by the set. -/ lemma countable_iff_exists_surjective_to_subtype {s : set α} (hs : s.nonempty) : countable s ↔ ∃ f : ℕ → s, surjective f := have inhabited s, from ⟨classical.choice hs.to_subtype⟩, have countable s → ∃ f : ℕ → s, surjective f, from assume ⟨h⟩, by exactI ⟨λ n, (decode s n).iget, λ a, ⟨encode a, by simp [encodek]⟩⟩, have (∃ f : ℕ → s, surjective f) → countable s, from assume ⟨f, fsurj⟩, ⟨⟨inv_fun f, option.some ∘ f, by intro h; simp [(inv_fun_eq (fsurj h) : f (inv_fun f h) = h)]⟩⟩, by split; assumption def countable.to_encodable {s : set α} : countable s → encodable s := classical.choice lemma countable_encodable' (s : set α) [H : encodable s] : countable s := ⟨H⟩ lemma countable_encodable [encodable α] (s : set α) : countable s := ⟨by apply_instance⟩ lemma exists_surjective_of_countable {s : set α} (hs : s.nonempty) (hc : countable s) : ∃f:ℕ → α, s = range f := begin rcases hs with ⟨x, hx⟩, letI : encodable s := countable.to_encodable hc, letI : inhabited s := ⟨⟨x, hx⟩⟩, have : countable (univ : set s) := countable_encodable _, rcases countable_iff_exists_surjective.1 this with ⟨g, hg⟩, have : range g = univ := univ_subset_iff.1 hg, use coe ∘ g, rw [range_comp, this], simp end @[simp] lemma countable_empty : countable (∅ : set α) := ⟨⟨λ x, x.2.elim, λ n, none, λ x, x.2.elim⟩⟩ @[simp] lemma countable_singleton (a : α) : countable ({a} : set α) := ⟨of_equiv _ (equiv.set.singleton a)⟩ lemma countable_subset {s₁ s₂ : set α} (h : s₁ ⊆ s₂) : countable s₂ → countable s₁ | ⟨H⟩ := ⟨@of_inj _ _ H _ (embedding_of_subset h).2⟩ lemma countable_image {s : set α} (f : α → β) (hs : countable s) : countable (f '' s) := let f' : s → f '' s := λ⟨a, ha⟩, ⟨f a, mem_image_of_mem f ha⟩ in have hf' : surjective f', from assume ⟨b, a, ha, hab⟩, ⟨⟨a, ha⟩, subtype.eq hab⟩, ⟨@encodable.of_inj _ _ hs.to_encodable (surj_inv hf') (injective_surj_inv hf')⟩ lemma countable_range [encodable α] (f : α → β) : countable (range f) := by rw ← image_univ; exact countable_image _ (countable_encodable _) lemma countable_of_injective_of_countable_image {s : set α} {f : α → β} (hf : inj_on f s) (hs : countable (f '' s)) : countable s := let ⟨g, hg⟩ := countable_iff_exists_inj_on.1 hs in countable_iff_exists_inj_on.2 ⟨g ∘ f, hg.comp hf (maps_to_image _ _)⟩ lemma countable_Union {t : α → set β} [encodable α] (ht : ∀a, countable (t a)) : countable (⋃a, t a) := by haveI := (λ a, (ht a).to_encodable); rw Union_eq_range_sigma; apply countable_range lemma countable_bUnion {s : set α} {t : α → set β} (hs : countable s) (ht : ∀a∈s, countable (t a)) : countable (⋃a∈s, t a) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact countable_Union (by simpa using ht) end lemma countable_sUnion {s : set (set α)} (hs : countable s) (h : ∀a∈s, countable a) : countable (⋃₀ s) := by rw sUnion_eq_bUnion; exact countable_bUnion hs h lemma countable_Union_Prop {p : Prop} {t : p → set β} (ht : ∀h:p, countable (t h)) : countable (⋃h:p, t h) := by by_cases p; simp [h, ht] lemma countable_union {s₁ s₂ : set α} (h₁ : countable s₁) (h₂ : countable s₂) : countable (s₁ ∪ s₂) := by rw union_eq_Union; exact countable_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma countable_insert {s : set α} {a : α} (h : countable s) : countable (insert a s) := by rw [set.insert_eq]; from countable_union (countable_singleton _) h lemma countable_finite {s : set α} : finite s → countable s | ⟨h⟩ := nonempty_of_trunc (by exactI trunc_encodable_of_fintype s) lemma countable_set_of_finite_subset {s : set α} : countable s → countable {t | finite t ∧ t ⊆ s} | ⟨h⟩ := begin resetI, refine countable_subset _ (countable_range (λ t : finset s, {a | ∃ h:a ∈ s, subtype.mk a h ∈ t})), rintro t ⟨⟨ht⟩, ts⟩, refine ⟨finset.univ.map (embedding_of_subset ts), set.ext $ λ a, _⟩, simp, split, { rintro ⟨as, b, bt, e⟩, cases congr_arg subtype.val e, exact bt }, { exact λ h, ⟨ts h, _, h, rfl⟩ } end lemma countable_pi {π : α → Type*} [fintype α] {s : Πa, set (π a)} (hs : ∀a, countable (s a)) : countable {f : Πa, π a | ∀a, f a ∈ s a} := countable_subset (show {f : Πa, π a | ∀a, f a ∈ s a} ⊆ range (λf : Πa, s a, λa, (f a).1), from assume f hf, ⟨λa, ⟨f a, hf a⟩, funext $ assume a, rfl⟩) $ have trunc (encodable (Π (a : α), s a)), from @encodable.fintype_pi α _ _ _ (assume a, (hs a).to_encodable), trunc.induction_on this $ assume h, @countable_range _ _ h _ lemma countable_prod {s : set α} {t : set β} (hs : countable s) (ht : countable t) : countable (set.prod s t) := begin haveI : encodable s := hs.to_encodable, haveI : encodable t := ht.to_encodable, haveI : encodable (s × t) := by apply_instance, have : range (λp, ⟨p.1, p.2⟩ : s × t → α × β) = set.prod s t, { ext z, rcases z with ⟨x, y⟩, simp only [exists_prop, set.mem_range, set_coe.exists, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, subtype.coe_mk, prod.exists], split, { rintros ⟨x', x's, y', y't, x'x, y'y⟩, simp [x'x.symm, y'y.symm, x's, y't] }, { rintros ⟨xs, yt⟩, exact ⟨x, xs, y, yt, rfl, rfl⟩ }}, rw ← this, exact countable_range _ end section enumerate /-- Enumerate elements in a countable set.-/ def enumerate_countable {s : set α} (h : countable s) (default : α) : ℕ → α := assume n, match @encodable.decode s (h.to_encodable) n with | (some y) := y | (none) := default end lemma subset_range_enumerate {s : set α} (h : countable s) (default : α) : s ⊆ range (enumerate_countable h default) := assume x hx, ⟨@encodable.encode s h.to_encodable ⟨x, hx⟩, by simp [enumerate_countable, encodable.encodek]⟩ end enumerate end set
2edd1a0a63deac95b30ba62162b2958c4903ce00
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/meta/smt/ematch.lean
1577cabe545f3228c638b31a8fd611f259d8017c
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,071
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.congruence_closure import init.meta.attribute init.meta.simp_tactic open tactic /- Heuristic instantiation lemma -/ meta constant hinst_lemma : Type meta constant hinst_lemmas : Type /- (mk_core m e as_simp), m is used to decide which definitions will be unfolded in patterns. If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion as a pattern. -/ meta constant hinst_lemma.mk_core : transparency → expr → bool → tactic hinst_lemma meta constant hinst_lemma.mk_from_decl_core : transparency → name → bool → tactic hinst_lemma meta constant hinst_lemma.pp : hinst_lemma → tactic format meta constant hinst_lemma.id : hinst_lemma → name meta instance : has_to_tactic_format hinst_lemma := ⟨hinst_lemma.pp⟩ meta def hinst_lemma.mk (h : expr) : tactic hinst_lemma := hinst_lemma.mk_core reducible h ff meta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma := hinst_lemma.mk_from_decl_core reducible h ff meta constant hinst_lemmas.mk : hinst_lemmas meta constant hinst_lemmas.add : hinst_lemmas → hinst_lemma → hinst_lemmas meta constant hinst_lemmas.fold {α : Type} : hinst_lemmas → α → (hinst_lemma → α → α) → α meta constant hinst_lemmas.merge : hinst_lemmas → hinst_lemmas → hinst_lemmas meta def mk_hinst_singleton : hinst_lemma → hinst_lemmas := hinst_lemmas.add hinst_lemmas.mk meta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format := let tac := s.fold (return format.nil) (λ h tac, do hpp ← h.pp, r ← tac, if r.is_nil then return hpp else return (r ++ to_fmt "," ++ format.line ++ hpp)) in do r ← tac, return $ format.cbrace (format.group r) meta instance : has_to_tactic_format hinst_lemmas := ⟨hinst_lemmas.pp⟩ open tactic private meta def add_lemma (m : transparency) (as_simp : bool) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas := do h ← hinst_lemma.mk_from_decl_core m h as_simp, return $ hs.add h meta def to_hinst_lemmas_core (m : transparency) : bool → list name → hinst_lemmas → tactic hinst_lemmas | as_simp [] hs := return hs | as_simp (n::ns) hs := let add n := add_lemma m as_simp n hs >>= to_hinst_lemmas_core as_simp ns in do /- First check if n is the name of a function with equational lemmas associated with it -/ eqns ← tactic.get_eqn_lemmas_for tt n, match eqns with | [] := do /- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/ add n | _ := do p ← is_prop_decl n, if p then add n /- n is a proposition -/ else do /- Add equational lemmas to resulting hinst_lemmas -/ new_hs ← to_hinst_lemmas_core tt eqns hs, to_hinst_lemmas_core as_simp ns new_hs end meta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command := do let t := `(caching_user_attribute hinst_lemmas), let v := `({name := attr_name, descr := "hinst_lemma attribute", mk_cache := λ ns, to_hinst_lemmas_core reducible as_simp ns hinst_lemmas.mk, dependencies := [`reducibility] } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name → command | [] := skip | (n::ns) := (mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns) <|> (do type ← infer_type (expr.const n []), let expected := `(caching_user_attribute hinst_lemmas), (is_def_eq type expected <|> fail ("failed to create hinst_lemma attribute '" ++ n.to_string ++ "', declaration already exists and has different type.")), mk_hinst_lemma_attrs_core ns) meta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name → hinst_lemmas → tactic hinst_lemmas | [] hs := return hs | (attr::attrs) hs := do ns ← attribute.get_instances attr, new_hs ← to_hinst_lemmas_core m as_simp ns hs, merge_hinst_lemma_attrs attrs new_hs /-- Create a new "cached" attribute (attr_name : caching_user_attribute hinst_lemmas). It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with attr_name, attrs_name, and simp_attr_names. For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern. -/ meta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command := do mk_hinst_lemma_attrs_core ff attr_names, mk_hinst_lemma_attrs_core tt simp_attr_names, let t := `(caching_user_attribute hinst_lemmas), let v := `({name := attr_name, descr := "hinst_lemma attribute set", mk_cache := λ ns, let aux1 : list name := attr_names, aux2 : list name := simp_attr_names in do { hs₁ ← to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk, hs₂ ← merge_hinst_lemma_attrs reducible ff aux1 hs₁, merge_hinst_lemma_attrs reducible tt aux2 hs₂}, dependencies := [`reducibility] ++ attr_names ++ simp_attr_names } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas := do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute hinst_lemmas) cnst, caching_user_attribute.get_cache attr structure ematch_config := (max_instances : nat := 10000) (max_generation : nat := 10) /- Ematching -/ meta constant ematch_state : Type meta constant ematch_state.mk : ematch_config → ematch_state meta constant ematch_state.internalize : ematch_state → expr → tactic ematch_state namespace tactic meta constant ematch_core : transparency → cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) meta constant ematch_all_core : transparency → cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) meta def ematch : cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_core reducible meta def ematch_all : cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_all_core reducible end tactic
2a3c0e51809e2ac39a4509ad6b47329b9d4c7974
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0216.lean
fcbd47e817e5297a2cdb1ef4522883e185b6a0a3
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
102
lean
example (x y : ℕ) (h : x = y) : y = x := begin revert x y, intros, symmetry, assumption end
d8f14233af4f99636a75bbce152f62fb797c6d8d
bb31430994044506fa42fd667e2d556327e18dfe
/src/category_theory/filtered.lean
2dfb410c9718d9a7ba8a9b0c8f6cd6000c17d705
[ "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
28,299
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import category_theory.fin_category import category_theory.limits.cones import category_theory.adjunction.basic import category_theory.category.preorder import category_theory.category.ulift /-! # Filtered categories A category is filtered if every finite diagram admits a cocone. We give a simple characterisation of this condition as 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. Filtered colimits are often better behaved than arbitrary colimits. See `category_theory/limits/types` for some details. Filtered categories are nice because colimits indexed by filtered categories tend to be easier to describe than general colimits (and more often preserved by functors). In this file we show that any functor from a finite category to a filtered category admits a cocone: * `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)` More generally, for any finite collection of objects and morphisms between them in a filtered category (even if not closed under composition) there exists some object `Z` receiving maps from all of them, so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute. This formulation is often more useful in practice and is available via `sup_exists`, which takes a finset of objects, and an indexed family (indexed by source and target) of finsets of morphisms. Furthermore, we give special support for two diagram categories: The `bowtie` and the `tulip`. This is because these shapes show up in the proofs that forgetful functors of algebraic categories (e.g. `Mon`, `CommRing`, ...) preserve filtered colimits. All of the above API, except for the `bowtie` and the `tulip`, is also provided for cofiltered categories. ## See also In `category_theory.limits.filtered_colimit_commutes_finite_limit` we show that filtered colimits commute with finite limits. -/ open function -- declare the `v`'s first; see `category_theory.category` for an explanation universes w v v₁ u u₁ u₂ namespace category_theory variables (C : Type u) [category.{v} C] /-- A category `is_filtered_or_empty` if 1. for every pair of objects there exists another object "to the right", and 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal. -/ class is_filtered_or_empty : Prop := (cocone_objs : ∀ (X Y : C), ∃ Z (f : X ⟶ Z) (g : Y ⟶ Z), true) (cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ Z (h : Y ⟶ Z), f ≫ h = g ≫ h) /-- A category `is_filtered` if 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. See <https://stacks.math.columbia.edu/tag/002V>. (They also define a diagram being filtered.) -/ class is_filtered extends is_filtered_or_empty C : Prop := [nonempty : nonempty C] @[priority 100] instance is_filtered_or_empty_of_semilattice_sup (α : Type u) [semilattice_sup α] : is_filtered_or_empty α := { cocone_objs := λ X Y, ⟨X ⊔ Y, hom_of_le le_sup_left, hom_of_le le_sup_right, trivial⟩, cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, (by ext)⟩, } @[priority 100] instance is_filtered_of_semilattice_sup_nonempty (α : Type u) [semilattice_sup α] [nonempty α] : is_filtered α := {} @[priority 100] instance is_filtered_or_empty_of_directed_le (α : Type u) [preorder α] [is_directed α (≤)] : is_filtered_or_empty α := { cocone_objs := λ X Y, let ⟨Z, h1, h2⟩ := exists_ge_ge X Y in ⟨Z, hom_of_le h1, hom_of_le h2, trivial⟩, cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, by simp⟩ } @[priority 100] instance is_filtered_of_directed_le_nonempty (α : Type u) [preorder α] [is_directed α (≤)] [nonempty α] : is_filtered α := {} -- Sanity checks example (α : Type u) [semilattice_sup α] [order_bot α] : is_filtered α := by apply_instance example (α : Type u) [semilattice_sup α] [order_top α] : is_filtered α := by apply_instance instance : is_filtered (discrete punit) := { cocone_objs := λ X Y, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, ⟨⟨dec_trivial⟩⟩, trivial⟩, cocone_maps := λ X Y f g, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, dec_trivial⟩, nonempty := ⟨⟨punit.star⟩⟩ } namespace is_filtered section allow_empty variables {C} [is_filtered_or_empty C] lemma cocone_objs : ∀ (X Y : C), ∃ Z (f : X ⟶ Z) (g : Y ⟶ Z), true := is_filtered_or_empty.cocone_objs lemma cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ Z (h : Y ⟶ Z), f ≫ h = g ≫ h := is_filtered_or_empty.cocone_maps /-- `max j j'` is an arbitrary choice of object to the right of both `j` and `j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def max (j j' : C) : C := (cocone_objs j j').some /-- `left_to_max j j'` is an arbitrary choice of morphism from `j` to `max j j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def left_to_max (j j' : C) : j ⟶ max j j' := (cocone_objs j j').some_spec.some /-- `right_to_max j j'` is an arbitrary choice of morphism from `j'` to `max j j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def right_to_max (j j' : C) : j' ⟶ max j j' := (cocone_objs j j').some_spec.some_spec.some /-- `coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq {j j' : C} (f f' : j ⟶ j') : C := (cocone_maps f f').some /-- `coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq_hom {j j' : C} (f f' : j ⟶ j') : j' ⟶ coeq f f' := (cocone_maps f f').some_spec.some /-- `coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that `f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. -/ @[simp, reassoc] lemma coeq_condition {j j' : C} (f f' : j ⟶ j') : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f' := (cocone_maps f f').some_spec.some_spec end allow_empty section nonempty open category_theory.limits variables {C} [is_filtered C] /-- Any finite collection of objects in a filtered category has an object "to the right". -/ lemma sup_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (X ⟶ S) := begin classical, apply finset.induction_on O, { exact ⟨is_filtered.nonempty.some, (by rintros - ⟨⟩)⟩, }, { rintros X O' nm ⟨S', w'⟩, use max X S', rintros Y mY, obtain rfl|h := eq_or_ne Y X, { exact ⟨left_to_max _ _⟩, }, { exact ⟨(w' (finset.mem_of_mem_insert_of_ne mY h)).some ≫ right_to_max _ _⟩, }, } end variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) /-- Given any `finset` of objects `{X, ...}` and indexed collection of `finset`s of morphisms `{f, ...}` in `C`, there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`, such that the triangles commute: `f ≫ T Y = T X`, for `f : X ⟶ Y` in the `finset`. -/ lemma sup_exists : ∃ (S : C) (T : Π {X : C}, X ∈ O → (X ⟶ S)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}, (⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → f ≫ T mY = T mX := begin classical, apply finset.induction_on H, { obtain ⟨S, f⟩ := sup_objs_exists O, refine ⟨S, λ X mX, (f mX).some, _⟩, rintros - - - - - ⟨⟩, }, { rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩, refine ⟨coeq (f ≫ T' mY) (T' mX), λ Z mZ, T' mZ ≫ coeq_hom (f ≫ T' mY) (T' mX), _⟩, intros X' Y' mX' mY' f' mf', rw [←category.assoc], by_cases h : X = X' ∧ Y = Y', { rcases h with ⟨rfl, rfl⟩, by_cases hf : f = f', { subst hf, apply coeq_condition, }, { rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, }, { rw @w' _ _ mX' mY' f' _, apply finset.mem_of_mem_insert_of_ne mf', contrapose! h, obtain ⟨rfl, h⟩ := h, rw [heq_iff_eq, psigma.mk.inj_iff] at h, exact ⟨rfl, h.1.symm⟩ }, }, end /-- An arbitrary choice of object "to the right" of a finite collection of objects `O` and morphisms `H`, making all the triangles commute. -/ noncomputable def sup : C := (sup_exists O H).some /-- The morphisms to `sup O H`. -/ noncomputable def to_sup {X : C} (m : X ∈ O) : X ⟶ sup O H := (sup_exists O H).some_spec.some m /-- The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute. -/ lemma to_sup_commutes {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y} (mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) : f ≫ to_sup O H mY = to_sup O H mX := (sup_exists O H).some_spec.some_spec mX mY mf variables {J : Type v} [small_category J] [fin_category J] /-- If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`, there exists a cocone over `F`. -/ lemma cocone_nonempty (F : J ⥤ C) : _root_.nonempty (cocone F) := begin classical, let O := (finset.univ.image F.obj), let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y, ⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))), obtain ⟨Z, f, w⟩ := sup_exists O H, refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩, intros j j' g, dsimp, simp only [category.comp_id], apply w, simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left, exists_prop_of_true, finset.mem_image], exact ⟨j, rfl, j', g, (by simp)⟩, end /-- An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`. -/ noncomputable def cocone (F : J ⥤ C) : cocone F := (cocone_nonempty F).some variables {D : Type u₁} [category.{v₁} D] /-- If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered. -/ lemma of_right_adjoint {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D := { cocone_objs := λ X Y, ⟨_, h.hom_equiv _ _ (left_to_max _ _), h.hom_equiv _ _ (right_to_max _ _), ⟨⟩⟩, cocone_maps := λ X Y f g, ⟨_, h.hom_equiv _ _ (coeq_hom _ _), by rw [← h.hom_equiv_naturality_left, ← h.hom_equiv_naturality_left, coeq_condition]⟩, nonempty := is_filtered.nonempty.map R.obj } /-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/ lemma of_is_right_adjoint (R : C ⥤ D) [is_right_adjoint R] : is_filtered D := of_right_adjoint (adjunction.of_right_adjoint R) /-- Being filtered is preserved by equivalence of categories. -/ lemma of_equivalence (h : C ≌ D) : is_filtered D := of_right_adjoint h.symm.to_adjunction end nonempty section special_shapes variables {C} [is_filtered_or_empty C] /-- `max₃ j₁ j₂ j₃` is an arbitrary choice of object to the right of `j₁`, `j₂` and `j₃`, whose existence is ensured by `is_filtered`. -/ noncomputable def max₃ (j₁ j₂ j₃ : C) : C := max (max j₁ j₂) j₃ /-- `first_to_max₃ j₁ j₂ j₃` is an arbitrary choice of morphism from `j₁` to `max₃ j₁ j₂ j₃`, whose existence is ensured by `is_filtered`. -/ noncomputable def first_to_max₃ (j₁ j₂ j₃ : C) : j₁ ⟶ max₃ j₁ j₂ j₃ := left_to_max j₁ j₂ ≫ left_to_max (max j₁ j₂) j₃ /-- `second_to_max₃ j₁ j₂ j₃` is an arbitrary choice of morphism from `j₂` to `max₃ j₁ j₂ j₃`, whose existence is ensured by `is_filtered`. -/ noncomputable def second_to_max₃ (j₁ j₂ j₃ : C) : j₂ ⟶ max₃ j₁ j₂ j₃ := right_to_max j₁ j₂ ≫ left_to_max (max j₁ j₂) j₃ /-- `third_to_max₃ j₁ j₂ j₃` is an arbitrary choice of morphism from `j₃` to `max₃ j₁ j₂ j₃`, whose existence is ensured by `is_filtered`. -/ noncomputable def third_to_max₃ (j₁ j₂ j₃ : C) : j₃ ⟶ max₃ j₁ j₂ j₃ := right_to_max (max j₁ j₂) j₃ /-- `coeq₃ f g h`, for morphisms `f g h : j₁ ⟶ j₂`, is an arbitrary choice of object which admits a morphism `coeq₃_hom f g h : j₂ ⟶ coeq₃ f g h` such that `coeq₃_condition₁`, `coeq₃_condition₂` and `coeq₃_condition₃` are satisfied. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq₃ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : C := coeq (coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h)) (coeq_hom g h ≫ right_to_max (coeq f g) (coeq g h)) /-- `coeq₃_hom f g h`, for morphisms `f g h : j₁ ⟶ j₂`, is an arbitrary choice of morphism `j₂ ⟶ coeq₃ f g h` such that `coeq₃_condition₁`, `coeq₃_condition₂` and `coeq₃_condition₃` are satisfied. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq₃_hom {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : j₂ ⟶ coeq₃ f g h := coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h) ≫ coeq_hom (coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h)) (coeq_hom g h ≫ right_to_max (coeq f g) (coeq g h)) lemma coeq₃_condition₁ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : f ≫ coeq₃_hom f g h = g ≫ coeq₃_hom f g h := by rw [coeq₃_hom, reassoc_of (coeq_condition f g)] lemma coeq₃_condition₂ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : g ≫ coeq₃_hom f g h = h ≫ coeq₃_hom f g h := begin dsimp [coeq₃_hom], slice_lhs 2 4 { rw [← category.assoc, coeq_condition _ _] }, slice_rhs 2 4 { rw [← category.assoc, coeq_condition _ _] }, slice_lhs 1 3 { rw [← category.assoc, coeq_condition _ _] }, simp only [category.assoc], end lemma coeq₃_condition₃ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : f ≫ coeq₃_hom f g h = h ≫ coeq₃_hom f g h := eq.trans (coeq₃_condition₁ f g h) (coeq₃_condition₂ f g h) /-- For every span `j ⟵ i ⟶ j'`, there exists a cocone `j ⟶ k ⟵ j'` such that the square commutes. -/ lemma span {i j j' : C} (f : i ⟶ j) (f' : i ⟶ j') : ∃ (k : C) (g : j ⟶ k) (g' : j' ⟶ k), f ≫ g = f' ≫ g' := let ⟨K, G, G', _⟩ := cocone_objs j j', ⟨k, e, he⟩ := cocone_maps (f ≫ G) (f' ≫ G') in ⟨k, G ≫ e, G' ≫ e, by simpa only [← category.assoc]⟩ /-- Given a "bowtie" of morphisms ``` j₁ j₂ |\ /| | \/ | | /\ | |/ \∣ vv vv k₁ k₂ ``` in a filtered category, we can construct an object `s` and two morphisms from `k₁` and `k₂` to `s`, making the resulting squares commute. -/ lemma bowtie {j₁ j₂ k₁ k₂ : C} (f₁ : j₁ ⟶ k₁) (g₁ : j₁ ⟶ k₂) (f₂ : j₂ ⟶ k₁) (g₂ : j₂ ⟶ k₂) : ∃ (s : C) (α : k₁ ⟶ s) (β : k₂ ⟶ s), f₁ ≫ α = g₁ ≫ β ∧ f₂ ≫ α = g₂ ≫ β := begin obtain ⟨t, k₁t, k₂t, ht⟩ := span f₁ g₁, obtain ⟨s, ts, hs⟩ := cocone_maps (f₂ ≫ k₁t) (g₂ ≫ k₂t), simp_rw category.assoc at hs, exact ⟨s, k₁t ≫ ts, k₂t ≫ ts, by rw reassoc_of ht, hs⟩, end /-- Given a "tulip" of morphisms ``` j₁ j₂ j₃ |\ / \ / | | \ / \ / | | vv vv | \ k₁ k₂ / \ / \ / \ / \ / v v l ``` in a filtered category, we can construct an object `s` and three morphisms from `k₁`, `k₂` and `l` to `s`, making the resulting squares commute. -/ lemma tulip {j₁ j₂ j₃ k₁ k₂ l : C} (f₁ : j₁ ⟶ k₁) (f₂ : j₂ ⟶ k₁) (f₃ : j₂ ⟶ k₂) (f₄ : j₃ ⟶ k₂) (g₁ : j₁ ⟶ l) (g₂ : j₃ ⟶ l) : ∃ (s : C) (α : k₁ ⟶ s) (β : l ⟶ s) (γ : k₂ ⟶ s), f₁ ≫ α = g₁ ≫ β ∧ f₂ ≫ α = f₃ ≫ γ ∧ f₄ ≫ γ = g₂ ≫ β := begin obtain ⟨l', k₁l, k₂l, hl⟩ := span f₂ f₃, obtain ⟨s, ls, l's, hs₁, hs₂⟩ := bowtie g₁ (f₁ ≫ k₁l) g₂ (f₄ ≫ k₂l), refine ⟨s, k₁l ≫ l's, ls, k₂l ≫ l's, _, by rw reassoc_of hl, _⟩; simp only [hs₁, hs₂, category.assoc], end end special_shapes end is_filtered /-- A category `is_cofiltered_or_empty` if 1. for every pair of objects there exists another object "to the left", and 2. for every pair of parallel morphisms there exists a morphism to the left so the compositions are equal. -/ class is_cofiltered_or_empty : Prop := (cone_objs : ∀ (X Y : C), ∃ W (f : W ⟶ X) (g : W ⟶ Y), true) (cone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ W (h : W ⟶ X), h ≫ f = h ≫ g) /-- A category `is_cofiltered` if 1. for every pair of objects there exists another object "to the left", 2. for every pair of parallel morphisms there exists a morphism to the left so the compositions are equal, and 3. there exists some object. See <https://stacks.math.columbia.edu/tag/04AZ>. -/ class is_cofiltered extends is_cofiltered_or_empty C : Prop := [nonempty : nonempty C] @[priority 100] instance is_cofiltered_or_empty_of_semilattice_inf (α : Type u) [semilattice_inf α] : is_cofiltered_or_empty α := { cone_objs := λ X Y, ⟨X ⊓ Y, hom_of_le inf_le_left, hom_of_le inf_le_right, trivial⟩, cone_maps := λ X Y f g, ⟨X, 𝟙 _, (by ext)⟩, } @[priority 100] instance is_cofiltered_of_semilattice_inf_nonempty (α : Type u) [semilattice_inf α] [nonempty α] : is_cofiltered α := {} @[priority 100] instance is_cofiltered_or_empty_of_directed_ge (α : Type u) [preorder α] [is_directed α (≥)] : is_cofiltered_or_empty α := { cone_objs := λ X Y, let ⟨Z, hX, hY⟩ := exists_le_le X Y in ⟨Z, hom_of_le hX, hom_of_le hY, trivial⟩, cone_maps := λ X Y f g, ⟨X, 𝟙 _, by simp⟩ } @[priority 100] instance is_cofiltered_of_directed_ge_nonempty (α : Type u) [preorder α] [is_directed α (≥)] [nonempty α] : is_cofiltered α := {} -- Sanity checks example (α : Type u) [semilattice_inf α] [order_bot α] : is_cofiltered α := by apply_instance example (α : Type u) [semilattice_inf α] [order_top α] : is_cofiltered α := by apply_instance instance : is_cofiltered (discrete punit) := { cone_objs := λ X Y, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, ⟨⟨dec_trivial⟩⟩, trivial⟩, cone_maps := λ X Y f g, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, dec_trivial⟩, nonempty := ⟨⟨punit.star⟩⟩ } namespace is_cofiltered section allow_empty variables {C} [is_cofiltered_or_empty C] lemma cone_objs : ∀ (X Y : C), ∃ W (f : W ⟶ X) (g : W ⟶ Y), true := is_cofiltered_or_empty.cone_objs lemma cone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ W (h : W ⟶ X), h ≫ f = h ≫ g := is_cofiltered_or_empty.cone_maps /-- `min j j'` is an arbitrary choice of object to the left of both `j` and `j'`, whose existence is ensured by `is_cofiltered`. -/ noncomputable def min (j j' : C) : C := (cone_objs j j').some /-- `min_to_left j j'` is an arbitrary choice of morphism from `min j j'` to `j`, whose existence is ensured by `is_cofiltered`. -/ noncomputable def min_to_left (j j' : C) : min j j' ⟶ j := (cone_objs j j').some_spec.some /-- `min_to_right j j'` is an arbitrary choice of morphism from `min j j'` to `j'`, whose existence is ensured by `is_cofiltered`. -/ noncomputable def min_to_right (j j' : C) : min j j' ⟶ j' := (cone_objs j j').some_spec.some_spec.some /-- `eq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object which admits a morphism `eq_hom f f' : eq f f' ⟶ j` such that `eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`. Its existence is ensured by `is_cofiltered`. -/ noncomputable def eq {j j' : C} (f f' : j ⟶ j') : C := (cone_maps f f').some /-- `eq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism `eq_hom f f' : eq f f' ⟶ j` such that `eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`. Its existence is ensured by `is_cofiltered`. -/ noncomputable def eq_hom {j j' : C} (f f' : j ⟶ j') : eq f f' ⟶ j := (cone_maps f f').some_spec.some /-- `eq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that `eq_hom f f' ≫ f = eq_hom f f' ≫ f'`. -/ @[simp, reassoc] lemma eq_condition {j j' : C} (f f' : j ⟶ j') : eq_hom f f' ≫ f = eq_hom f f' ≫ f' := (cone_maps f f').some_spec.some_spec /-- For every cospan `j ⟶ i ⟵ j'`, there exists a cone `j ⟵ k ⟶ j'` such that the square commutes. -/ lemma cospan {i j j' : C} (f : j ⟶ i) (f' : j' ⟶ i) : ∃ (k : C) (g : k ⟶ j) (g' : k ⟶ j'), g ≫ f = g' ≫ f' := let ⟨K, G, G', _⟩ := cone_objs j j', ⟨k, e, he⟩ := cone_maps (G ≫ f) (G' ≫ f') in ⟨k, e ≫ G, e ≫ G', by simpa only [category.assoc] using he⟩ lemma _root_.category_theory.functor.ranges_directed (F : C ⥤ Type*) (j : C) : directed (⊇) (λ (f : Σ' i, i ⟶ j), set.range (F.map f.2)) := λ ⟨i, ij⟩ ⟨k, kj⟩, let ⟨l, li, lk, e⟩ := cospan ij kj in by refine ⟨⟨l, lk ≫ kj⟩, e ▸ _, _⟩; simp_rw F.map_comp; apply set.range_comp_subset_range end allow_empty section nonempty open category_theory.limits variables {C} [is_cofiltered C] /-- Any finite collection of objects in a cofiltered category has an object "to the left". -/ lemma inf_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (S ⟶ X) := begin classical, apply finset.induction_on O, { exact ⟨is_cofiltered.nonempty.some, (by rintros - ⟨⟩)⟩, }, { rintros X O' nm ⟨S', w'⟩, use min X S', rintros Y mY, obtain rfl|h := eq_or_ne Y X, { exact ⟨min_to_left _ _⟩, }, { exact ⟨min_to_right _ _ ≫ (w' (finset.mem_of_mem_insert_of_ne mY h)).some⟩, }, } end variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) /-- Given any `finset` of objects `{X, ...}` and indexed collection of `finset`s of morphisms `{f, ...}` in `C`, there exists an object `S`, with a morphism `T X : S ⟶ X` from each `X`, such that the triangles commute: `T X ≫ f = T Y`, for `f : X ⟶ Y` in the `finset`. -/ lemma inf_exists : ∃ (S : C) (T : Π {X : C}, X ∈ O → (S ⟶ X)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}, (⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → T mX ≫ f = T mY := begin classical, apply finset.induction_on H, { obtain ⟨S, f⟩ := inf_objs_exists O, refine ⟨S, λ X mX, (f mX).some, _⟩, rintros - - - - - ⟨⟩, }, { rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩, refine ⟨eq (T' mX ≫ f) (T' mY), λ Z mZ, eq_hom (T' mX ≫ f) (T' mY) ≫ T' mZ, _⟩, intros X' Y' mX' mY' f' mf', rw [category.assoc], by_cases h : X = X' ∧ Y = Y', { rcases h with ⟨rfl, rfl⟩, by_cases hf : f = f', { subst hf, apply eq_condition, }, { rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, }, { rw @w' _ _ mX' mY' f' _, apply finset.mem_of_mem_insert_of_ne mf', contrapose! h, obtain ⟨rfl, h⟩ := h, rw [heq_iff_eq, psigma.mk.inj_iff] at h, exact ⟨rfl, h.1.symm⟩ }, }, end /-- An arbitrary choice of object "to the left" of a finite collection of objects `O` and morphisms `H`, making all the triangles commute. -/ noncomputable def inf : C := (inf_exists O H).some /-- The morphisms from `inf O H`. -/ noncomputable def inf_to {X : C} (m : X ∈ O) : inf O H ⟶ X := (inf_exists O H).some_spec.some m /-- The triangles consisting of a morphism in `H` and the maps from `inf O H` commute. -/ lemma inf_to_commutes {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y} (mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) : inf_to O H mX ≫ f = inf_to O H mY := (inf_exists O H).some_spec.some_spec mX mY mf variables {J : Type w} [small_category J] [fin_category J] /-- If we have `is_cofiltered C`, then for any functor `F : J ⥤ C` with `fin_category J`, there exists a cone over `F`. -/ lemma cone_nonempty (F : J ⥤ C) : _root_.nonempty (cone F) := begin classical, let O := (finset.univ.image F.obj), let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y, ⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))), obtain ⟨Z, f, w⟩ := inf_exists O H, refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩, intros j j' g, dsimp, simp only [category.id_comp], symmetry, apply w, simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left, exists_prop_of_true, finset.mem_image], exact ⟨j, rfl, j', g, (by simp)⟩, end /-- An arbitrary choice of cone over `F : J ⥤ C`, for `fin_category J` and `is_cofiltered C`. -/ noncomputable def cone (F : J ⥤ C) : cone F := (cone_nonempty F).some variables {D : Type u₁} [category.{v₁} D] /-- If `C` is cofiltered, and we have a functor `L : C ⥤ D` with a right adjoint, then `D` is cofiltered. -/ lemma of_left_adjoint {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) : is_cofiltered D := { cone_objs := λ X Y, ⟨L.obj (min (R.obj X) (R.obj Y)), (h.hom_equiv _ X).symm (min_to_left _ _), (h.hom_equiv _ Y).symm (min_to_right _ _), ⟨⟩⟩, cone_maps := λ X Y f g, ⟨L.obj (eq (R.map f) (R.map g)), (h.hom_equiv _ _).symm (eq_hom _ _), by rw [← h.hom_equiv_naturality_right_symm, ← h.hom_equiv_naturality_right_symm, eq_condition]⟩, nonempty := is_cofiltered.nonempty.map L.obj } /-- If `C` is cofiltered, and we have a left adjoint functor `L : C ⥤ D`, then `D` is cofiltered. -/ lemma of_is_left_adjoint (L : C ⥤ D) [is_left_adjoint L] : is_cofiltered D := of_left_adjoint (adjunction.of_left_adjoint L) /-- Being cofiltered is preserved by equivalence of categories. -/ lemma of_equivalence (h : C ≌ D) : is_cofiltered D := of_left_adjoint h.to_adjunction end nonempty end is_cofiltered section opposite open opposite instance is_cofiltered_op_of_is_filtered [is_filtered C] : is_cofiltered Cᵒᵖ := { cone_objs := λ X Y, ⟨op (is_filtered.max X.unop Y.unop), (is_filtered.left_to_max _ _).op, (is_filtered.right_to_max _ _).op, trivial⟩, cone_maps := λ X Y f g, ⟨op (is_filtered.coeq f.unop g.unop), (is_filtered.coeq_hom _ _).op, begin rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, exact is_filtered.coeq_condition f.unop g.unop, end⟩, nonempty := ⟨op is_filtered.nonempty.some⟩ } instance is_filtered_op_of_is_cofiltered [is_cofiltered C] : is_filtered Cᵒᵖ := { cocone_objs := λ X Y, ⟨op (is_cofiltered.min X.unop Y.unop), (is_cofiltered.min_to_left X.unop Y.unop).op, (is_cofiltered.min_to_right X.unop Y.unop).op, trivial⟩, cocone_maps := λ X Y f g, ⟨op (is_cofiltered.eq f.unop g.unop), (is_cofiltered.eq_hom f.unop g.unop).op, begin rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, exact is_cofiltered.eq_condition f.unop g.unop, end⟩, nonempty := ⟨op is_cofiltered.nonempty.some⟩ } end opposite section ulift instance [is_filtered C] : is_filtered (ulift.{u₂} C) := is_filtered.of_equivalence ulift.equivalence instance [is_cofiltered C] : is_cofiltered (ulift.{u₂} C) := is_cofiltered.of_equivalence ulift.equivalence instance [is_filtered C] : is_filtered (ulift_hom C) := is_filtered.of_equivalence ulift_hom.equiv instance [is_cofiltered C] : is_cofiltered (ulift_hom C) := is_cofiltered.of_equivalence ulift_hom.equiv instance [is_filtered C] : is_filtered (as_small C) := is_filtered.of_equivalence as_small.equiv instance [is_cofiltered C] : is_cofiltered (as_small C) := is_cofiltered.of_equivalence as_small.equiv end ulift end category_theory
bc82c69413369a4fd0ee9298ebf535df354c9b15
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/smt_tests3.lean
791c6b7624b51f5339ee4ec3e989cf501f50ed8b
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
670
lean
def f : nat → nat | 0 := 1 | (n+1) := f n + 1 lemma ex(a : nat) : f a ≠ 0 := begin induction a, dsimp [f], intro x, contradiction, dsimp [f], change nat.succ (f a) ≠ 0, apply nat.succ_ne_zero end lemma ex2 (a : nat) : f a ≠ 0 := begin [smt] induction a, { intros, ematch_using [f] }, { repeat {ematch_using [f, nat.add_one, nat.succ_ne_zero]}} end lemma ex3 (a : nat) : f (a+1) = f a + 1 := begin [smt] dsimp [f] end lemma ex4 (a : nat) : f (a+1) = f a + 1 := begin [smt] simp [f] end lemma ex5 (a : nat) : f (a+1) = f a + 1 := begin [smt] ematch_using [f] end lemma ex6 (a : nat) : f 0 = 1 := begin [smt] ematch_using [f] end
07a2a4f47c7bf2789da803bbb09d8a8436e33ba1
367134ba5a65885e863bdc4507601606690974c1
/src/order/preorder_hom.lean
17a943fa13460d8643dfa668d1bafd1061a43805
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,274
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin # Preorder homomorphisms Bundled monotone functions, `x ≤ y → f x ≤ f y`. -/ import logic.function.iterate import order.basic import order.bounded_lattice import order.complete_lattice import tactic.monotonicity /-! # Category of preorders -/ /-- Bundled monotone (aka, increasing) function -/ structure preorder_hom (α β : Type*) [preorder α] [preorder β] := (to_fun : α → β) (monotone' : monotone to_fun) infixr ` →ₘ `:25 := preorder_hom namespace preorder_hom variables {α : Type*} {β : Type*} {γ : Type*} [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (preorder_hom α β) := { F := λ f, α → β, coe := preorder_hom.to_fun } @[mono] lemma monotone (f : α →ₘ β) : monotone f := preorder_hom.monotone' f @[simp] lemma coe_fun_mk {f : α → β} (hf : _root_.monotone f) (x : α) : mk f hf x = f x := rfl @[ext] lemma ext (f g : preorder_hom α β) (h : ∀ a, f a = g a) : f = g := by { cases f, cases g, congr, funext, exact h _ } lemma coe_inj (f g : preorder_hom α β) (h : (f : α → β) = g) : f = g := by { ext, rw h } /-- The identity function as bundled monotone function. -/ @[simps] def id : preorder_hom α α := ⟨id, monotone_id⟩ instance : inhabited (preorder_hom α α) := ⟨id⟩ @[simp] lemma coe_id : (@id α _ : α → α) = id := rfl /-- The composition of two bundled monotone functions. -/ @[simps] def comp (g : preorder_hom β γ) (f : preorder_hom α β) : preorder_hom α γ := ⟨g ∘ f, g.monotone.comp f.monotone⟩ @[simp] lemma comp_id (f : preorder_hom α β) : f.comp id = f := by { ext, refl } @[simp] lemma id_comp (f : preorder_hom α β) : id.comp f = f := by { ext, refl } /-- `subtype.val` as a bundled monotone function. -/ def subtype.val (p : α → Prop) : subtype p →ₘ α := ⟨subtype.val, λ x y h, h⟩ /-- The preorder structure of `α →ₘ β` is pointwise inequality: `f ≤ g ↔ ∀ a, f a ≤ g a`. -/ instance : preorder (α →ₘ β) := preorder.lift preorder_hom.to_fun instance {β : Type*} [partial_order β] : partial_order (α →ₘ β) := partial_order.lift preorder_hom.to_fun $ by rintro ⟨⟩ ⟨⟩ h; congr; exact h @[simps] instance {β : Type*} [semilattice_sup β] : has_sup (α →ₘ β) := { sup := λ f g, ⟨λ a, f a ⊔ g a, λ x y h, sup_le_sup (f.monotone h) (g.monotone h)⟩ } instance {β : Type*} [semilattice_sup β] : semilattice_sup (α →ₘ β) := { sup := has_sup.sup, le_sup_left := λ a b x, le_sup_left, le_sup_right := λ a b x, le_sup_right, sup_le := λ a b c h₀ h₁ x, sup_le (h₀ x) (h₁ x), .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [semilattice_inf β] : has_inf (α →ₘ β) := { inf := λ f g, ⟨λ a, f a ⊓ g a, λ x y h, inf_le_inf (f.monotone h) (g.monotone h)⟩ } instance {β : Type*} [semilattice_inf β] : semilattice_inf (α →ₘ β) := { inf := has_inf.inf, inf_le_left := λ a b x, inf_le_left, inf_le_right := λ a b x, inf_le_right, le_inf := λ a b c h₀ h₁ x, le_inf (h₀ x) (h₁ x), .. (_ : partial_order (α →ₘ β)) } instance {β : Type*} [lattice β] : lattice (α →ₘ β) := { .. (_ : semilattice_sup (α →ₘ β)), .. (_ : semilattice_inf (α →ₘ β)) } @[simps] instance {β : Type*} [order_bot β] : has_bot (α →ₘ β) := { bot := ⟨λ a, ⊥, λ a b h, le_refl _⟩ } instance {β : Type*} [order_bot β] : order_bot (α →ₘ β) := { bot := has_bot.bot, bot_le := λ a x, bot_le, .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [order_top β] : has_top (α →ₘ β) := { top := ⟨λ a, ⊤, λ a b h, le_refl _⟩ } instance {β : Type*} [order_top β] : order_top (α →ₘ β) := { top := has_top.top, le_top := λ a x, le_top, .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [complete_lattice β] : has_Inf (α →ₘ β) := { Inf := λ s, ⟨ λ x, Inf ((λ f : _ →ₘ _, f x) '' s), λ x y h, Inf_le_Inf_of_forall_exists_le (by simp only [and_imp, exists_prop, set.mem_image, exists_exists_and_eq_and, exists_imp_distrib]; intros; subst_vars; refine ⟨_,by assumption, monotone _ h⟩) ⟩ } @[simps] instance {β : Type*} [complete_lattice β] : has_Sup (α →ₘ β) := { Sup := λ s, ⟨ λ x, Sup ((λ f : _ →ₘ _, f x) '' s), λ x y h, Sup_le_Sup_of_forall_exists_le (by simp only [and_imp, exists_prop, set.mem_image, exists_exists_and_eq_and, exists_imp_distrib]; intros; subst_vars; refine ⟨_,by assumption, monotone _ h⟩) ⟩ } @[simps Sup Inf] instance {β : Type*} [complete_lattice β] : complete_lattice (α →ₘ β) := { Sup := has_Sup.Sup, le_Sup := λ s f hf x, @le_Sup β _ ((λ f : _ →ₘ _, f x) '' s) (f x) ⟨f, hf, rfl⟩, Sup_le := λ s f hf x, @Sup_le β _ _ _ $ λ b (h : b ∈ (λ (f : α →ₘ β), f x) '' s), by rcases h with ⟨g, h, ⟨ ⟩⟩; apply hf _ h, Inf := has_Inf.Inf, le_Inf := λ s f hf x, @le_Inf β _ _ _ $ λ b (h : b ∈ (λ (f : α →ₘ β), f x) '' s), by rcases h with ⟨g, h, ⟨ ⟩⟩; apply hf _ h, Inf_le := λ s f hf x, @Inf_le β _ ((λ f : _ →ₘ _, f x) '' s) (f x) ⟨f, hf, rfl⟩, .. (_ : lattice (α →ₘ β)), .. (_ : order_top (α →ₘ β)), .. (_ : order_bot (α →ₘ β)) } lemma iterate_sup_le_sup_iff {α : Type*} [semilattice_sup α] (f : α →ₘ α) : (∀ n₁ n₂ a₁ a₂, f^[n₁ + n₂] (a₁ ⊔ a₂) ≤ (f^[n₁] a₁) ⊔ (f^[n₂] a₂)) ↔ (∀ a₁ a₂, f (a₁ ⊔ a₂) ≤ (f a₁) ⊔ a₂) := begin split; intros h, { exact h 1 0, }, { intros n₁ n₂ a₁ a₂, have h' : ∀ n a₁ a₂, f^[n] (a₁ ⊔ a₂) ≤ (f^[n] a₁) ⊔ a₂, { intros n, induction n with n ih; intros a₁ a₂, { refl, }, { calc f^[n + 1] (a₁ ⊔ a₂) = (f^[n] (f (a₁ ⊔ a₂))) : function.iterate_succ_apply f n _ ... ≤ (f^[n] ((f a₁) ⊔ a₂)) : f.monotone.iterate n (h a₁ a₂) ... ≤ (f^[n] (f a₁)) ⊔ a₂ : ih _ _ ... = (f^[n + 1] a₁) ⊔ a₂ : by rw ← function.iterate_succ_apply, }, }, calc f^[n₁ + n₂] (a₁ ⊔ a₂) = (f^[n₁] (f^[n₂] (a₁ ⊔ a₂))) : function.iterate_add_apply f n₁ n₂ _ ... = (f^[n₁] (f^[n₂] (a₂ ⊔ a₁))) : by rw sup_comm ... ≤ (f^[n₁] ((f^[n₂] a₂) ⊔ a₁)) : f.monotone.iterate n₁ (h' n₂ _ _) ... = (f^[n₁] (a₁ ⊔ (f^[n₂] a₂))) : by rw sup_comm ... ≤ (f^[n₁] a₁) ⊔ (f^[n₂] a₂) : h' n₁ a₁ _, }, end end preorder_hom namespace order_embedding /-- Convert an `order_embedding` to a `preorder_hom`. -/ def to_preorder_hom {X Y : Type*} [preorder X] [preorder Y] (f : X ↪o Y) : X →ₘ Y := { to_fun := f, monotone' := f.monotone } @[simp] lemma to_preorder_hom_coe {X Y : Type*} [preorder X] [preorder Y] (f : X ↪o Y) : (f.to_preorder_hom : X → Y) = (f : X → Y) := rfl end order_embedding
1dec1c681e9c3722c44b9dae048c2638853fcb8e
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/pseudo_normed_group/profinitely_filtered.lean
7bc1c80253b045e1ec8e9424024e26d1c63f427c
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,367
lean
import algebra.punit_instances import topology.algebra.group import pseudo_normed_group.basic import hacks_and_tricks.type_pow import facts /-! # profinitely_filtered_pseudo_normed_group The definition of a profinitely_filtered_pseudo_normed_group, and an API for this definition. -/ open pseudo_normed_group open_locale nnreal big_operators local attribute [instance] type_pow /-- A *profinitely filtered pseudo-normed topological group* is * an abelian group `M` with an increasing filtration `filtration M c, c : ℝ≥0` such that * `filtration M c` is a profinite set * `M` is pseudo-normed, so `0 ∈ filtration M c`, `-(filtration M c) = filtration M c`, and `x₁ ∈ filtration M c₁, x₂ ∈ filtration M c₂ → (x₁ + x₂) ∈ filtration M (c₁ + c₂)` * (bounded) addition and negation are continuous. Morphisms are continuous and bounded homomorphisms. -/ class profinitely_filtered_pseudo_normed_group (M : Type*) extends pseudo_normed_group M := [topology : ∀ c, topological_space (filtration c)] [t2 : ∀ c, t2_space (filtration c)] [td : ∀ c, totally_disconnected_space (filtration c)] [compact : ∀ c, compact_space (filtration c)] (continuous_add' : ∀ (c₁ c₂), continuous (add' : filtration c₁ × filtration c₂ → filtration (c₁ + c₂))) (continuous_neg' : ∀ c, continuous (neg' : filtration c → filtration c)) (continuous_cast_le : ∀ (c₁ c₂) [h : fact (c₁ ≤ c₂)], continuous (cast_le : filtration c₁ → filtration c₂)) namespace profinitely_filtered_pseudo_normed_group variables {M M₁ M₂ M₃ : Type*} variables [profinitely_filtered_pseudo_normed_group M] variables [profinitely_filtered_pseudo_normed_group M₁] variables [profinitely_filtered_pseudo_normed_group M₂] variables [profinitely_filtered_pseudo_normed_group M₃] instance (c : ℝ≥0) : topological_space (filtration M c) := topology c instance (c : ℝ≥0) : t2_space (filtration M c) := t2 c instance (c : ℝ≥0) : totally_disconnected_space (filtration M c) := td c instance (c : ℝ≥0) : compact_space (filtration M c) := compact c lemma is_closed_map_cast_le (c₁ c₂) [h : fact (c₁ ≤ c₂)] : is_closed_map (@pseudo_normed_group.cast_le M _ _ _ h) := (continuous_cast_le c₁ c₂).is_closed_map lemma closed_embedding_cast_le (c₁ c₂) [h : fact (c₁ ≤ c₂)] : closed_embedding (@pseudo_normed_group.cast_le M _ _ _ h) := closed_embedding_of_continuous_injective_closed (continuous_cast_le c₁ c₂) (injective_cast_le c₁ c₂) (is_closed_map_cast_le c₁ c₂) lemma embedding_cast_le (c₁ c₂) [h : fact (c₁ ≤ c₂)] : embedding (@pseudo_normed_group.cast_le M _ _ _ h) := (closed_embedding_cast_le c₁ c₂).to_embedding end profinitely_filtered_pseudo_normed_group section set_option old_structure_cmd true structure profinitely_filtered_pseudo_normed_group_hom (M₁ M₂ : Type*) [profinitely_filtered_pseudo_normed_group M₁] [profinitely_filtered_pseudo_normed_group M₂] extends M₁ →+ M₂ := (bound' : ∃ C, ∀ c x, x ∈ filtration M₁ c → to_fun x ∈ filtration M₂ (C * c)) (continuous' : ∀ ⦃c₁ c₂⦄ (f₀ : filtration M₁ c₁ → filtration M₂ c₂) (h : ∀ x, to_fun ↑x = f₀ x), continuous f₀) end attribute [nolint doc_blame] profinitely_filtered_pseudo_normed_group_hom.mk profinitely_filtered_pseudo_normed_group_hom.to_add_monoid_hom namespace profinitely_filtered_pseudo_normed_group_hom open profinitely_filtered_pseudo_normed_group variables {M M₁ M₂ M₃ : Type*} variables [profinitely_filtered_pseudo_normed_group M] variables [profinitely_filtered_pseudo_normed_group M₁] variables [profinitely_filtered_pseudo_normed_group M₂] variables [profinitely_filtered_pseudo_normed_group M₃] variables (f g : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) instance : has_coe_to_fun (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) := ⟨_, profinitely_filtered_pseudo_normed_group_hom.to_fun⟩ @[simp] lemma coe_mk (f) (h₁) (h₂) (h₃) (h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) = f := rfl @[simp] lemma mk_to_monoid_hom (f) (h₁) (h₂) (h₃) (h₄) : (⟨f, h₁, h₂, h₃, h₄⟩ : profinitely_filtered_pseudo_normed_group_hom M₁ M₂).to_add_monoid_hom = ⟨f, h₁, h₂⟩ := rfl @[simp] lemma coe_to_add_monoid_hom : ⇑f.to_add_monoid_hom = f := rfl @[simp] lemma map_zero : f 0 = 0 := f.to_add_monoid_hom.map_zero @[simp] lemma map_add (x y) : f (x + y) = f x + f y := f.to_add_monoid_hom.map_add _ _ @[simp] lemma map_sum {ι : Type*} (x : ι → M₁) (s : finset ι) : f (∑ i in s, x i) = ∑ i in s, f (x i) := f.to_add_monoid_hom.map_sum _ _ @[simp] lemma map_sub (x y) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub _ _ @[simp] lemma map_neg (x) : f (-x) = -(f x) := f.to_add_monoid_hom.map_neg _ @[simp] lemma map_gsmul (x) (n : ℤ) : f (n • x) = n • (f x) := f.to_add_monoid_hom.map_gsmul _ _ /-- Make a profinitely filtered pseudo-normed group hom from a group hom and a proof that it is bounded and continuous. -/ def mk_of_bound (f : M₁ →+ M₂) (C : ℝ≥0) (hC : ∀ c, ∃ (H : ∀ x, x ∈ filtration M₁ c → f x ∈ filtration M₂ (C * c)), @continuous (filtration M₁ c) (filtration M₂ (C * c)) _ _ (λ x, ⟨f x, H x x.2⟩)) : profinitely_filtered_pseudo_normed_group_hom M₁ M₂ := { bound' := ⟨C, λ c, (hC c).some⟩, continuous' := λ c₁ c₂ f₀ hf₀, begin obtain ⟨_, H⟩ := hC c₁, haveI : fact ((C * c₁) ≤ max (C * c₁) c₂) := ⟨le_max_left _ _⟩, haveI : fact (c₂ ≤ max (C * c₁) c₂) := ⟨le_max_right _ _⟩, rw (embedding_cast_le c₂ (max (C * c₁) c₂)).continuous_iff, rw (embedding_cast_le (C * c₁) (max (C * c₁) c₂)).continuous_iff at H, convert H using 1, ext, dsimp, rw ← hf₀, refl end, .. f } /-- Make a profinitely filtered pseudo-normed group hom from a group hom and a proof that it is bounded and continuous. -/ def mk_of_strict (f : M₁ →+ M₂) (h : ∀ c, ∃ (H : ∀ x, x ∈ filtration M₁ c → f x ∈ filtration M₂ c), @continuous (filtration M₁ c) (filtration M₂ c) _ _ (λ x, ⟨f x, H x x.2⟩)) : profinitely_filtered_pseudo_normed_group_hom M₁ M₂ := mk_of_bound f 1 $ λ c, begin obtain ⟨w, H⟩ := h c, refine ⟨_, _⟩, { simpa only [one_mul] }, { rwa (embedding_cast_le (1 * c) c).continuous_iff, } end /-- Make a profinitely filtered pseudo-normed group hom from a group hom and a proof that it is bounded and continuous. -/ noncomputable def mk' (f : M₁ →+ M₂) (h : ∃ C, ∀ c, ∃ (H : ∀ x, x ∈ filtration M₁ c → f x ∈ filtration M₂ (C * c)), @continuous (filtration M₁ c) (filtration M₂ (C * c)) _ _ (λ x, ⟨f x, H x x.2⟩)) : profinitely_filtered_pseudo_normed_group_hom M₁ M₂ := mk_of_bound f h.some h.some_spec @[simp] lemma coe_mk_of_bound (f : M₁ →+ M₂) (C) (h) : ⇑(mk_of_bound f C h) = f := rfl @[simp] lemma coe_mk' (f : M₁ →+ M₂) (h) : ⇑(mk' f h) = f := rfl def strict : Prop := ∀ ⦃c x⦄, x ∈ filtration M₁ c → f x ∈ filtration M₂ c def bound_by (C : ℝ≥0) : Prop := ∀ ⦃c x⦄, x ∈ filtration M₁ c → f x ∈ filtration M₂ (C * c) lemma strict_iff_bound_by_one : f.strict ↔ f.bound_by 1 := by simp only [strict, bound_by, one_mul] variables {f} lemma strict.bound_by_one (hf : f.strict) : f.bound_by 1 := f.strict_iff_bound_by_one.1 hf lemma bound_by.strict (hf : f.bound_by 1) : f.strict := f.strict_iff_bound_by_one.2 hf variables (f) lemma bound : ∃ C, f.bound_by C := f.bound' lemma mk_of_bound_bound_by (f : M₁ →+ M₂) (C) (h) : (mk_of_bound f C h).bound_by C := λ c, (h c).some lemma mk_of_strict_strict (f : M₁ →+ M₂) (h) : (mk_of_strict f h).strict := λ c, (h c).some protected lemma continuous ⦃c₁ c₂⦄ (f₀ : filtration M₁ c₁ → filtration M₂ c₂) (h : ∀ x, f ↑x = f₀ x) : continuous f₀ := f.continuous' f₀ h -- /-- `f.level c` is the function `filtration M₁ c → filtration M₂ c` -- induced by a `profinitely_filtered_pseudo_normed_group_hom M₁ M₂`. -/ -- @[simps] def level (c : ℝ≥0) (x : filtration M₁ c) : filtration M₂ c := ⟨f x, f.strict x.2⟩ -- lemma level_continuous (c : ℝ≥0) : continuous (f.level c) := f.continuous' c variables {f g} @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H instance : has_zero (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) := ⟨mk_of_bound (0 : M₁ →+ M₂) 0 (λ c, ⟨λ _ _, zero_mem_filtration _, @continuous_const _ _ _ _ 0⟩)⟩ instance : inhabited (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) := ⟨0⟩ lemma zero_bound_by_zero : (0 : profinitely_filtered_pseudo_normed_group_hom M₁ M₂).bound_by 0 := mk_of_bound_bound_by _ _ _ lemma coe_inj ⦃f g : profinitely_filtered_pseudo_normed_group_hom M₁ M₂⦄ (h : (f : M₁ → M₂) = g) : f = g := by cases f; cases g; cases h; refl /-- The identity function as `profinitely_filtered_pseudo_normed_group_hom`. -/ @[simps] def id : profinitely_filtered_pseudo_normed_group_hom M M := mk_of_bound (add_monoid_hom.id _) 1 $ begin refine λ c, ⟨_, _⟩, { intros, rwa one_mul }, haveI : fact (1 * c ≤ c) := by { rw one_mul, exact ⟨le_rfl⟩ }, rw (embedding_cast_le (1 * c) c).continuous_iff, convert continuous_id, ext, refl end /-- The composition of `profinitely_filtered_pseudo_normed_group_hom`s. -/ @[simps] noncomputable def comp (g : profinitely_filtered_pseudo_normed_group_hom M₂ M₃) (f : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) : profinitely_filtered_pseudo_normed_group_hom M₁ M₃ := mk' (g.to_add_monoid_hom.comp f.to_add_monoid_hom) $ begin obtain ⟨Cf, hCf⟩ := f.bound, obtain ⟨Cg, hCg⟩ := g.bound, refine ⟨Cg * Cf, λ c, ⟨_, _⟩⟩, { intros x hx, rw mul_assoc, exact hCg (hCf hx) }, let f₀ : filtration M₁ c → filtration M₂ (Cf * c) := λ x, ⟨f x, hCf x.2⟩, have hf₀ : continuous f₀ := f.continuous _ (λ x, rfl), let g₀ : filtration M₂ (Cf * c) → filtration M₃ (Cg * (Cf * c)) := λ x, ⟨g x, hCg x.2⟩, have hg₀ : continuous g₀ := g.continuous _ (λ x, rfl), haveI : fact (Cg * Cf * c ≤ Cg * (Cf * c)) := by { rw mul_assoc, exact ⟨le_rfl⟩ }, rw (embedding_cast_le (Cg * Cf * c) (Cg * (Cf * c))).continuous_iff, exact hg₀.comp hf₀ end end profinitely_filtered_pseudo_normed_group_hom namespace punit -- PR #8138 instance (X : Type*) [subsingleton X] (p : X → Prop) : subsingleton (subtype p) := ⟨λ x y, subtype.ext $ subsingleton.elim _ _⟩ instance : profinitely_filtered_pseudo_normed_group punit := { filtration := λ _, set.univ, filtration_mono := λ _ _ _, set.subset_univ _, zero_mem_filtration := λ _, set.mem_univ _, neg_mem_filtration := λ _ _ _, set.mem_univ _, add_mem_filtration := λ _ _ _ _ _ _, set.mem_univ _, continuous_add' := λ _ _, continuous_of_discrete_topology, continuous_neg' := λ _, continuous_of_discrete_topology, continuous_cast_le := λ _ _ _, continuous_of_discrete_topology } end punit section continuity variables {M M₁ M₂ M₃ : Type*} namespace pseudo_normed_group /-- Helper function for pseudo-normed groups. `pow_incl` is the natural inclusion function `(filtration M c)^n → M^n`. Note that `(filtration M c)^n` is not the same type as `filtration (M^n) c`, although they are naturally equivalent. -/ def pow_incl {n : ℕ} {c : ℝ≥0} [pseudo_normed_group M] : (filtration M c : Type*)^n → M^n := λ x j, x j lemma pow_incl_injective {n : ℕ} {c : ℝ≥0} [pseudo_normed_group M] : function.injective (@pow_incl M n c _) := λ x y h, funext $ λ j, subtype.coe_injective $ congr_fun h j @[simp] lemma pow_incl_apply {n : ℕ} {c : ℝ≥0} [pseudo_normed_group M] (x : (filtration M c : Type*)^n) (j : fin n) : pow_incl x j = x j := rfl end pseudo_normed_group open pseudo_normed_group profinitely_filtered_pseudo_normed_group variables [profinitely_filtered_pseudo_normed_group M] variables [profinitely_filtered_pseudo_normed_group M₁] variables [profinitely_filtered_pseudo_normed_group M₂] variables [profinitely_filtered_pseudo_normed_group M₃] /-- A function `f : M₁ → M₂` between profinitely filtered pseudo-normed groups is continuous if it is continuous when restricted to the filtration sets. Implementation detail: to avoid diamonds of topologies on `filtration M c` we avoid `topological_space M`. We therefore give a hands on definition of continuity. -/ def pfpng_ctu (f : M₁ → M₂) : Prop := ∀ ⦃c₁ c₂⦄ (f₀ : filtration M₁ c₁ → filtration M₂ c₂) (h : ∀ x, f ↑x = f₀ x), continuous f₀ section pfpng_ctu lemma pfpng_ctu_const (y : M₂) : pfpng_ctu (λ x : M₁, y) := begin intros c₁ c₂ f₀ h, suffices : f₀ = λ x, f₀ ⟨0, zero_mem_filtration _⟩, { rw this, exact continuous_const }, ext1 x, apply subtype.coe_injective, rw [← h, ← h] end lemma pfpng_ctu.neg {f : M₁ → M₂} (hf : pfpng_ctu f) : pfpng_ctu (-f) := begin intros c₁ c₂ f₀ h, let g := neg' ∘ f₀, have hg : f₀ = neg' ∘ g, { ext, simp [neg_neg] }, rw hg, refine (continuous_neg' c₂).comp (hf g _), intro x, specialize h x, simp only [g, ← h, neg_neg, pi.neg_apply, neg'_eq] end lemma pfpng_ctu.add {f g : M₁ → M₂} (hf : pfpng_ctu f) (hg : pfpng_ctu g) (H : ∀ c₁, ∃ c₂, ∀ x : filtration M₁ c₁, f x ∈ filtration M₂ c₂) : pfpng_ctu (f + g) := begin intros c₁ c₂ fg₀ hfg₀, obtain ⟨cf, hcf⟩ := H c₁, let f₀ : filtration M₁ c₁ → filtration M₂ cf := λ x, ⟨f x, hcf x⟩, have hf₀ : ∀ x, f ↑x = f₀ x := λ x, rfl, have f₀_ctu : continuous f₀ := hf f₀ hf₀, let cg := cf + c₂, haveI : fact (c₂ ≤ cf + cg) := ⟨calc c₂ ≤ cf + c₂ : self_le_add_left _ _ ... ≤ cf + (cf + c₂) : self_le_add_left _ _⟩, have hcg : ∀ x : filtration M₁ c₁, g x ∈ filtration M₂ cg, { intros x, have : g x = -(f x) + (f + g) x, { simp only [pi.add_apply, neg_add_cancel_left] }, rw this, refine add_mem_filtration (neg_mem_filtration $ hcf x) _, rw hfg₀, exact (fg₀ x).2 }, let g₀ : filtration M₁ c₁ → filtration M₂ cg := λ x, ⟨g x, hcg x⟩, have hg₀ : ∀ x, g ↑x = g₀ x := λ x, rfl, have g₀_ctu : continuous g₀ := hg g₀ hg₀, have aux := (f₀_ctu.prod_mk g₀_ctu), rw (embedding_cast_le c₂ (cf + cg)).continuous_iff, convert (continuous_add' cf cg).comp aux using 1, ext, dsimp, rw [← hfg₀, pi.add_apply] end lemma pfpng_ctu.sub {f g : M₁ → M₂} (hf : pfpng_ctu f) (hg : pfpng_ctu g) (H : ∀ c₁, ∃ c₂, ∀ x : filtration M₁ c₁, f x ∈ filtration M₂ c₂) : pfpng_ctu (f - g) := by { rw [sub_eq_add_neg], exact hf.add (hg.neg) H } variables (M) lemma pfpng_ctu_id : pfpng_ctu (@id M) := begin intros c₁ c₂ f₀ h, haveI : fact (c₁ ≤ max c₁ c₂) := ⟨le_max_left _ _⟩, haveI : fact (c₂ ≤ max c₁ c₂) := ⟨le_max_right _ _⟩, have : @cast_le M _ c₂ (max c₁ c₂) _ ∘ f₀ = cast_le, { ext, dsimp, rw ← h, refl }, rw [(embedding_cast_le c₂ (max c₁ c₂)).continuous_iff, this], exact (embedding_cast_le _ _).continuous end lemma pfpng_ctu_smul_nat : ∀ (n : ℕ), pfpng_ctu (λ x : M, n • x) | 0 := by { simp only [zero_smul], exact pfpng_ctu_const 0 } | (n+1) := by { simp only [add_smul, one_smul, add_comm], exact (pfpng_ctu_id M).add (pfpng_ctu_smul_nat n) (λ c, ⟨c, λ x, x.2⟩) } lemma pfpng_ctu_smul_int : ∀ (n : ℤ), pfpng_ctu (λ x : M, n • x) | (n:ℕ) := by simpa only [gsmul_coe_nat] using pfpng_ctu_smul_nat M n | -[1+n] := by simpa only [gsmul_neg_succ_of_nat] using (pfpng_ctu_smul_nat M (n + 1)).neg end pfpng_ctu end continuity namespace profinitely_filtered_pseudo_normed_group_hom variables {M M₁ M₂ : Type*} variables [profinitely_filtered_pseudo_normed_group M] variables [profinitely_filtered_pseudo_normed_group M₁] variables [profinitely_filtered_pseudo_normed_group M₂] def add (f g : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) : profinitely_filtered_pseudo_normed_group_hom M₁ M₂ := { to_fun := f + g, bound' := begin obtain ⟨Cf, hCf⟩ := f.bound, obtain ⟨Cg, hCg⟩ := g.bound, refine ⟨Cf + Cg, λ c x hx, _⟩, rw add_mul, apply add_mem_filtration (hCf hx) (hCg hx), end, continuous' := begin apply pfpng_ctu.add f.continuous g.continuous, obtain ⟨Cf, hCf⟩ := f.bound, intro c₁, refine ⟨Cf * c₁, λ x, hCf x.2⟩, end, .. f.to_add_monoid_hom + g.to_add_monoid_hom } def sub (f g : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) : profinitely_filtered_pseudo_normed_group_hom M₁ M₂ := { to_fun := f - g, bound' := begin obtain ⟨Cf, hCf⟩ := f.bound, obtain ⟨Cg, hCg⟩ := g.bound, refine ⟨Cf + Cg, λ c x hx, _⟩, rw add_mul, apply sub_mem_filtration (hCf hx) (hCg hx), end, continuous' := begin apply pfpng_ctu.sub f.continuous g.continuous, obtain ⟨Cf, hCf⟩ := f.bound, intro c₁, refine ⟨Cf * c₁, λ x, hCf x.2⟩, end, .. f.to_add_monoid_hom - g.to_add_monoid_hom } def neg (f : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) : profinitely_filtered_pseudo_normed_group_hom M₁ M₂ := { to_fun := -f, bound' := begin obtain ⟨Cf, hCf⟩ := f.bound, refine ⟨Cf, λ c x hx, _⟩, apply neg_mem_filtration (hCf hx), end, continuous' := pfpng_ctu.neg f.continuous, .. -f.to_add_monoid_hom } instance : has_add (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) := ⟨add⟩ instance : has_sub (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) := ⟨sub⟩ instance : has_neg (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) := ⟨neg⟩ instance : add_comm_group (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) := function.injective.add_comm_group profinitely_filtered_pseudo_normed_group_hom.to_add_monoid_hom (λ f g h, by { ext, rw add_monoid_hom.ext_iff at h, exact h x }) rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) @[simps] def to_add_monoid_hom_hom : (profinitely_filtered_pseudo_normed_group_hom M₁ M₂) →+ (M₁ →+ M₂) := { to_fun := to_add_monoid_hom, map_zero' := rfl, map_add' := λ _ _, rfl } lemma to_add_monoid_hom_hom_injective : function.injective (@to_add_monoid_hom_hom M₁ M₂ _ _) := λ f g h, by { ext x, exact add_monoid_hom.congr_fun h x } lemma bound_by.add {f g : profinitely_filtered_pseudo_normed_group_hom M₁ M₂} {Cf Cg : ℝ≥0} (hf : f.bound_by Cf) (hg : g.bound_by Cg) : (f + g).bound_by (Cf + Cg) := λ c x hx, by { rw add_mul, exact add_mem_filtration (hf hx) (hg hx) } @[simp] lemma add_apply (f g : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) (x : M₁) : (f + g) x = f x + g x := rfl @[simp] lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → profinitely_filtered_pseudo_normed_group_hom M₁ M₂) (x : M₁) : (∑ i in s, f i) x = ∑ i in s, (f i x) := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty], refl }, { intros i s his IH, simp only [finset.sum_insert his, add_apply, IH] } end lemma sum_bound_by {ι : Type*} (s : finset ι) (f : ι → profinitely_filtered_pseudo_normed_group_hom M₁ M₂) (C : ι → ℝ≥0) (hf : ∀ i ∈ s, (f i).bound_by (C i)) : (∑ i in s, f i).bound_by (∑ i in s, C i) := begin classical, revert hf, apply finset.induction_on s, { intro, simp only [finset.sum_empty], exact zero_bound_by_zero }, { intros i s his IH hf, simp only [finset.sum_insert his], apply (hf _ (s.mem_insert_self i)).add (IH $ λ j hj, hf _ $ finset.mem_insert_of_mem hj) } end end profinitely_filtered_pseudo_normed_group_hom namespace profinitely_filtered_pseudo_normed_group /-! ## Products -/ section pi variables {ι : Type*} (M : ι → Type*) [Π i, profinitely_filtered_pseudo_normed_group (M i)] instance pi_topology (c : ℝ≥0) : topological_space (filtration (Π i, M i) c) := topological_space.induced (filtration_pi_equiv M c) $ infer_instance @[simps apply symm_apply] def filtration_pi_homeo (c : ℝ≥0) : filtration (Π i, M i) c ≃ₜ Π i, filtration (M i) c := { to_fun := λ x i, ⟨x.1 i, x.2 i⟩, inv_fun := λ x, ⟨λ i, x i, λ i, (x i).2⟩, left_inv := by { rintro ⟨x, hx⟩, refl }, right_inv := by { intro x, ext, refl }, continuous_to_fun := begin rw continuous_def, intros U hU, rw is_open_induced_iff, refine ⟨U, hU, _⟩, refl, end, continuous_inv_fun := begin rw continuous_def, rintros s ⟨t, ht, s_eq⟩, simpa [← s_eq] using continuous_def.1 _ t ht, { rw [filtration_pi_equiv, continuous_def], intros U hU, simp only [*, equiv.coe_fn_mk, set.preimage_id', subtype.coe_eta, subtype.coe_mk] }, end } instance pi_t2 (c : ℝ≥0) : t2_space (filtration (Π i, M i) c) := begin have : t2_space (Π i, filtration (M i) c) := infer_instance, apply @embedding.t2_space _ _ _ _ this (filtration_pi_homeo M c) (filtration_pi_homeo M c).embedding, end instance pi_td (c : ℝ≥0) : totally_disconnected_space (filtration (Π i, M i) c) := begin obtain ⟨H⟩ : totally_disconnected_space (Π i, filtration (M i) c) := infer_instance, rw [← homeomorph.range_coe (filtration_pi_homeo M c), ← set.image_univ] at H, exact ⟨embedding.is_totally_disconnected (filtration_pi_homeo M c).embedding H⟩, end instance pi_compact (c : ℝ≥0) : compact_space (filtration (Π i, M i) c) := begin obtain ⟨H⟩ : compact_space (Π i, filtration (M i) c) := infer_instance, rw [← (homeomorph.compact_image (filtration_pi_homeo M c).symm), set.image_univ, homeomorph.range_coe] at H, exact ⟨H⟩, end def prod_pi_homeo_pi_prod [Π i, profinitely_filtered_pseudo_normed_group (M i)] (c₁ c₂ : ℝ≥0) : filtration (Π i, M i) c₁ × filtration (Π i, M i) c₂ ≃ₜ Π i, (filtration (M i) c₁ × filtration (M i) c₂) := { to_fun := λ x i, ⟨⟨x.1.1 i, x.1.2 i⟩, ⟨x.2.1 i, x.2.2 i⟩⟩, inv_fun := λ x, ⟨⟨λ i, (x i).1.1, λ i, (x i).1.2⟩, ⟨λ i, (x i).2.1, λ i, (x i).2.2⟩⟩, left_inv := by {rintro ⟨x, hx⟩, simp only [subtype.coe_eta, subtype.val_eq_coe]}, right_inv := by { intro x, ext; refl}, continuous_to_fun := begin apply continuous_pi, intro i, apply continuous.prod_mk, have h₁ := (homeomorph.comp_continuous_iff (filtration_pi_homeo M c₁)).mpr continuous_fst, exact (continuous_apply i).comp h₁, have h₂ := (homeomorph.comp_continuous_iff (filtration_pi_homeo M c₂)).mpr continuous_snd, exact (continuous_apply i).comp h₂, end, continuous_inv_fun := begin apply continuous.prod_mk, let f₁ : (Π i, (filtration (M i) c₁) × (filtration (M i) c₂)) → (filtration (Π i, M i) c₁) := λ x, ⟨λ (i : ι), (x i).fst.val, λ i, (x i).fst.prop⟩, have : continuous ((filtration_pi_homeo M c₁) ∘ f₁), { apply continuous_pi, intro i, dsimp [filtration_pi_homeo, f₁], simp only [subtype.coe_eta], exact continuous_fst.comp (continuous_apply i), }, exact (homeomorph.comp_continuous_iff (filtration_pi_homeo M c₁)).mp this, let f₂ : (Π i, (filtration (M i) c₁) × (filtration (M i) c₂)) → (filtration (Π i, M i) c₂) := λ x, ⟨λ (i : ι), (x i).snd.val, λ i, (x i).snd.prop⟩, have : continuous ((filtration_pi_homeo M c₂) ∘ f₂), { apply continuous_pi, intro i, dsimp [filtration_pi_homeo, f₂], simp only [subtype.coe_eta], exact continuous_snd.comp (continuous_apply i), }, exact (homeomorph.comp_continuous_iff (filtration_pi_homeo M c₂)).mp this, end,} instance pi : profinitely_filtered_pseudo_normed_group (Π i, M i) := { continuous_add' := begin intros c₁ c₂, rw [← homeomorph.comp_continuous_iff (filtration_pi_homeo M (c₁ + c₂)), ← homeomorph.comp_continuous_iff' (prod_pi_homeo_pi_prod M c₁ c₂).symm], apply continuous_pi, intro i, exact (continuous_add' c₁ c₂).comp (continuous_apply i), end, continuous_neg' := begin intro c, rw [← homeomorph.comp_continuous_iff (filtration_pi_homeo M c), ← homeomorph.comp_continuous_iff' (filtration_pi_homeo M c).symm], apply continuous_pi, intro i, exact (continuous_neg' c).comp (continuous_apply i), end, continuous_cast_le := begin intros c₁ c₂ h, rw [← homeomorph.comp_continuous_iff (filtration_pi_homeo M c₂), ← homeomorph.comp_continuous_iff' (filtration_pi_homeo M c₁).symm], apply continuous_pi, intro i, have := @continuous_cast_le _ _ _ _ h, exact this.comp (continuous_apply i), end, .. pseudo_normed_group.pi M } variables {M} @[simps] def pi_proj (i : ι) : profinitely_filtered_pseudo_normed_group_hom (Π i, M i) (M i) := profinitely_filtered_pseudo_normed_group_hom.mk_of_bound (pi.eval_add_monoid_hom M i) 1 $ begin refine λ c, ⟨λ x hx, by { rw one_mul, exact hx i }, _⟩, have := ((continuous_apply i).comp (filtration_pi_homeo M c).continuous), haveI : fact (c ≤ 1 * c) := by { rw one_mul, exact ⟨le_rfl⟩ }, rw (embedding_cast_le c (1 * c)).continuous_iff at this, convert this using 0, end lemma pi_proj_bound_by (i : ι) : (@pi_proj _ M _ i).bound_by 1 := profinitely_filtered_pseudo_normed_group_hom.mk_of_bound_bound_by _ _ _ /-- Universal property of the product of profinitely filtered pseudo-normed groups -/ @[simps {fully_applied := ff}] def pi_lift {N : Type*} [profinitely_filtered_pseudo_normed_group N] (f : Π i, profinitely_filtered_pseudo_normed_group_hom N (M i)) (hf : ∃ C, ∀ i, (f i).bound_by C) : profinitely_filtered_pseudo_normed_group_hom N (Π i, M i) := { to_fun := add_monoid_hom.mk_to_pi (λ i, (f i).to_add_monoid_hom), bound' := by { obtain ⟨C, hC⟩ := hf, refine ⟨C, λ c x hx i, hC i hx⟩ }, continuous' := begin intros c₁ c₂ f₀ hf₀, apply continuous_induced_rng, apply continuous_pi, intro i, let g := function.eval i ∘ filtration_pi_homeo M c₂ ∘ f₀, refine (f i).continuous g (λ x, _), specialize hf₀ x, rw function.funext_iff at hf₀, exact hf₀ i end, .. add_monoid_hom.mk_to_pi (λ i, (f i).to_add_monoid_hom) } noncomputable def pi_map {N : ι → Type*} [Π i, profinitely_filtered_pseudo_normed_group (N i)] (f : Π i, profinitely_filtered_pseudo_normed_group_hom (M i) (N i)) (hf : ∃ C, ∀ i, (f i).bound_by C) : profinitely_filtered_pseudo_normed_group_hom (Π i, M i) (Π i, N i) := pi_lift (λ i, (f i).comp (pi_proj i)) begin obtain ⟨C, hC⟩ := hf, refine ⟨C, λ i c x hx, hC i _⟩, have := pi_proj_bound_by i hx, rwa one_mul at this, end end pi end profinitely_filtered_pseudo_normed_group
f20128269b244454ae3d13e54e887123dcb3a76a
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/tools/super/simp.lean
ddaae27c38fa85efd8ff7dde78bfcbdb7dbc1d91
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,503
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause_ops .prover_state open tactic monad namespace super meta def prove_using_assumption : tactic unit := do tgt ← target, ass ← mk_local_def `h tgt, exact ass meta def simplify_capturing_assumptions (type : expr) : tactic (expr × expr × list expr) := do S ← simp_lemmas.mk_default, (type', heq) ← simplify S type, hyps ← return $ contained_lconsts type, hyps' ← return $ contained_lconsts_list [type', heq], add_hyps ← return $ list.filter (λn : expr, ¬hyps^.contains n^.local_uniq_name) hyps'^.values, return (type', heq, add_hyps) meta def try_simplify_left (c : clause) (i : ℕ) : tactic (list clause) := on_left_at c i $ λtype, do (type', heq, add_hyps) ← simplify_capturing_assumptions type, hyp ← mk_local_def `h type', prf ← mk_eq_mpr heq hyp, return [(hyp::add_hyps, prf)] meta def try_simplify_right (c : clause) (i : ℕ) : tactic (list clause) := on_right_at' c i $ λhyp, do (type', heq, add_hyps) ← simplify_capturing_assumptions hyp^.local_type, heqtype ← infer_type heq, heqsymm ← mk_eq_symm heq, prf ← mk_eq_mpr heqsymm hyp, return [(add_hyps, prf)] meta def simp_inf : inf_decl := inf_decl.mk 40 $ take given, sequence' $ do r ← [try_simplify_right, try_simplify_left], i ← list.range given^.c^.num_lits, [inf_if_successful 2 given (r given^.c i)] end super
505d6b88aa8811d83658acc62549311da1c6b002
b147e1312077cdcfea8e6756207b3fa538982e12
/tactic/basic.lean
4fdaa906d9a38b79b8768325f33af05091627845
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,004
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.dlist.basic namespace expr open tactic protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := do n ← e.to_nat, return n protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] end expr namespace environment meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) end environment namespace tactic meta definition mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (do (new_t, pr) ← target >>= tac, replace_target new_t pr, return tt) <|> return ff else return ff, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) end instance_cache /-- Reset the instance cache for the main goal. -/ meta def reset_instance_cache : tactic unit := unfreeze_local_instances meta def match_head (e : expr) : expr → tactic unit | e' := unify e e' <|> do `(_ → %%e') ← whnf e', v ← mk_mvar, match_head (e'.instantiate_var v) meta def find_matching_head : expr → list expr → tactic (list expr) | e [] := return [] | e (H :: Hs) := do t ← infer_type H, ((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs meta def subst_locals (s : list (expr × expr)) (e : expr) : expr := (e.abstract_locals (s.map (expr.local_uniq_name ∘ prod.fst)).reverse).instantiate_vars (s.map prod.snd) meta def set_binder : expr → list binder_info → expr | e [] := e | (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs) | e _ := e /-- variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h' , gs) meta def try_intros : list name → tactic (list name) | [] := do tgt ← target >>= instantiate_mvars, if tgt.is_pi then failed else return [] | (x::xs) := (intro x >> try_intros xs) <|> pure (x :: xs) meta def ext1 (xs : list name) : tactic (list name) := do ls ← attribute.get_instances `extensionality, ls.any_of (λ l, applyc l), try_intros xs meta def ext : list name → option ℕ → tactic unit | _ (some 0) := return () | xs n := focus1 (do ys ← ext1 xs, ext ys (nat.pred <$> n) <|> return ()) meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] meta def drop_binders : expr → tactic expr | (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders | e := pure e meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, [c] ← pure $ env.constructors_of struct_n | fail "too many constructors", vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do e ← mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n open nat meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and fail if none succeeds -/ meta def apply_list_expr : list expr → tactic unit | [] := fail "no matching rule" | (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t /-- constructs a list of expressions given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list.-/ meta def build_list_expr_for_apply : list pexpr → tactic (list expr) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← list.mmap mk_const l, return (m.append tail)) <|> return (a::tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times -/ meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit := do l ← build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l) meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg) meta def apply_assumption (asms : option (list expr) := none) (tac : tactic unit := return ()) : tactic unit := do { ctx ← asms.to_monad <|> local_context, ctx.any_of (λ H, () <$ symm_apply H ; tac) } <|> do { exfalso, ctx ← asms.to_monad <|> local_context, ctx.any_of (λ H, () <$ symm_apply H ; tac) } <|> fail "assumption tactic failed" open nat meta def solve_by_elim_aux (discharger : tactic unit) (asms : option (list expr)) : ℕ → tactic unit | 0 := done | (succ n) := discharger <|> (apply_assumption asms $ solve_by_elim_aux n) meta structure by_elim_opt := (discharger : tactic unit := done) (restr_hyp_set : option (list expr) := none) (max_rep : ℕ := 3) meta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit := solve_by_elim_aux opt.discharger opt.restr_hyp_set opt.max_rep end tactic
1c89ae5f4ebbe6d9cf4157aae5ef7f7c2f3fef20
d320d01276642370017b4ce56793b5f73e0016f9
/lean projects and notes/hw8_sa3tnc.lean
e6aec0b62b5f8a0438a2d1d0538d877d5d2e0a4f
[]
no_license
samiazam00/my-work
388d815ddc7e47860375959ba31be2530be7f11e
e9a8218b2441dce00bf117d3d985d00e6ee14ec0
refs/heads/master
1,608,518,076,248
1,580,268,523,000
1,580,268,523,000
236,280,156
0
0
null
null
null
null
UTF-8
Lean
false
false
10,751
lean
/- Samreen Azam (sa3tnc) CS 2102 F19, Homework #8, Predicate Logic & Proofs. -/ namespace hw8 /- #1. Equality and proofs of equality. -/ /- A. [10 points] Fill in the blank. When we say that the binary equality relation, =, on objects of any type, α, is reflexive, we mean that for any value, a, of type, α, _______. ANSWER: a = a (any value of type α is equal to itself) -/ /- B. [10 points] Complete the following definition in Lean to formalize the proposition that 1 equals 1. -/ def one_eq_one : Prop := -- ANSWER ∀ (n : ℕ), n = 1 → eq n n /- C. [10 points] Give an English language proof of the proposition that 1 = 1 by completing the following incomplete proof. To obtain a proof of 1 = 1 we apply the ________ property of the ________ relation to the specific value, _________. ANSWER: 1) reflexive 2) binary 3) one -/ /- D. [10 points] Give a formal proof of this proposition by completing the following definition. -/ def proof_that_one_eq_one : one_eq_one := -- ANSWER --∀ (n : ℕ) one_eq_one n n sorry --had to comment answer on line 58 out since it's incomplete so line 68 was getting an error /- [10 points] E. Complete the following test case to produce an example that suggests (correctly) that Lean will accept a proof that two *different terms* are equal as long as they reduce to the same value. -/ -- ANSWER: Give a proposition and proof in Lean def two_plus_two_eq_four : 2 + 2 = 4 := eq.refl 4 -- ANSWER Does eq.refl work as suggested? Yes /- #2. Predicates and Properties A predicate is a parameterized proposition. By applying a predicate to different arguments, we get different propositions. Such a propopsition can be said to be "about" the argument to which it was applied. We interpret such a proposition as asserting that its argument has a *property* of interest. If the proposition has a proof (is true), the object does have the asserted property, and if the proposition is not true, the object doesn't have that property. In the following set of problems, we will take the property of a natural number "being even" as a case in point. In natural language, we will say that a natural number, n, is even if and only if (1) it is zero, or, (2) it is two more than another even number. Think about this inductive definition. Why does it cover all possible cases -- an infinitude of cases? (No need for an answer here.) -/ /- A. [10 points] We have accepted as *axioms* in our definition of evennness that zero is even and that any number that is two more than another even number is even. These are the only axioms you may use in giving a proof that four is even. Give a natural language proof now. Hint, start by saying the following: Proof: To prove that four is even, *it will suffice* to show that 2 is even, because if two is even then, given that 4 is two more than two, if two is even then so is four, by rule (2). Now all that remains to be proved is that _______________. Give the rest of your natural language proof here, and be sure to indicate which of the two rules you are applying at each step in your reasoning. ANSWER: 2 is two more than 0 (rule 1) -/ /- B. [10 points] We formalize a predicate, such as is_even, as a family of "inductive propositions" given by a function from argument values to propositions. Such an inductive definition thus has the type, α → Prop, where α is the type of argument to which the predicate is applied. Please see the first line of the definition of is_even that follows for an example. Having specified the *type* of a predicate, in this case from ℕ → Prop, we then define the set of constructors to define the logical rules that can be used to construct proofs of any such proposition. These rules are the (formal) axioms that can be used to construct proofs. The first one (below) states that the term, pf_zero_is_even, is to be accepted as a proof of is_even 0 (which is how we write the application of a predicate to a value to obtain a proposition, here that "0 is even"). The second constructor/axiom/rule provides a way to build a proof of (is_even 2+n) by applying the constructor to any n along with a proof that that particular n is even. (Yes: the ∀ specifies the first argument to pf_even_plus_two_is_even. This is necessary to give the argument a name, here n, so that that name can be used in defining the rest of the constructor's type). -/ inductive is_even : ℕ → Prop | pf_zero_is_even : (is_even 0) | pf_even_plus_two_is_even : ∀ (n : ℕ), is_even n → is_even (nat.succ (nat.succ n)) /- Give formal proofs for each of the following propositions. (Notice how we obtain different propositions by applying the predicate, is_even, to different argument values. This is what we mean when we say that a predicate defines a family of propositions.) -/ open is_even theorem zero_even : is_even 0 := -- ANSWER begin exact pf_zero_is_even end /- In this case, give a proof term without using a begin/end proof script. -/ theorem two_even : is_even 2 := -- ANSWER pf_even_plus_two_is_even 0 zero_even /- In this case, give a proof using a begin/end proof script. -/ theorem eight_even : is_even 8 := begin apply pf_even_plus_two_is_even, --Answer: apply pf_even_plus_two_is_even, apply pf_even_plus_two_is_even, apply pf_even_plus_two_is_even, exact zero_even end /- C. [10 points] Formally specify a predicate, is_odd, on the natural numbers. You can reason about any natural number being odd using two rules, just as for being even. Once you've defined your predicate (an inductive family of proposition, just like is_even), formally state and prove the following propositions (however you wish). - 1 is odd - 7 is odd -/ -- ANSWER inductive is_odd : ℕ → Prop | pf_one_is_odd : (is_odd 1) | pf_odd_plus_two_is_odd : ∀ (n : ℕ), is_odd n → is_odd (nat.succ (nat.succ n)) open is_odd -- ANSWER theorem one_odd : is_odd 1 := begin exact pf_one_is_odd end --ANSWER theorem seven_odd : is_odd 7 := begin apply pf_odd_plus_two_is_odd, apply pf_odd_plus_two_is_odd, apply pf_odd_plus_two_is_odd, exact one_odd end /- Introducing an important concept. In the preceding problems, we've seen that we can think of a predicate with one argument as defining a property objects, such as the property of being even. Now we shift perspective from the concept of a property, per se, to the concept of "the set of objects that have a given property." The set of objects that have the is_even property, for example, could be written as evens = {0, 2, 4, 6, 8, 10, ...} or more formally as evens = { n : ℕ | is_even n} The elements of these sets are all, and only, the values that "satisfy" the is_even predicate. A value satisfies its predicate if, when plugged in, the resulting proposition has a proof (and so is true). The key conclusion is that a predicate with a single argument defines a *set*, namely the set of all and only those objects that have that property. -/ /- #4. Predicates and binary relations Mathematicians define *binary relations* as sets of ordered pairs. For example, the equality relation on natural numbers comprises the set of of all pairs of natural numbers such that the first and second elements are the same. We could write this set like this: equals = { (0,0), (1,1), (2,2), ...}, or like this: equals = { (m : ℕ, n : ℕ) | m = n } We formalize binary relations as predicates with *two* arguments. The type of such a predicate in Lean is thus α → β → Prop, where α and β are the types of the arguments. In our example, we have a two-place predicate that defines the set of ordered pairs of natural numbers where the two elements of each pair are co-equal. Study and understand the following specification of this binary relation. Look at the construtor, mk, in particular: it says that you can construct a proof that a pair of values, n and m, is in our id_nat_relation if you have a proof of n = m. (In other words, it suffices to show that n = m using Lean's built in equality relation to construct a proof that (n, m) is in our id_nat_relation.) -/ inductive id_nat_relation : ℕ → ℕ → Prop | mk : ∀ (n m : ℕ), n = m → id_nat_relation n m /- A. [10 points] Give a formal proof that id_nat_relation contains the pair, (3, 3). Do it by completing the following proof. Think carefully about the third argument: you need a *value* of what type here? What do we call a value of a logical type? -/ theorem three_three_in_id : id_nat_relation 3 3 := -- ANSWER (apply a constructor, of course) --id_nat_relation.mk 3 3 ( sorry /- B. [10 points] Explain in just a few words why it is not possible to prove that (3,5) is in this relation. -/ -- ANSWER: An axiom of this relation is that n = m, so it only works for pairs of the same values /- EXTRA CREDIT. -/ /- Here's a definition of what it means for a relation to be reflexive. -/ def reflexive {α : Type} (r : α → α → Prop) := ∀ (a : α), r a a /- A. Formally state and prove that id_nat_relation is reflexive. Hint: use a script and start it with "assume (a : ℕ)". Remember that to prove a ∀ proposition, we *assume* that we're given some arbitrary but specific value of the given type, then we prove the rest of the proposition about it. But because we didn't say anything about the element we picked, we can conclude that the statement must be true of any element of the type. -/ -- ANSWER theorem id_nat_refl : reflexive id_nat_relation := begin assume (a : ℕ), assume (h : a = a) exact id_nat_relation h, end /- B. [Double extra credit.] Formally define what we mean by a relation being symmetric and transitive, in the style of the above definition of reflexive, and formally state and show that our id_nat_reflexive relation is also symmetric and transitive. Answer: Symmetric - if x = y, then y = x. In this case, a will always equal a since it is the same variable, so paramter order does not affect the result. Transitive - For x, y, and z: if x is related to y and y is related to z, then x is related to z. In this function, if h : (a → a → prop) and (h = id_nat_relation), then (id_nat_relation : (a → a → prop)) -/ end hw8
bdd28bb233cfe1ff85ed3af7c55a282fc3ee6260
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/finsupp/pointwise.lean
cd164c995fd2b23c2a2d78e4c6a3ba7576e04af2
[ "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
1,972
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.finsupp.basic /-! # The pointwise product on `finsupp`. TODO per issue #1864: We intend to remove the convolution product on finsupp, and define it only on a type synonym `add_monoid_algebra`. After we've done this, it would be good to make this the default product on `finsupp`. -/ noncomputable theory open_locale classical open finset universes u₁ u₂ u₃ u₄ u₅ variables {α : Type u₁} {β : Type u₂} {γ : Type u₃} {δ : Type u₄} {ι : Type u₅} namespace finsupp /-! ### Declarations about the pointwise product on `finsupp`s -/ section variables [mul_zero_class β] /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is `f a * g a`. -/ instance : has_mul (α →₀ β) := ⟨zip_with (*) (mul_zero 0)⟩ @[simp] lemma mul_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ * g₂) a = g₁ a * g₂ a := rfl lemma support_mul {g₁ g₂ : α →₀ β} : (g₁ * g₂).support ⊆ g₁.support ∩ g₂.support := begin intros a h, simp only [mul_apply, mem_support_iff] at h, simp only [mem_support_iff, mem_inter, ne.def], rw ←not_or_distrib, intro w, apply h, cases w; { rw w, simp }, end end instance [semiring β] : semigroup (α →₀ β) := { mul := (*), mul_assoc := λ f g h, by { ext, simp only [mul_apply, mul_assoc], }, } instance [semiring β] : distrib (α →₀ β) := { left_distrib := λ f g h, by { ext, simp only [mul_apply, add_apply, left_distrib] {proj := ff} }, right_distrib := λ f g h, by { ext, simp only [mul_apply, add_apply, right_distrib] {proj := ff} }, ..(infer_instance : semigroup (α →₀ β)), ..(infer_instance : add_comm_monoid (α →₀ β)) } -- If `non_unital_semiring` existed in the algebraic hierarchy, we could produce one here. end finsupp
a25923a95252cb962b93ca6826bf300edb1e6678
e1da55f4222dac91b940ca052928eaace09762da
/src/corner.lean
fc4b89eddcd117b84755302274b9bbb1975274fa
[]
no_license
b-mehta/regularity-lemma
c5826e22c280d0b073a4e62dba731f4dd3d1b69f
cf26082b0c88fa54276e6fdc3338c15e607c52c6
refs/heads/master
1,658,209,524,267
1,644,406,456,000
1,644,406,456,000
457,327,371
1
0
null
null
null
null
UTF-8
Lean
false
false
21,556
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import .triangle_removal import combinatorics.additive.salem_spencer /-! # The corners theorem and Roth's theorem This file proves the corners theorem and Roth's theorem. -/ open_locale classical open finset variables {N : ℕ} /-- A corner in `s` is three points of the form `(x, y), (x + h, y), (x, y + h)` with `0 < h`. Here, we record `x`, `y`, `h`. -/ def is_corner (s : finset (ℕ × ℕ)) : ℕ → ℕ → ℕ → Prop := λ x y h, (x, y) ∈ s ∧ (x + h, y) ∈ s ∧ (x, y + h) ∈ s /-- A corner in `s` is three points of the form `(x, y), (x + h, y), (x, y + h)` with `h < 0`. Here, we record `x`, `y`, `h`. Note that we use a slightly different formulation because of natural subtraction.-/ def is_anticorner (s : finset (ℕ × ℕ)) : ℕ → ℕ → ℕ → Prop := λ x y h, (x, y) ∈ s ∧ (h ≤ x ∧ (x - h, y) ∈ s) ∧ (h ≤ y ∧ (x, y - h) ∈ s) /-- The type of vertices of the corners graph. -/ inductive corners_vertices (N : ℕ) | horiz : fin N → corners_vertices | vert : fin N → corners_vertices | diag : fin (2 * N) → corners_vertices open corners_vertices instance (N : ℕ) : inhabited (corners_vertices (N + 1)) := ⟨vert default⟩ instance : fintype (corners_vertices N) := fintype.of_equiv (fin N ⊕ fin N ⊕ fin (2 * N)) { to_fun := sum.elim horiz (sum.elim vert diag), inv_fun := λ i, corners_vertices.rec_on i sum.inl (sum.inr ∘ sum.inl) (sum.inr ∘ sum.inr), left_inv := λ i, by { rcases i with (_ | _ | _); refl }, right_inv := λ i, by { rcases i with (_ | _ | _); refl } } @[simp] lemma card_corners_vertices : fintype.card (corners_vertices N) = 4 * N := by { simp only [fintype.of_equiv_card, fintype.card_fin, fintype.card_sum], ring } /-- The edges of the corners graph. -/ inductive corners_edge (s : finset (ℕ × ℕ)) : corners_vertices N → corners_vertices N → Prop | hv {h v : fin N} : ((h : ℕ), (v : ℕ)) ∈ s → corners_edge (horiz h) (vert v) | vh {h v : fin N} : ((h : ℕ), (v : ℕ)) ∈ s → corners_edge (vert v) (horiz h) | hd {h : fin N} {k : fin (2 * N)} : (h : ℕ) ≤ k → ((h : ℕ), (k : ℕ) - h) ∈ s → corners_edge (horiz h) (diag k) | dh {h : fin N} {k : fin (2 * N)} : (h : ℕ) ≤ k → ((h : ℕ), (k : ℕ) - h) ∈ s → corners_edge (diag k) (horiz h) | vd {v : fin N} {k : fin (2 * N)} : (v : ℕ) ≤ k → ((k : ℕ) - v, (v : ℕ)) ∈ s → corners_edge (vert v) (diag k) | dv {v : fin N} {k : fin (2 * N)} : (v : ℕ) ≤ k → ((k : ℕ) - v, (v : ℕ)) ∈ s → corners_edge (diag k) (vert v) variables {s : finset (ℕ × ℕ)} section corners_edge open corners_edge lemma corners_edge_symm : ∀ (x y : corners_vertices N), corners_edge s x y → corners_edge s y x | _ _ (hv h) := vh h | _ _ (vh h) := hv h | _ _ (hd h₁ h₂) := dh h₁ h₂ | _ _ (dh h₁ h₂) := hd h₁ h₂ | _ _ (vd h₁ h₂) := dv h₁ h₂ | _ _ (dv h₁ h₂) := vd h₁ h₂ lemma corners_edge_irrefl : ∀ (x : corners_vertices N), ¬ corners_edge s x x. /-- Picturing a `N × N` grid, this is the graph whose vertices are vertical, horizontal and diagonal (one way) lines and whose edges are the pairs of lines that meet within `s`. -/ def corners_graph (N : ℕ) (s : finset (ℕ × ℕ)) : simple_graph (corners_vertices N) := { adj := corners_edge s, symm := corners_edge_symm, loopless := corners_edge_irrefl } @[simp] lemma corners_edge_horiz_vert {h v : fin N} : (corners_graph _ s).adj (horiz h) (vert v) ↔ ((h : ℕ), (v : ℕ)) ∈ s := ⟨by { rintro ⟨⟩, assumption }, corners_edge.hv⟩ @[simp] lemma corners_edge_horiz_diag {h : fin N} {k} : (corners_graph _ s).adj (horiz h) (diag k) ↔ (h : ℕ) ≤ k ∧ ((h : ℕ), (k : ℕ) - h) ∈ s := ⟨by { rintro ⟨⟩, tauto }, λ i, corners_edge.hd i.1 i.2⟩ @[simp] lemma corners_edge_vert_diag {v : fin N} {k} : (corners_graph _ s).adj (vert v) (diag k) ↔ (v : ℕ) ≤ k ∧ ((k : ℕ) - v, (v : ℕ)) ∈ s := ⟨by { rintro ⟨⟩, tauto }, λ i, corners_edge.vd i.1 i.2⟩ /-- Throwaway tactic. -/ meta def sets_simp : tactic unit := `[ext] >> `[simp only [finset.mem_insert, finset.mem_singleton]] >> `[try {tauto}] lemma corners_triple {s : finset (ℕ × ℕ)} {N : ℕ} : ∀ x y z, (corners_graph N s).adj x y → (corners_graph N s).adj x z → (corners_graph N s).adj y z → ∃ h v {k : fin (2 * N)}, {horiz h, vert v, diag k} = ({x, y, z} : finset (corners_vertices N)) ∧ (corners_graph _ s).adj (horiz h) (vert v) ∧ (corners_graph _ s).adj (horiz h) (diag k) ∧ (corners_graph _ s).adj (vert v) (diag k) | _ _ _ h₁@(hv _) h₂@(hd _ _) h₃ := ⟨_, _, _, rfl, h₁, h₂, h₃⟩ | _ _ _ (vh h₁) (vd h₂ i₂) (hd h₃ i₃) := ⟨_, _, _, by sets_simp, hv h₁, hd h₃ i₃, vd h₂ i₂⟩ | _ _ _ (hd h₁ i₁) (hv h₂) (dv h₃ i₃) := ⟨_, _, _, by sets_simp, hv h₂, hd h₁ i₁, vd h₃ i₃⟩ | _ _ _ (dh h₁ i₁) (dv h₂ i₂) (hv h₃) := ⟨_, _, _, by sets_simp, hv h₃, hd h₁ i₁, vd h₂ i₂⟩ | _ _ _ (vd h₁ i₁) (vh h₂) (dh h₃ i₃) := ⟨_, _, _, by sets_simp, hv h₂, hd h₃ i₃, vd h₁ i₁⟩ | _ _ _ (dv h₁ i₁) (dh h₂ i₂) (vh h₃) := ⟨_, _, _, by sets_simp, hv h₃, hd h₂ i₂, vd h₁ i₁⟩ end corners_edge /-- Maps an horizontal, a vertical and a diagonal line to their three points of intersection. -/ noncomputable def triangle_map : fin N × fin N × fin (2 * N) → finset (corners_vertices N) := λ hvk, {horiz hvk.1, vert hvk.2.1, diag hvk.2.2} /-- State whether an horizontal, a vertical and a diagonal line meet within `s`. -/ @[derive decidable_pred] def explicit_triangles (s : finset (ℕ × ℕ)) (N : ℕ) : fin N × fin N × fin (2 * N) → Prop := λ (i : fin N × fin N × fin (2 * N)), (↑i.1, ↑i.2.1) ∈ s ∧ ((i.1 : ℕ) ≤ i.2.2 ∧ (↑i.1, ↑i.2.2 - ↑i.1) ∈ s) ∧ ((i.2.1 : ℕ) ≤ i.2.2 ∧ (↑i.2.2 - ↑i.2.1, ↑i.2.1) ∈ s) lemma triangle_map_mem (x : fin N × fin N × fin (2 * N)) (hx : explicit_triangles s N x) : triangle_map x ∈ (corners_graph N s).triangle_finset := by simpa [simple_graph.mem_triangle_finset'', explicit_triangles, triangle_map] using hx lemma triangle_map_injective : function.injective (triangle_map : _ → finset (corners_vertices N)) := begin rintro ⟨h₁, v₁, k₁⟩ ⟨h₂, v₂, k₂⟩, simpa only [triangle_map, finset.subset.antisymm_iff, subset_iff, mem_insert, mem_singleton, forall_eq_or_imp, forall_eq, prod.mk.inj_iff, or_false, false_or] using and.left, end lemma triangle_map_surj {t} (ht : t ∈ (corners_graph N s).triangle_finset) : ∃ a, explicit_triangles s N a ∧ triangle_map a = t := begin rw simple_graph.mem_triangle_finset''' at ht, obtain ⟨x, y, z, xy, xz, yz, rfl⟩ := ht, obtain ⟨h, v, k, i₀, i₁, i₂, i₃⟩ := corners_triple _ _ _ xy xz yz, exact ⟨⟨h, v, k⟩, ⟨by simpa using i₁, by simpa using i₂, by simpa using i₃⟩, i₀⟩, end lemma triangles_corners_graph {s : finset (ℕ × ℕ)} {N : ℕ} : (corners_graph N s).triangle_finset.card = (univ.filter (explicit_triangles s N)).card := begin refine (card_congr (λ a _, triangle_map a) (λ t ht, _) (λ x y _ _, _) (λ t ht, _)).symm, { apply triangle_map_mem _ (mem_filter.1 ht).2 }, { apply triangle_map_injective }, obtain ⟨_, ht', rfl⟩ := triangle_map_surj ht, exact ⟨w, by simpa using ht', rfl⟩, end lemma triangle_gives_corner_or_anticorner {h v : fin N} {k : fin (2 * N)} (hv : (↑h, ↑v) ∈ s) (hk₁ : (h : ℕ) ≤ k) (hk₁' : ((h : ℕ), (k : ℕ) - h) ∈ s) (vk₁ : (v : ℕ) ≤ k) (vk₁' : ((k : ℕ) - v, (v : ℕ)) ∈ s) : ((h : ℕ) + v ≤ k ∧ is_corner s h v (k - (h + v))) ∨ ((k : ℕ) ≤ h + v ∧ is_anticorner s h v (h + v - k)) := begin cases le_total ((h : ℕ) + v) (k : ℕ) with hvk hvk, { refine or.inl ⟨hvk, hv, _, _⟩, { rwa [←nat.add_sub_assoc hvk, nat.add_sub_add_left] }, { rwa [←nat.add_sub_assoc hvk, add_comm (v : ℕ), nat.add_sub_add_right] } }, { have hvkh : (h : ℕ) + v - k ≤ h, { rwa [tsub_le_iff_right, add_le_add_iff_left], }, have hvkv : (h : ℕ) + v - k ≤ v, { rwa [tsub_le_iff_right, add_comm, add_le_add_iff_left] }, refine or.inr ⟨hvk, hv, ⟨hvkh, _⟩, ⟨hvkv, _⟩⟩, { convert vk₁' using 2, rw [tsub_eq_iff_eq_add_of_le hvkh, ←nat.sub_add_comm vk₁, nat.add_sub_of_le hvk, add_tsub_cancel_right] }, { convert hk₁' using 2, rw [eq_tsub_iff_add_eq_of_le hk₁, add_comm, ←nat.add_sub_assoc hvkv, nat.sub_sub_self hvk] } } end lemma triangle_trivial_of_no_corners (cs : ∀ (x y h : ℕ), is_corner s x y h → h = 0) (as : ∀ (x y h : ℕ), is_anticorner s x y h → h = 0) {h v : fin N} {k : fin (2 * N)} (hv : (↑h, ↑v) ∈ s) (hk₁ : (h : ℕ) ≤ k) (hk₁' : ((h : ℕ), (k : ℕ) - h) ∈ s) (vk₁ : (v : ℕ) ≤ k) (vk₁' : ((k : ℕ) - v, (v : ℕ)) ∈ s) : (k : ℕ) = h + v := begin rcases triangle_gives_corner_or_anticorner hv hk₁ hk₁' vk₁ vk₁' with (⟨i₁, i₂⟩ | ⟨i₁, i₂⟩), { apply le_antisymm (nat.le_of_sub_eq_zero (cs _ _ _ i₂)) i₁ }, { apply le_antisymm i₁ (nat.le_of_sub_eq_zero (as _ _ _ i₂)) }, end lemma trivial_triangles_corners_graph {s : finset (ℕ × ℕ)} {n : ℕ} (cs : ∀ (x y h : ℕ), is_corner s x y h → h = 0) (as : ∀ (x y h : ℕ), is_anticorner s x y h → h = 0) : (corners_graph n s).triangle_finset.card ≤ n^2 := begin have : ((range n).product (range n)).card = n^2, { simp [sq] }, rw [←this, triangles_corners_graph], refine card_le_card_of_inj_on (λ i, ⟨i.1, i.2.1⟩) _ _, { rintro ⟨h, v, k⟩ -, simp only [mem_range, mem_product], exact ⟨h.prop, v.prop⟩ }, simp only [true_and, prod.forall, mem_filter, mem_univ, prod.mk.inj_iff, explicit_triangles], rintro h ⟨v, k₁⟩ ⟨hv, ⟨hk₁', hk₁⟩, vk₁', vk₁⟩ h₂ ⟨v₂, k₂⟩ ⟨-, ⟨hk₂', hk₂⟩, vk₂', vk₂⟩ ⟨heq, veq⟩, dsimp at *, rw subtype.coe_injective.eq_iff at heq veq, substs heq veq, simp only [true_and, prod.mk.inj_iff, eq_self_iff_true, subtype.ext_iff], rw triangle_trivial_of_no_corners cs as hv hk₁' hk₁ vk₁' vk₁, rw triangle_trivial_of_no_corners cs as hv hk₂' hk₂ vk₂' vk₂, end /-- The trivial triangles -/ def trivial_triangles (N : ℕ) (s : finset (ℕ × ℕ)) : finset (fin N × fin N × fin (2 * N)) := univ.filter (λ xyz, (↑xyz.1, ↑xyz.2.1) ∈ s ∧ (xyz.1 : ℕ) + xyz.2.1 = xyz.2.2) lemma trivial_triangles_mem : ∀ x ∈ trivial_triangles N s, explicit_triangles s N x := λ ⟨h, v, k⟩ t, begin simp only [trivial_triangles, true_and, mem_filter, mem_univ] at t, exact ⟨t.1, by simp [←t.2, t.1]⟩, end lemma card_trivial_triangles (hA : s ⊆ (range N).product (range N)) : (trivial_triangles N s).card = s.card := begin refine card_congr (λ xyz _, (xyz.1, xyz.2.1)) _ _ _, { rintro ⟨x, y, z⟩ t, apply (mem_filter.1 t).2.1 }, { rintro ⟨x₁, y₁, z₁⟩ ⟨x₂, y₂, z₂⟩ t₁ t₂ hxy, simp only [prod.mk.inj_iff] at hxy, simp only [prod.mk.inj_iff, subtype.ext_iff, ←and.assoc, hxy, true_and, eq_self_iff_true], rw ←(mem_filter.1 t₁).2.2, rw ←(mem_filter.1 t₂).2.2, simp [hxy.1, hxy.2] }, rintro ⟨x, y⟩ hxy, have := hA hxy, simp only [mem_range, mem_product] at this, refine ⟨⟨⟨_, this.1⟩, ⟨_, this.2⟩, ⟨x + y, _⟩⟩, mem_filter.2 ⟨mem_univ _, hxy, rfl⟩, rfl⟩, rw two_mul, apply add_lt_add this.1 this.2, end lemma disjoint_triangles {ε : ℝ} (hA : s ⊆ (range N).product (range N)) (hA' : ε * N^2 ≤ s.card) : (corners_graph N s).triangle_free_far (ε/16) := begin refine simple_graph.triangle_free_far_of_disjoint_triangles ((trivial_triangles N s).map ⟨_, triangle_map_injective⟩) _ _ _, { simp only [subset_iff, and_imp, exists_prop, forall_exists_index, function.embedding.coe_fn_mk, mem_map], rintro _ x hx rfl, apply triangle_map_mem _ (trivial_triangles_mem _ hx), }, { simp only [set.pairwise, mem_map, mem_coe, forall_exists_index, prod.forall, prod.forall', function.embedding.coe_fn_mk, trivial_triangles, true_and, and_imp, mem_filter, mem_univ], rintro _ ⟨h₁, _⟩ ⟨⟨v₁, _⟩, ⟨_, k₁⟩⟩ t₁ i₁ rfl _ ⟨h₂, _⟩ ⟨⟨v₂, _⟩, ⟨_, k₂⟩⟩ t₂ i₂ rfl q, dsimp at i₁ i₂ t₁ t₂, substs i₁ i₂, rw triangle_map_injective.ne_iff at q, dsimp [triangle_map], simp only [prod.mk.inj_iff, subtype.mk_eq_mk, ne.def] at q, rw finset.card_le_one, simp only [and_imp, mem_insert, mem_inter, mem_singleton, true_and, forall_eq_or_imp, and_true, false_or, forall_eq, implies_true_iff, eq_self_iff_true, subtype.mk_eq_mk, or_false, forall_and_distrib, and_assoc, @imp.swap (_ + _ = _)], refine ⟨_, _, _, _, _, _⟩; { intros i₁ i₂, apply q, simpa [i₁] using i₂ } }, rw [card_map, card_trivial_triangles hA, card_corners_vertices], norm_num, linarith, end lemma weak_corners_theorem {ε : ℝ} (hε : 0 < ε) : ∃ n₀ : ℕ, ∀ n, n₀ ≤ n → ∀ s ⊆ (range n).product (range n), ε * n^2 ≤ s.card → ∃ x y h, 0 < h ∧ (is_corner s x y h ∨ is_anticorner s x y h) := begin refine ⟨⌊1/(simple_graph.triangle_removal_bound (ε / 16) * 64)⌋₊ + 1, λ n hn s hA hA', _⟩, rw nat.add_one_le_iff at hn, have n_pos : 0 < n := (nat.zero_le _).trans_lt hn, have : ε ≤ 1, { have := hA'.trans (nat.cast_le.2 (card_le_of_subset hA)), simp only [sq, card_range, nat.cast_mul, card_product] at this, rwa mul_le_iff_le_one_left at this, exact mul_pos (nat.cast_pos.2 n_pos) (nat.cast_pos.2 n_pos) }, have tf : (corners_graph n s).triangle_free_far (ε/16) := disjoint_triangles hA hA', by_contra h, simp only [not_and', or_imp_distrib, forall_and_distrib, not_exists, not_lt, le_zero_iff] at h, have h₁ := simple_graph.triangle_removal_2 (show 0 < ε/16, by linarith) (by linarith) tf, rw card_corners_vertices at h₁, have i := h₁.trans (nat.cast_le.2 (trivial_triangles_corners_graph h.1 h.2)), rw [nat.cast_mul, mul_pow, nat.cast_pow, ←mul_assoc] at i, norm_num at i, have : simple_graph.triangle_removal_bound (ε / 16) * 64 * n ≤ 1, { apply le_of_mul_le_mul_right _ (sq_pos_of_ne_zero (n : ℝ) (nat.cast_ne_zero.2 n_pos.ne')), rwa [one_mul, mul_assoc, ←pow_succ] }, have po : 0 < simple_graph.triangle_removal_bound (ε / 16) * 64 := mul_pos (simple_graph.triangle_removal_bound_pos (by linarith) (by linarith)) (by norm_num), apply not_lt_of_le this, rwa [nat.floor_lt (one_div_nonneg.2 po.le), div_lt_iff' po] at hn, end lemma alt_set (c : ℕ × ℕ) (s : finset (ℕ × ℕ)) : (s.filter (λ (x : ℕ × ℕ), x.1 ≤ c.1 ∧ x.2 ≤ c.2 ∧ (c.1 - x.1, c.2 - x.2) ∈ s)).card = ((s.product s).filter (λ (x : (ℕ × ℕ) × ℕ × ℕ), (x.1.1 + x.2.1, x.1.2 + x.2.2) = c)).card := begin rcases c with ⟨c₁, c₂⟩, refine (card_congr (λ (a : _ × _) ha, a.1) _ _ _).symm, { rintro ⟨⟨a₁, a₂⟩, b₁, b₂⟩ i, dsimp, simp only [mem_filter, mem_product, prod.mk.inj_iff] at i, simp only [mem_filter], rw [←i.2.1, ←i.2.2], simpa using i.1 }, { dsimp, simp only [prod.forall, mem_filter, mem_product, prod.mk.inj_iff], rintro a₁ a₂ ⟨a₃, a₄⟩ ⟨⟨a₅, a₆⟩, a₇, a₈⟩ ⟨-, rfl, rfl⟩ ⟨_, h₁⟩ ⟨⟩, simpa [eq_comm] using h₁ }, simp only [and_imp, exists_prop, prod.forall, mem_filter, exists_and_distrib_right, prod.mk.inj_iff, exists_eq_right_right, exists_eq_right, prod.exists, mem_product], intros x y xy hx hy t, refine ⟨_, _, ⟨xy, t⟩, _, _⟩, { rw [←nat.add_sub_assoc hx, nat.add_sub_cancel_left] }, { rw [←nat.add_sub_assoc hy, nat.add_sub_cancel_left] }, end lemma correlate {n : ℕ} (hn : 0 < n) (s : finset (ℕ × ℕ)) (hA : s ⊆ (range n).product (range n)) : ∃ c ∈ (range (2 * n)).product (range (2 * n)), (s.card : ℝ)^2 / ((2 * n)^2) ≤ (s.filter (λ (xy : ℕ × ℕ), xy.1 ≤ c.1 ∧ xy.2 ≤ c.2 ∧ (c.1 - xy.1, c.2 - xy.2) ∈ s)).card := begin simp_rw [alt_set _ s], let f : (ℕ × ℕ) × ℕ × ℕ → ℕ × ℕ := λ ab, (ab.1.1 + ab.2.1, ab.1.2 + ab.2.2), have : ∀ a ∈ s.product s, f a ∈ (range (2 * n)).product (range (2 * n)), { rintro ⟨⟨a₁, a₂⟩, a₃, a₄⟩ h, simp only [mem_product] at h, have i := and.intro (hA h.1) (hA h.2), simp only [mem_range, mem_product] at i, simp only [mem_product, mem_range, two_mul], exact ⟨add_lt_add i.1.1 i.2.1, add_lt_add i.1.2 i.2.2⟩ }, refine exists_le_card_fiber_of_mul_le_card_of_maps_to' this _ _, { simp [hn.ne'] }, { simp only [card_product, card_range, nsmul_eq_mul, nat.cast_pow, nat.cast_two, nat.cast_mul, ←sq], rw [mul_div_assoc', mul_div_cancel_left], simp [hn.ne'] } end lemma corners_theorem {ε : ℝ} (hε : 0 < ε) : ∃ n₀ : ℕ, ∀ n, n₀ ≤ n → ∀ s ⊆ (range n).product (range n), ε * n^2 ≤ s.card → ∃ x y h, 0 < h ∧ is_corner s x y h := begin let ε' : ℝ := (ε/2)^2, have hε' : 0 < ε' := pow_pos (by linarith) _, obtain ⟨n₀, hn₀⟩ := weak_corners_theorem hε', refine ⟨n₀ + 1, λ n hn s hA hAcard, _⟩, obtain ⟨⟨c₁, c₂⟩, -, hA'card⟩ := correlate (nat.succ_pos'.trans_le hn) s hA, let A' : finset (ℕ × ℕ) := s.filter (λ xy, xy.1 ≤ c₁ ∧ xy.2 ≤ c₂ ∧ (c₁ - xy.1, c₂ - xy.2) ∈ s), have hA' : A' ⊆ s := filter_subset _ _, have : (s.card : ℝ)^2 / ((2 * n)^2) ≤ A'.card := hA'card, by_contra h, simp only [not_and', or_imp_distrib, forall_and_distrib, not_exists, not_lt, le_zero_iff] at h, have nc : ¬(∃ (x y h : ℕ), 0 < h ∧ (is_corner A' x y h ∨ is_anticorner A' x y h)), { simp only [not_exists, not_and', not_lt, or_imp_distrib, le_zero_iff, forall_and_distrib], refine ⟨λ x y k i, h x y k ⟨hA' i.1, hA' i.2.1, hA' i.2.2⟩, _⟩, { rintro x y k ⟨xy, ⟨kx, xky⟩, ky, xyk⟩, simp only [mem_filter] at xy xky xyk, rw tsub_tsub_assoc xy.2.2.1 ky at xyk, rw tsub_tsub_assoc xy.2.1 kx at xky, apply h (c₁ - x) (c₂ - y) k ⟨xy.2.2.2, xky.2.2.2, xyk.2.2.2⟩ } }, refine nc (hn₀ _ ((nat.le_succ _).trans hn) A' (hA'.trans hA) (le_trans _ this)), rw [←mul_pow, ←div_pow], refine pow_le_pow_of_le_left (mul_nonneg (by linarith) (nat.cast_nonneg _)) _ _, rw le_div_iff, { exact (le_of_eq (by ring)).trans hAcard }, exact mul_pos zero_lt_two (nat.cast_pos.2 (nat.succ_pos'.trans_le hn)), end lemma roth (δ : ℝ) (hδ : 0 < δ) : ∃ n₀ : ℕ, ∀ n, n₀ ≤ n → ∀ s ⊆ range n, δ * n ≤ s.card → ∃ a d, 0 < d ∧ a ∈ s ∧ a + d ∈ s ∧ a + 2 * d ∈ s := begin let δ' : ℝ := δ/4, have hδ' : 0 < δ' := div_pos hδ (by norm_num), obtain ⟨n₀, hn₀⟩ := corners_theorem hδ', refine ⟨n₀, λ n hn s hA hAcard, _⟩, let B : finset (ℕ × ℕ) := ((range (2 * n)).product (range (2 * n))).filter (λ xy, xy.1 ≤ xy.2 ∧ xy.2 - xy.1 ∈ s), have : n * card s ≤ card B, { rw [←card_range n, ←card_product], refine card_le_card_of_inj_on (λ ia, (ia.1, ia.1 + ia.2)) _ _, { rintro ⟨i, a⟩ t, simp only [mem_range, mem_product] at t, simp only [true_and, mem_filter, add_tsub_cancel_left, mem_range, le_add_iff_nonneg_right, zero_le', mem_product, t.2, and_true, two_mul], exact ⟨t.1.trans_le (nat.le_add_right _ _), add_lt_add t.1 (mem_range.1 (hA t.2))⟩ }, simp only [and_imp, prod.forall, mem_range, prod.mk.inj_iff, mem_product], rintro i a₁ hi ha₁ _ a₂ - ha₂ rfl, simp }, have : δ' * ↑(2 * n) ^ 2 ≤ ↑(B.card), { refine le_trans _ (nat.cast_le.2 this), rw [nat.cast_mul, nat.cast_two, mul_pow, ←mul_assoc, nat.cast_mul], norm_num, rw [sq, ←mul_assoc, mul_comm _ (s.card : ℝ)], apply mul_le_mul_of_nonneg_right hAcard (nat.cast_nonneg _) }, obtain ⟨x, y, k, hk, xy, xky, xyk⟩ := hn₀ _ (hn.trans (nat.le_mul_of_pos_left zero_lt_two)) B (filter_subset _ _) this, refine ⟨y - (x + k), k, hk, (mem_filter.1 xky).2.2, _, _⟩, { rw [←nat.sub_add_comm (mem_filter.1 xky).2.1, nat.add_sub_add_right], apply (mem_filter.1 xy).2.2 }, { rw [←nat.sub_add_comm (mem_filter.1 xky).2.1, two_mul, ←add_assoc, nat.add_sub_add_right], apply (mem_filter.1 xyk).2.2 }, end lemma roth' (δ : ℝ) (hδ : 0 < δ) : ∃ n₀ : ℕ, ∀ n, n₀ ≤ n → ∀ s ⊆ range n, δ * n ≤ s.card → ¬ add_salem_spencer (s : set ℕ) := begin obtain ⟨n₀, hn₀⟩ := roth δ hδ, refine ⟨n₀, λ n hn s hA hAcard hA', _⟩, obtain ⟨a, d, hd, x, y, z⟩ := hn₀ n hn s hA hAcard, exact mul_ne_zero two_ne_zero hd.ne' (self_eq_add_right.1 $ hA' x z y $ by ring), end open asymptotics filter lemma roth_asymptotic : is_o (λ N, (roth_number_nat N : ℝ)) (λ N, (N : ℝ)) at_top := begin rw is_o_iff, intros δ hδ, rw eventually_at_top, obtain ⟨n₀, hn₀⟩ := roth' δ hδ, refine ⟨n₀, λ n hn, _⟩, simp only [real.norm_coe_nat, ←not_lt], obtain ⟨s, hA₁, hA₂, hA₃⟩ := add_roth_number_spec (range n), refine λ h, (hn₀ n hn _ hA₁ _) hA₃, rw hA₂, exact h.le, end
fd67ff8fa46f0bb760bb10e051ce5803743d38af
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.14.lean
267ece5edd49a5f26111d78a656390d542c188d7
[]
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
405
lean
/- page 105 -/ import standard import data.examples.vector open nat vector prod -- BEGIN variables {A B : Type} definition unzip : Π {n : nat}, vector (A × B) n → vector A n × vector B n | zero nil := (nil, nil) | (succ n) ((a, b)::v) := match unzip v with (va, vb) := (a :: va, b :: vb) end example : unzip ((1, 10) :: (2, 20) :: nil) = (1 :: 2 :: nil, 10 :: 20 :: nil) := rfl -- END
50e2f7edb56302070f869d7f7f84654ae341f81a
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/suggest.lean
47ed0a70d02e534d1c3bb8a78b2ffd7d77dae893
[ "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
20,601
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen and Scott Morrison -/ import data.mllist import tactic.solve_by_elim /-! # `suggest` and `library_search` `suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the current goal. * `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals * `library_search` prints a single `exact ...` which closes the goal, or fails -/ namespace tactic open native namespace suggest open solve_by_elim /-- Map a name (typically a head symbol) to a "canonical" definitional synonym. Given a name `n`, we want a name `n'` such that a sufficiently applied expression with head symbol `n` is always definitionally equal to an expression with head symbol `n'`. Thus, we can search through all lemmas with a result type of `n'` to solve a goal with head symbol `n`. For example, `>` is mapped to `<` because `a > b` is definitionally equal to `b < a`, and `not` is mapped to `false` because `¬ a` is definitionally equal to `p → false` The default is that the original argument is returned, so `<` is just mapped to `<`. `normalize_synonym` is called for every lemma in the library, so it needs to be fast. -/ -- TODO this is a hack; if you suspect more cases here would help, please report them meta def normalize_synonym : name → name | `gt := `has_lt.lt | `ge := `has_le.le | `monotone := `has_le.le | `not := `false | n := n /-- Compute the head symbol of an expression, then normalise synonyms. This is only used when analysing the goal, so it is okay to do more expensive analysis here. -/ -- We may want to tweak this further? meta def allowed_head_symbols : expr → list name -- We first have a various "customisations": -- Because in `ℕ` `a.succ ≤ b` is definitionally `a < b`, -- we add some special cases to allow looking for `<` lemmas even when the goal has a `≤`. -- Note we only do this in the `ℕ` case, for performance. | `(@has_le.le ℕ _ (nat.succ _) _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ (nat.succ _)) := [`has_le.le, `has_lt.lt] | `(@has_le.le ℕ _ 1 _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ 1) := [`has_le.le, `has_lt.lt] -- And then the generic cases: | (expr.pi _ _ _ t) := allowed_head_symbols t | (expr.app f _) := allowed_head_symbols f | (expr.const n _) := [normalize_synonym n] | _ := [`_] . /-- A declaration can match the head symbol of the current goal in four possible ways: * `ex` : an exact match * `mp` : the declaration returns an `iff`, and the right hand side matches the goal * `mpr` : the declaration returns an `iff`, and the left hand side matches the goal * `both`: the declaration returns an `iff`, and the both sides match the goal -/ @[derive decidable_eq, derive inhabited] inductive head_symbol_match | ex | mp | mpr | both open head_symbol_match /-- a textual representation of a `head_symbol_match`, for trace debugging. -/ def head_symbol_match.to_string : head_symbol_match → string | ex := "exact" | mp := "iff.mp" | mpr := "iff.mpr" | both := "iff.mp and iff.mpr" /-- Determine if, and in which way, a given expression matches the specified head symbol. -/ meta def match_head_symbol (hs : name_set) : expr → option head_symbol_match | (expr.pi _ _ _ t) := match_head_symbol t | `(%%a ↔ %%b) := if hs.contains `iff then some ex else match (match_head_symbol a, match_head_symbol b) with | (some ex, some ex) := some both | (some ex, _) := some mpr | (_, some ex) := some mp | _ := none end | (expr.app f _) := match_head_symbol f | (expr.const n _) := if hs.contains (normalize_synonym n) then some ex else none | _ := if hs.contains `_ then some ex else none /-- A package of `declaration` metadata, including the way in which its type matches the head symbol which we are searching for. -/ meta structure decl_data := (d : declaration) (n : name) (m : head_symbol_match) (l : ℕ) -- cached length of name /-- Generate a `decl_data` from the given declaration if it matches the head symbol `hs` for the current goal. -/ -- We used to check here for private declarations, or declarations with certain suffixes. -- It turns out `apply` is so fast, it's better to just try them all. meta def process_declaration (hs : name_set) (d : declaration) : option decl_data := let n := d.to_name in if !d.is_trusted || n.is_internal then none else (λ m, ⟨d, n, m, n.length⟩) <$> match_head_symbol hs d.type /-- Retrieve all library definitions with a given head symbol. -/ meta def library_defs (hs : name_set) : tactic (list decl_data) := do trace_if_enabled `suggest format!"Looking for lemmas with head symbols {hs}.", env ← get_env, let defs := env.decl_filter_map (process_declaration hs), -- Sort by length; people like short proofs let defs := defs.qsort(λ d₁ d₂, d₁.l ≤ d₂.l), trace_if_enabled `suggest format!"Found {defs.length} relevant lemmas:", trace_if_enabled `suggest $ defs.map (λ ⟨d, n, m, l⟩, (n, m.to_string)), return defs /-- We unpack any element of a list of `decl_data` corresponding to an `↔` statement that could apply in both directions into two separate elements. This ensures that both directions can be independently returned by `suggest`, and avoids a problem where the application of one direction prevents the application of the other direction. (See `exp_le_exp` in the tests.) -/ meta def unpack_iff_both : list decl_data → list decl_data | [] := [] | (⟨d, n, both, l⟩ :: L) := ⟨d, n, mp, l⟩ :: ⟨d, n, mpr, l⟩ :: unpack_iff_both L | (⟨d, n, m, l⟩ :: L) := ⟨d, n, m, l⟩ :: unpack_iff_both L /-- Apply the lemma `e`, then attempt to close all goals using `solve_by_elim opt`, failing if `close_goals = tt` and there are any goals remaining. Returns the number of subgoals which were closed using `solve_by_elim`. -/ -- Implementation note: as this is used by both `library_search` and `suggest`, -- we first run `solve_by_elim` separately on the independent goals, -- whether or not `close_goals` is set, -- and then run `solve_by_elim { all_goals := tt }`, -- requiring that it succeeds if `close_goals = tt`. meta def apply_and_solve (close_goals : bool) (opt : opt := { }) (e : expr) : tactic ℕ := do trace_if_enabled `suggest format!"Trying to apply lemma: {e}", apply e opt.to_apply_cfg, trace_if_enabled `suggest format!"Applied lemma: {e}", ng ← num_goals, -- Phase 1 -- Run `solve_by_elim` on each "safe" goal separately, not worrying about failures. -- (We only attempt the "safe" goals in this way in Phase 1. In Phase 2 we will do -- backtracking search across all goals, allowing us to guess solutions that involve data, or -- unify metavariables, but only as long as we can finish all goals.) try (any_goals (independent_goal >> solve_by_elim opt)), -- Phase 2 (done >> return ng) <|> (do -- If there were any goals that we did not attempt solving in the first phase -- (because they weren't propositional, or contained a metavariable) -- as a second phase we attempt to solve all remaining goals at once -- (with backtracking across goals). (any_goals (success_if_fail independent_goal) >> solve_by_elim { backtrack_all_goals := tt, ..opt }) <|> -- and fail unless `close_goals = ff` guard ¬ close_goals, ng' ← num_goals, return (ng - ng')) /-- Apply the declaration `d` (or the forward and backward implications separately, if it is an `iff`), and then attempt to solve the subgoal using `apply_and_solve`. Returns the number of subgoals successfully closed. -/ meta def apply_declaration (close_goals : bool) (opt : opt := { }) (d : decl_data) : tactic ℕ := let tac := apply_and_solve close_goals opt in do (e, t) ← decl_mk_const d.d, match d.m with | ex := tac e | mp := do l ← iff_mp_core e t, tac l | mpr := do l ← iff_mpr_core e t, tac l | both := undefined -- we use `unpack_iff_both` to ensure this isn't reachable end /-- An `application` records the result of a successful application of a library lemma. -/ meta structure application := (state : tactic_state) (script : string) (decl : option declaration) (num_goals : ℕ) (hyps_used : ℕ) end suggest open solve_by_elim open suggest declare_trace suggest -- Trace a list of all relevant lemmas -- Call `apply_declaration`, then prepare the tactic script and -- count the number of local hypotheses used. private meta def apply_declaration_script (g : expr) (hyps : list expr) (opt : opt := { }) (d : decl_data) : tactic application := -- (This tactic block is only executed when we evaluate the mllist, -- so we need to do the `focus1` here.) retrieve $ focus1 $ do apply_declaration ff opt d, ng ← num_goals, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, s ← read, m ← tactic_statement g, return { application . state := s, decl := d.d, script := m, num_goals := ng, hyps_used := hyps.countp (λ h, h.occurs g) } -- implementation note: we produce a `tactic (mllist tactic application)` first, -- because it's easier to work in the tactic monad, but in a moment we squash this -- down to an `mllist tactic application`. private meta def suggest_core' (opt : opt := { }) : tactic (mllist tactic application) := do g :: _ ← get_goals, hyps ← local_context, -- Make sure that `solve_by_elim` doesn't just solve the goal immediately: (retrieve (do focus1 $ solve_by_elim opt, s ← read, m ← tactic_statement g, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, return $ mllist.of_list [⟨s, m, none, 0, hyps.countp (λ h, h.occurs g)⟩])) <|> -- Otherwise, let's actually try applying library lemmas. (do -- Collect all definitions with the correct head symbol t ← infer_type g, defs ← unpack_iff_both <$> library_defs (name_set.of_list $ allowed_head_symbols t), let defs : mllist tactic _ := mllist.of_list defs, -- Try applying each lemma against the goal, -- recording the tactic script as a string, -- the number of remaining goals, -- and number of local hypotheses used. let results := defs.mfilter_map (apply_declaration_script g hyps opt), -- Now call `symmetry` and try again. -- (Because we are using `mllist`, this is essentially free if we've already found a lemma.) symm_state ← retrieve $ try_core $ symmetry >> read, let results_symm := match symm_state with | (some s) := defs.mfilter_map (λ d, retrieve $ set_state s >> apply_declaration_script g hyps opt d) | none := mllist.nil end, return (results.append results_symm)) /-- The core `suggest` tactic. It attempts to apply a declaration from the library, then solve new goals using `solve_by_elim`. It returns a list of `application`s consisting of fields: * `state`, a tactic state resulting from the successful application of a declaration from the library, * `script`, a string of the form `refine ...` or `exact ...` which will reproduce that tactic state, * `decl`, an `option declaration` indicating the declaration that was applied (or none, if `solve_by_elim` succeeded), * `num_goals`, the number of remaining goals, and * `hyps_used`, the number of local hypotheses used in the solution. -/ meta def suggest_core (opt : opt := { }) : mllist tactic application := (mllist.monad_lift (suggest_core' opt)).join /-- See `suggest_core`. Returns a list of at most `limit` `application`s, sorted by number of goals, and then (reverse) number of hypotheses used. -/ meta def suggest (limit : option ℕ := none) (opt : opt := { }) : tactic (list application) := do let results := suggest_core opt, -- Get the first n elements of the successful lemmas L ← if h : limit.is_some then results.take (option.get h) else results.force, -- Sort by number of remaining goals, then by number of hypotheses used. return $ L.qsort (λ d₁ d₂, d₁.num_goals < d₂.num_goals ∨ (d₁.num_goals = d₂.num_goals ∧ d₁.hyps_used ≥ d₂.hyps_used)) /-- Returns a list of at most `limit` strings, of the form `exact ...` or `refine ...`, which make progress on the current goal using a declaration from the library. -/ meta def suggest_scripts (limit : option ℕ := none) (opt : opt := { }) : tactic (list string) := do L ← suggest limit opt, return $ L.map application.script /-- Returns a string of the form `exact ...`, which closes the current goal. -/ meta def library_search (opt : opt := { }) : tactic string := (suggest_core opt).mfirst (λ a, do guard (a.num_goals = 0), write a.state, return a.script) namespace interactive open tactic open interactive open lean.parser open interactive.types open solve_by_elim local postfix `?`:9001 := optional declare_trace silence_suggest -- Turn off `exact/refine ...` trace messages for `suggest` /-- `suggest` tries to apply suitable theorems/defs from the library, and generates a list of `exact ...` or `refine ...` scripts that could be used at this step. It leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def suggest (n : parse (with_desc "n" small_nat)?) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do asms ← mk_assumption_set ff hs attr_names, L ← tactic.suggest_scripts (n.get_or_else 50) { lemma_thunks := return asms, ..opt }, if is_trace_enabled_for `silence_suggest then skip else if L.length = 0 then fail "There are no applicable declarations" else L.mmap trace >> skip /-- `suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. An example of `suggest` in action, ```lean example (n : nat) : n < n + 1 := begin suggest, sorry end ``` prints the list, ```lean Try this: exact nat.lt.base n Try this: exact nat.lt_succ_self n Try this: refine not_le.mp _ Try this: refine gt_iff_lt.mp _ Try this: refine nat.lt.step _ Try this: refine lt_of_not_ge _ ... ``` -/ add_tactic_doc { name := "suggest", category := doc_category.tactic, decl_names := [`tactic.interactive.suggest], tags := ["search", "Try this"] } declare_trace silence_library_search -- Turn off `exact ...` trace message for `library_search /-- `library_search` attempts to apply every definition in the library whose head symbol matches the goal, and then discharge any new goals using `solve_by_elim`. If it succeeds, it prints a trace message `exact ...` which can replace the invocation of `library_search`. By default `library_search` only unfolds `reducible` definitions when attempting to match lemmas against the goal. Previously, it would unfold most definitions, sometimes giving surprising answers, or slow answers. The old behaviour is still available via `library_search!`. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `library_search with attr` to include all lemmas with the attribute `attr`. -/ meta def library_search (semireducible : parse $ optional (tk "!")) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do asms ← mk_assumption_set ff hs attr_names, (tactic.library_search { backtrack_all_goals := tt, lemma_thunks := return asms, md := if semireducible.is_some then tactic.transparency.semireducible else tactic.transparency.reducible, ..opt } >>= if is_trace_enabled_for `silence_library_search then (λ _, skip) else trace) <|> fail "`library_search` failed. If you aren't sure what to do next, you can also try `library_search!`, `suggest`, or `hint`. Possible reasons why `library_search` failed: * `library_search` will only apply a single lemma from the library, and then try to fill in its hypotheses from local hypotheses. * If you haven't already, try stating the theorem you want in its own lemma. * Sometimes the library has one version of a lemma but not a very similar version obtained by permuting arguments. Try replacing `a + b` with `b + a`, or `a - b < c` with `a < b + c`, to see if maybe the lemma exists but isn't stated quite the way you would like. * Make sure that you have all the side conditions for your theorem to be true. For example you won't find `a - b + b = a` for natural numbers in the library because it's false! Search for `b ≤ a → a - b + b = a` instead. * If a definition you made is in the goal, you won't find any theorems about it in the library. Try unfolding the definition using `unfold my_definition`. * If all else fails, ask on https://leanprover.zulipchat.com/, and maybe we can improve the library and/or `library_search` for next time." /-- `library_search` is a tactic to identify existing lemmas in the library. It tries to close the current goal by applying a lemma from the library, then discharging any new goals using `solve_by_elim`. Typical usage is: ```lean example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- Try this: exact nat.mul_sub_left_distrib n m k ``` `library_search` prints a trace message showing the proof it found, shown above as a comment. Typically you will then copy and paste this proof, replacing the call to `library_search`. -/ add_tactic_doc { name := "library_search", category := doc_category.tactic, decl_names := [`tactic.interactive.library_search], tags := ["search", "Try this"] } end interactive /-- Invoking the hole command `library_search` ("Use `library_search` to complete the goal") calls the tactic `library_search` to produce a proof term with the type of the hole. Running it on ```lean example : 0 < 1 := {!!} ``` produces ```lean example : 0 < 1 := nat.one_pos ``` -/ @[hole_command] meta def library_search_hole_cmd : hole_command := { name := "library_search", descr := "Use `library_search` to complete the goal.", action := λ _, do script ← library_search, -- Is there a better API for dropping the 'exact ' prefix on this string? return [((script.mk_iterator.remove 6).to_string, "by library_search")] } add_tactic_doc { name := "library_search", category := doc_category.hole_cmd, decl_names := [`tactic.library_search_hole_cmd], tags := ["search", "Try this"] } end tactic
361dacf05ff19bb82c7cb244581e6d18f98adb87
626e312b5c1cb2d88fca108f5933076012633192
/src/group_theory/nilpotent.lean
fb140b51c454638f67ab4f29d922d587d19cc8c4
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,334
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Ines Wright -/ import group_theory.general_commutator import group_theory.quotient_group /-! # Nilpotent groups An API for nilpotent groups, that is, groups for which the upper central series reaches `⊤`. ## Main definitions Recall that if `H K : subgroup G` then `⁅H, K⁆ : subgroup G` is the subgroup of `G` generated by the commutators `hkh⁻¹k⁻¹`. Recall also Lean's conventions that `⊤` denotes the subgroup `G` of `G`, and `⊥` denotes the trivial subgroup `{1}`. * `upper_central_series G : ℕ → subgroup G` : the upper central series of a group `G`. This is an increasing sequence of normal subgroups `H n` of `G` with `H 0 = ⊥` and `H (n + 1) / H n` is the centre of `G / H n`. * `lower_central_series G : ℕ → subgroup G` : the lower central series of a group `G`. This is a decreasing sequence of normal subgroups `H n` of `G` with `H 0 = ⊤` and `H (n + 1) = ⁅H n, G⁆`. * `is_nilpotent` : A group G is nilpotent if its upper central series reaches `⊤`, or equivalently if its lower central series reaches `⊥`. * `nilpotency_class` : the length of the upper central series of a nilpotent group. * `is_ascending_central_series (H : ℕ → subgroup G) : Prop` and * `is_descending_central_series (H : ℕ → subgroup G) : Prop` : Note that in the literature a "central series" for a group is usually defined to be a *finite* sequence of normal subgroups `H 0`, `H 1`, ..., starting at `⊤`, finishing at `⊥`, and with each `H n / H (n + 1)` central in `G / H (n + 1)`. In this formalisation it is convenient to have two weaker predicates on an infinite sequence of subgroups `H n` of `G`: we say a sequence is a *descending central series* if it starts at `G` and `⁅H n, ⊤⁆ ⊆ H (n + 1)` for all `n`. Note that this series may not terminate at `⊥`, and the `H i` need not be normal. Similarly a sequence is an *ascending central series* if `H 0 = ⊥` and `⁅H (n + 1), ⊤⁆ ⊆ H n` for all `n`, again with no requirement that the series reaches `⊤` or that the `H i` are normal. ## Main theorems `G` is *defined* to be nilpotent if the upper central series reaches `⊤`. * `nilpotent_iff_finite_ascending_central_series` : `G` is nilpotent iff some ascending central series reaches `⊤`. * `nilpotent_iff_finite_descending_central_series` : `G` is nilpotent iff some descending central series reaches `⊥`. * `nilpotent_iff_lower` : `G` is nilpotent iff the lower central series reaches `⊥`. ## Warning A "central series" is usually defined to be a finite sequence of normal subgroups going from `⊥` to `⊤` with the property that each subquotient is contained within the centre of the associated quotient of `G`. This means that if `G` is not nilpotent, then none of what we have called `upper_central_series G`, `lower_central_series G` or the sequences satisfying `is_ascending_central_series` or `is_descending_central_series` are actually central series. Note that the fact that the upper and lower central series are not central series if `G` is not nilpotent is a standard abuse of notation. -/ open subgroup variables {G : Type*} [group G] (H : subgroup G) [normal H] /-- If `H` is a normal subgroup of `G`, then the set `{x : G | ∀ y : G, x*y*x⁻¹*y⁻¹ ∈ H}` is a subgroup of `G` (because it is the preimage in `G` of the centre of the quotient group `G/H`.) -/ def upper_central_series_step : subgroup G := { carrier := {x : G | ∀ y : G, x * y * x⁻¹ * y⁻¹ ∈ H}, one_mem' := λ y, by simp [subgroup.one_mem], mul_mem' := λ a b ha hb y, begin convert subgroup.mul_mem _ (ha (b * y * b⁻¹)) (hb y) using 1, group, end, inv_mem' := λ x hx y, begin specialize hx y⁻¹, rw [mul_assoc, inv_inv] at ⊢ hx, exact subgroup.normal.mem_comm infer_instance hx, end } lemma mem_upper_central_series_step (x : G) : x ∈ upper_central_series_step H ↔ ∀ y, x * y * x⁻¹ * y⁻¹ ∈ H := iff.rfl open quotient_group /-- The proof that `upper_central_series_step H` is the preimage of the centre of `G/H` under the canonical surjection. -/ lemma upper_central_series_step_eq_comap_center : upper_central_series_step H = subgroup.comap (mk' H) (center (quotient H)) := begin ext, rw [mem_comap, mem_center_iff, forall_coe], apply forall_congr, intro y, change x * y * x⁻¹ * y⁻¹ ∈ H ↔ ((y * x : G) : quotient H) = (x * y : G), rw [eq_comm, eq_iff_div_mem, div_eq_mul_inv], congr' 2, group, end instance : normal (upper_central_series_step H) := begin rw upper_central_series_step_eq_comap_center, apply_instance, end variable (G) /-- An auxiliary type-theoretic definition defining both the upper central series of a group, and a proof that it is normal, all in one go. -/ def upper_central_series_aux : ℕ → Σ' (H : subgroup G), normal H | 0 := ⟨⊥, infer_instance⟩ | (n + 1) := let un := upper_central_series_aux n, un_normal := un.2 in by exactI ⟨upper_central_series_step un.1, infer_instance⟩ /-- `upper_central_series G n` is the `n`th term in the upper central series of `G`. -/ def upper_central_series (n : ℕ) : subgroup G := (upper_central_series_aux G n).1 instance (n : ℕ) : normal (upper_central_series G n) := (upper_central_series_aux G n).2 @[simp] lemma upper_central_series_zero : upper_central_series G 0 = ⊥ := rfl /-- The `n+1`st term of the upper central series `H i` has underlying set equal to the `x` such that `⁅x,G⁆ ⊆ H n`-/ lemma mem_upper_central_series_succ_iff (n : ℕ) (x : G) : x ∈ upper_central_series G (n + 1) ↔ ∀ y : G, x * y * x⁻¹ * y⁻¹ ∈ upper_central_series G n := iff.rfl -- is_nilpotent is already defined in the root namespace (for elements of rings). /-- A group `G` is nilpotent if its upper central series is eventually `G`. -/ class group.is_nilpotent (G : Type*) [group G] : Prop := (nilpotent [] : ∃ n : ℕ, upper_central_series G n = ⊤) open group section classical open_locale classical /-- The nilpotency class of a nilpotent group is the small natural `n` such that the `n`'th term of the upper central series is `G`. -/ noncomputable def group.nilpotency_class (G : Type*) [group G] [is_nilpotent G] : ℕ := nat.find (is_nilpotent.nilpotent G) end classical variable {G} /-- A sequence of subgroups of `G` is an ascending central series if `H 0` is trivial and `⁅H (n + 1), G⁆ ⊆ H n` for all `n`. Note that we do not require that `H n = G` for some `n`. -/ def is_ascending_central_series (H : ℕ → subgroup G) : Prop := H 0 = ⊥ ∧ ∀ (x : G) (n : ℕ), x ∈ H (n + 1) → ∀ g, x * g * x⁻¹ * g⁻¹ ∈ H n /-- A sequence of subgroups of `G` is a descending central series if `H 0` is `G` and `⁅H n, G⁆ ⊆ H (n + 1)` for all `n`. Note that we do not requre that `H n = {1}` for some `n`. -/ def is_descending_central_series (H : ℕ → subgroup G) := H 0 = ⊤ ∧ ∀ (x : G) (n : ℕ), x ∈ H n → ∀ g, x * g * x⁻¹ * g⁻¹ ∈ H (n + 1) /-- Any ascending central series for a group is bounded above by the upper central series. -/ lemma ascending_central_series_le_upper (H : ℕ → subgroup G) (hH : is_ascending_central_series H) : ∀ n : ℕ, H n ≤ upper_central_series G n | 0 := hH.1.symm ▸ le_refl ⊥ | (n + 1) := begin specialize ascending_central_series_le_upper n, intros x hx, have := hH.2 x n hx, rw mem_upper_central_series_succ_iff, intro y, apply ascending_central_series_le_upper, apply this, end variable (G) /-- The upper central series of a group is an ascending central series. -/ lemma upper_central_series_is_ascending_central_series : is_ascending_central_series (upper_central_series G) := ⟨rfl, λ x n h, h⟩ lemma upper_central_series_mono : monotone (upper_central_series G) := begin refine monotone_nat_of_le_succ _, intros n x hx y, rw [mul_assoc, mul_assoc, ← mul_assoc y x⁻¹ y⁻¹], exact mul_mem (upper_central_series G n) hx (normal.conj_mem (upper_central_series.subgroup.normal G n) x⁻¹ (inv_mem _ hx) y), end /-- A group `G` is nilpotent iff there exists an ascending central series which reaches `G` in finitely many steps. -/ theorem nilpotent_iff_finite_ascending_central_series : is_nilpotent G ↔ ∃ H : ℕ → subgroup G, is_ascending_central_series H ∧ ∃ n : ℕ, H n = ⊤ := begin split, { intro h, use upper_central_series G, refine ⟨upper_central_series_is_ascending_central_series G, h.1⟩ }, { rintro ⟨H, hH, n, hn⟩, use n, have := ascending_central_series_le_upper H hH n, rw hn at this, exact eq_top_iff.mpr this } end /-- A group `G` is nilpotent iff there exists a descending central series which reaches the trivial group in a finite time. -/ theorem nilpotent_iff_finite_descending_central_series : is_nilpotent G ↔ ∃ H : ℕ → subgroup G, is_descending_central_series H ∧ ∃ n : ℕ, H n = ⊥ := begin rw nilpotent_iff_finite_ascending_central_series, split, { rintro ⟨H, ⟨h0, hH⟩, n, hn⟩, use (λ m, H (n - m)), split, { refine ⟨hn, λ x m hx g, _⟩, dsimp at hx, by_cases hm : n ≤ m, { have hnm : n - m = 0 := nat.sub_eq_zero_of_le hm, rw [hnm, h0, subgroup.mem_bot] at hx, subst hx, convert subgroup.one_mem _, group }, { push_neg at hm, apply hH, convert hx, rw nat.sub_succ, exact nat.succ_pred_eq_of_pos (nat.sub_pos_of_lt hm) } }, { use n, rwa nat.sub_self } }, { rintro ⟨H, ⟨h0, hH⟩, n, hn⟩, use (λ m, H (n - m)), split, { refine ⟨hn, λ x m hx g, _⟩, dsimp only at hx, by_cases hm : n ≤ m, { have hnm : n - m = 0 := nat.sub_eq_zero_of_le hm, dsimp only, rw [hnm, h0], exact mem_top _ }, { push_neg at hm, dsimp only, convert hH x _ hx g, rw nat.sub_succ, exact (nat.succ_pred_eq_of_pos (nat.sub_pos_of_lt hm)).symm } }, { use n, rwa nat.sub_self } }, end /-- The lower central series of a group `G` is a sequence `H n` of subgroups of `G`, defined by `H 0` is all of `G` and for `n≥1`, `H (n + 1) = ⁅H n, G⁆` -/ def lower_central_series (G : Type*) [group G] : ℕ → subgroup G | 0 := ⊤ | (n+1) := ⁅lower_central_series n, ⊤⁆ variable {G} @[simp] lemma lower_central_series_zero : lower_central_series G 0 = ⊤ := rfl lemma mem_lower_central_series_succ_iff (n : ℕ) (q : G) : q ∈ lower_central_series G (n + 1) ↔ q ∈ closure {x | ∃ (p ∈ lower_central_series G n) (q ∈ (⊤ : subgroup G)), p * q * p⁻¹ * q⁻¹ = x} := iff.rfl lemma lower_central_series_succ (n : ℕ) : lower_central_series G (n + 1) = closure {x | ∃ (p ∈ lower_central_series G n) (q ∈ (⊤ : subgroup G)), p * q * p⁻¹ * q⁻¹ = x} := rfl instance (n : ℕ) : normal (lower_central_series G n) := begin induction n with d hd, { simp [subgroup.top_normal] }, { haveI := hd, exact general_commutator_normal (lower_central_series G d) ⊤ }, end lemma lower_central_series_antimono {m n : ℕ} (h : n ≤ m) : lower_central_series G m ≤ lower_central_series G n := begin refine @monotone_nat_of_le_succ (order_dual (subgroup G)) _ _ _ _ _ h, intros n x hx, simp only [mem_lower_central_series_succ_iff, exists_prop, mem_top, exists_true_left, true_and] at hx, refine closure_induction hx _ (subgroup.one_mem _) (@subgroup.mul_mem _ _ _) (@subgroup.inv_mem _ _ _), rintros y ⟨z, hz, a, ha⟩, rw [← ha, mul_assoc, mul_assoc, ← mul_assoc a z⁻¹ a⁻¹], exact mul_mem (lower_central_series G n) hz (normal.conj_mem (lower_central_series.subgroup.normal n) z⁻¹ (inv_mem _ hz) a), end /-- The lower central series of a group is a descending central series. -/ theorem lower_central_series_is_descending_central_series : is_descending_central_series (lower_central_series G) := begin split, refl, intros x n hxn g, exact general_commutator_containment _ _ hxn (subgroup.mem_top g), end /-- Any descending central series for a group is bounded below by the lower central series. -/ lemma descending_central_series_ge_lower (H : ℕ → subgroup G) (hH : is_descending_central_series H) : ∀ n : ℕ, lower_central_series G n ≤ H n | 0 := hH.1.symm ▸ le_refl ⊤ | (n + 1) := begin specialize descending_central_series_ge_lower n, apply (general_commutator_le _ _ _).2, intros x hx q _, exact hH.2 x n (descending_central_series_ge_lower hx) q, end /-- A group is nilpotent if and only if its lower central series eventually reaches the trivial subgroup. -/ theorem nilpotent_iff_lower_central_series : is_nilpotent G ↔ ∃ n, lower_central_series G n = ⊥ := begin rw nilpotent_iff_finite_descending_central_series, split, { rintro ⟨H, ⟨h0, hs⟩, n, hn⟩, use n, have := descending_central_series_ge_lower H ⟨h0, hs⟩ n, rw hn at this, exact eq_bot_iff.mpr this }, { intro h, use [lower_central_series G, lower_central_series_is_descending_central_series, h] }, end lemma lower_central_series_map_subtype_le (H : subgroup G) (n : ℕ) : (lower_central_series H n).map H.subtype ≤ lower_central_series G n := begin induction n with d hd, { simp }, { rw [lower_central_series_succ, lower_central_series_succ, monoid_hom.map_closure], apply subgroup.closure_mono, rintros x1 ⟨x2, ⟨x3, hx3, x4, hx4, rfl⟩, rfl⟩, exact ⟨x3, (hd (mem_map.mpr ⟨x3, hx3, rfl⟩)), x4, by simp⟩ } end instance subgroup.is_nilpotent (H : subgroup G) [hG : is_nilpotent G] : is_nilpotent H := begin rw nilpotent_iff_lower_central_series at *, rcases hG with ⟨n, hG⟩, use n, have := lower_central_series_map_subtype_le H n, simp only [hG, set_like.le_def, mem_map, forall_apply_eq_imp_iff₂, exists_imp_distrib] at this, exact eq_bot_iff.mpr (λ x hx, subtype.ext (this x hx)), end @[priority 100] instance is_nilpotent_of_subsingleton [subsingleton G] : is_nilpotent G := nilpotent_iff_lower_central_series.2 ⟨0, subsingleton.elim ⊤ ⊥⟩ lemma upper_central_series.map {H : Type*} [group H] {f : G →* H} (h : function.surjective f) (n : ℕ) : subgroup.map f (upper_central_series G n) ≤ upper_central_series H n := begin induction n with d hd, { simp }, { rintros _ ⟨x, hx : x ∈ upper_central_series G d.succ, rfl⟩ y', rcases (h y') with ⟨y, rfl⟩, simpa using hd (mem_map_of_mem f (hx y)) } end lemma lower_central_series.map {H : Type*} [group H] (f : G →* H) (n : ℕ) : subgroup.map f (lower_central_series G n) ≤ lower_central_series H n := begin induction n with d hd, { simp [nat.nat_zero_eq_zero] }, { rintros a ⟨x, hx : x ∈ lower_central_series G d.succ, rfl⟩, refine closure_induction hx _ (by simp [f.map_one, subgroup.one_mem _]) (λ y z hy hz, by simp [monoid_hom.map_mul, subgroup.mul_mem _ hy hz]) (λ y hy, by simp [f.map_inv, subgroup.inv_mem _ hy]), rintros a ⟨y, hy, z, ⟨-, rfl⟩⟩, apply mem_closure.mpr, exact λ K hK, hK ⟨f y, hd (mem_map_of_mem f hy), by simp⟩ } end
c5b188c44859c1daec2f58ee1604b8c49836a947
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/flat_parser2.lean
44708caf52b2dccf0c979af418dff4f03e7cd3fe
[ "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
17,143
lean
import init.Lean.Message init.Lean.Parser.Syntax init.Lean.Parser.Trie init.Lean.Parser.basic import init.Lean.Parser.token namespace Lean namespace flatParser open String open Parser (Syntax Syntax.missing Syntax.atom Syntax.ident Syntax.rawNode number stringLit) open Parser (Trie TokenMap) def maxPrec : Nat := 1024 abbrev pos := String.utf8Pos /-- A precomputed cache for quickly mapping Char offsets to positions. -/ structure FileMap := (offsets : Array Nat) (lines : Array Nat) namespace FileMap private def fromStringAux (s : String) : Nat → Nat → Nat → pos → Array Nat → Array Nat → FileMap | 0 offset line i offsets lines := ⟨offsets.push offset, lines.push line⟩ | (k+1) offset line i offsets lines := if s.utf8AtEnd i then ⟨offsets.push offset, lines.push line⟩ else let c := s.utf8Get i in let i := s.utf8Next i in let offset := offset + 1 in if c = '\n' then fromStringAux k offset (line+1) i (offsets.push offset) (lines.push (line+1)) else fromStringAux k offset line i offsets lines def fromString (s : String) : FileMap := fromStringAux s s.length 0 1 0 (Array.nil.push 0) (Array.nil.push 1) /- Remark: `offset is in [(offsets.get b), (offsets.get e)]` and `b < e` -/ private def toPositionAux (offsets : Array Nat) (lines : Array Nat) (offset : Nat) : Nat → Nat → Nat → Position | 0 b e := ⟨offset, 1⟩ -- unreachable | (k+1) b e := let offsetB := offsets.read' b in if e = b + 1 then ⟨offset - offsetB, lines.read' b⟩ else let m := (b + e) / 2 in let offsetM := offsets.read' m in if offset = offsetM then ⟨0, lines.read' m⟩ else if offset > offsetM then toPositionAux k m e else toPositionAux k b m def toPosition : FileMap → Nat → Position | ⟨offsets, lines⟩ offset := toPositionAux offsets lines offset offsets.size 0 (offsets.size-1) end FileMap structure TokenConfig := («prefix» : String) (lbp : Nat := 0) structure FrontendConfig := (filename : String) (input : String) (FileMap : FileMap) /- Remark: if we have a Node in the Trie with `some TokenConfig`, the String induced by the path is equal to the `TokenConfig.prefix`. -/ structure ParserConfig extends FrontendConfig := (tokens : Trie TokenConfig) -- Backtrackable State structure ParserState := (messages : MessageLog) structure TokenCacheEntry := (startPos stopPos : pos) (tk : Syntax) -- Non-backtrackable State structure ParserCache := (tokenCache : Option TokenCacheEntry := none) inductive Result (α : Type) | ok (a : α) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result | error {} (msg : String) (i : pos) (cache : ParserCache) (stx : Syntax) (eps : Bool) : Result inductive Result.IsOk {α : Type} : Result α → Prop | mk (a : α) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result.IsOk (Result.ok a i cache State eps) theorem errorIsNotOk {α : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool} (h : Result.IsOk (@Result.error α msg i cache stx eps)) : False := match h with end @[inline] def unreachableError {α β : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool} (h : Result.IsOk (@Result.error α msg i cache stx eps)) : β := False.elim (errorIsNotOk h) def resultOk := {r : Result Unit // r.IsOk} @[inline] def mkResultOk (i : pos) (cache : ParserCache) (State : ParserState) (eps := tt) : resultOk := ⟨Result.ok () i cache State eps, Result.IsOk.mk _ _ _ _ _⟩ def mkError {α : Type} (r : resultOk) (msg : String) (stx : Syntax := Syntax.missing) (eps := tt) : Result α := match r with | ⟨Result.ok _ i c s _, _⟩ := Result.error msg i c stx eps | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h def parserCoreM (α : Type) := resultOk → Result α abbrev parserCore := parserCoreM Syntax @[inline] def parserCoreM.pure {α : Type} (a : α) : parserCoreM α := λ r, match r with | ⟨Result.ok _ it c s _, h⟩ := Result.ok a it c s tt | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline_if_reduce] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[inline_if_reduce] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def parserCoreM.bind {α β : Type} (x : parserCoreM α) (f : α → parserCoreM β) : parserCoreM β := λ r, match x r with | Result.ok a i c s e₁ := (match f a (mkResultOk i c s) with | Result.ok b i c s e₂ := Result.ok b i c s (strictAnd e₁ e₂) | Result.error msg i c stx e₂ := Result.error msg i c stx (strictAnd e₁ e₂)) | Result.error msg i c stx e := Result.error msg i c stx e instance : Monad parserCoreM := {bind := @parserCoreM.bind, pure := @parserCoreM.pure} instance : Inhabited parserCore := ⟨λ r, mkError r "error"⟩ @[inline] def parserCoreM.error {α : Type} (msg : String) : parserCoreM α := λ r, mkError r msg @[inline] def error {α : Type} {m : Type → Type} [HasMonadLiftT parserCoreM m] (msg : String) : m α := monadLift $ parserCoreM.error msg abbrev BasicParserM : Type → Type := ReaderT ParserConfig parserCoreM abbrev basicParser : Type := BasicParserM Syntax abbrev CommandParserM (ρ : Type) : Type → Type := ReaderT ρ (ReaderT parserCore parserCoreM) abbrev TermParserM : Type → Type := ReaderT (Nat → parserCore) (CommandParserM ParserConfig) abbrev termParser : Type := TermParserM Syntax abbrev trailingTermParser : Type := Syntax → termParser structure CommandParserConfig extends ParserConfig := (leadingTermParsers : TokenMap termParser) (trailingTermParsers : TokenMap trailingTermParser) abbrev commandParser : Type := CommandParserM CommandParserConfig Syntax abbrev commandParserCore : Type := CommandParserM ParserConfig Syntax @[inline] def termParserOfBasicParser {α : Type} (p : BasicParserM α) : TermParserM α := λ _ cfg _, p cfg @[inline] def commandParserOfBasicParser {α : Type} (p : BasicParserM α) : CommandParserM CommandParserConfig α := λ cfg _, p cfg.toParserConfig instance basic2termP : HasMonadLift BasicParserM TermParserM := ⟨@termParserOfBasicParser⟩ instance basic2commandP : HasMonadLift BasicParserM (CommandParserM CommandParserConfig) := ⟨@commandParserOfBasicParser⟩ @[inline] def Term.Parser (rbp := 0) : termParser := λ p _ _, p rbp @[inline] def command.Parser : commandParser := λ _ p, p @[inline] def readCfg : TermParserM ParserConfig := λ _ cfg _, pure cfg def peekToken : BasicParserM Syntax := error "TODO" def currLbp : TermParserM Nat := do tk ← monadLift peekToken, match tk with | Syntax.atom ⟨_, sym⟩ := do cfg ← readCfg, (match cfg.tokens.matchPrefix sym.mkIterator with | some ⟨_, tkCfg⟩ := pure tkCfg.lbp | _ := error "currLbp: unreachable") | Syntax.rawNode {kind := @number, ..} := pure maxPrec | Syntax.rawNode {kind := @stringLit, ..} := pure maxPrec | Syntax.ident _ := pure maxPrec | _ := error "currLbp: unknown token kind" #exit match tk with | Syntax.atom ⟨_, sym⟩ := do cfg ← read, -- some ⟨_, tkCfg⟩ ← pure (cfg.tokens.matchPrefix sym.mkIterator) | error "currLbp: unreachable", pure 0 | Syntax.ident _ := pure maxPrec | Syntax.rawNode {kind := @number, ..} := pure maxPrec | Syntax.rawNode {kind := @stringLit, ..} := pure maxPrec | _ := error "currLbp: unknown token kind" private def trailing (cfg : CommandParserConfig) : trailingTermParser := λ _ p _ _ r, p 0 r -- TODO(Leo) private def leading (cfg : CommandParserConfig) : termParser := λ p _ _ r, p 0 r -- TODO(Leo) def dummy : Nat → parserCore := λ _ r, mkError r "dummy" def pratt (leadingP : termParser) (trailingP : trailingTermParser) (p : termParser) : commandParserCore := p dummy def commandParserOfTermParser (p : termParser) : commandParser := λ cfg rec r, let leadingP : termParser := leading cfg in let trailingP : trailingTermParser := trailing cfg in let cfg : ParserConfig := cfg.toParserConfig in let p : commandParserCore := pratt leadingP trailingP p in p cfg rec r #exit def prattParser (cfg : CommandParserConfig) : termParser := leading @[inline] def toParserCore (termP : Nat → Parser) (cmdP : parserCore) : Nat → parserCore := fix (λ recF rbp cfg r, termP rbp cmdP recF cfg r) @[inline] def Parser.run (x : Parser) (termP : Nat → Parser) (cmdP : parserCore) : parserCore := x cmdP (toParserCore termP cmdP) -- STOPPED HERE #exit def parserCore.run (cmdP : parserCore) (termP : parserCore) : parserCore := def aux (f : Nat → parserCore) : Nat → parserCore structure CommandParserConfig extends recParserConfig := (leadingTermParsers : TokenMap Parser) (trailingTermParsers : TokenMap trailingParser) abbrev CommandParserM (α : Type) : Type := parserCoreM CommandParserConfig α abbrev commandParser := CommandParserM Syntax #exit -- abbrev -- def parserM (α : Type) := recParsers → parserCoreM α abbreviation Parser := parserM Syntax abbreviation trailingParser := Syntax → Parser @[inline] def command.Parser : Parser := λ cfg, cfg.cmdParser cfg @[inline] def Term.Parser (rbp : Nat := 0) : Parser := λ ps, ps.termParser rbp instance : Monad parserM := {pure := @parserM.pure, bind := @parserM.bind} @[inline] protected def orelse {α : Type} (p q : parserM α) : parserM α := λ ps cfg r, match r with | ⟨Result.ok _ i₁ _ s₁ _, _⟩ := (match p ps cfg r with | Result.error msg₁ i₂ c₂ stx₁ tt := q ps cfg (mkResultOk i₁ c₂ s₁) | other := other) | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] protected def failure {α : Type} : parserM α := λ _ _ r, match r with | ⟨Result.ok _ i c s _, h⟩ := Result.error "failure" i c Syntax.missing tt | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h instance : Alternative parserM := { orelse := @flatParser.orelse, failure := @flatParser.failure, ..flatParser.Monad } def setSilentError {α : Type} : Result α → Result α | (Result.error i c msg stx _) := Result.error i c msg stx tt | other := other /-- `try p` behaves like `p`, but it pretends `p` hasn't consumed any input when `p` fails. -/ @[inline] def try {α : Type} (p : parserM α) : parserM α := λ ps cfg r, setSilentError (p ps cfg r) @[inline] def atEnd (cfg : ParserConfig) (i : pos) : Bool := cfg.input.utf8AtEnd i @[inline] def curr (cfg : ParserConfig) (i : pos) : Char := cfg.input.utf8Get i @[inline] def next (cfg : ParserConfig) (i : pos) : pos := cfg.input.utf8Next i @[inline] def inputSize (cfg : ParserConfig) : Nat := cfg.input.length @[inline] def currPos : resultOk → pos | ⟨Result.ok _ i _ _ _, _⟩ := i | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] def currState : resultOk → ParserState | ⟨Result.ok _ _ _ s _, _⟩ := s | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] def satisfy (p : Char → Bool) : parserM Char := λ _ cfg r, match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then mkError r "end of input" else let c := curr cfg i in if p c then Result.ok c (next cfg i) ch st ff else mkError r "unexpected character" | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h def any : parserM Char := satisfy (λ _, tt) @[specialize] def takeUntilAux (p : Char → Bool) (cfg : ParserConfig) : Nat → resultOk → Result Unit | 0 r := r.val | (n+1) r := match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then r.val else let c := curr cfg i in if p c then r.val else takeUntilAux n (mkResultOk (next cfg i) ch st tt) | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[specialize] def takeUntil (p : Char → Bool) : parserM Unit := λ ps cfg r, takeUntilAux p cfg (inputSize cfg) r def takeUntilNewLine : parserM Unit := takeUntil (= '\n') def whitespace : parserM Unit := takeUntil (λ c, !c.isWhitespace) -- setOption Trace.Compiler.boxed True --- setOption pp.implicit True def strAux (cfg : ParserConfig) (str : String) (error : String) : Nat → resultOk → pos → Result Unit | 0 r j := mkError r error | (n+1) r j := if str.utf8AtEnd j then r.val else match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then Result.error error i ch Syntax.missing tt else if curr cfg i = str.utf8Get j then strAux n (mkResultOk (next cfg i) ch st tt) (str.utf8Next j) else Result.error error i ch Syntax.missing tt | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h -- #exit @[inline] def str (s : String) : parserM Unit := λ ps cfg r, strAux cfg s ("expected " ++ repr s) (inputSize cfg) r 0 @[specialize] def manyAux (p : parserM Unit) : Nat → Bool → parserM Unit | 0 fst := pure () | (k+1) fst := λ ps cfg r, let i₀ := currPos r in let s₀ := currState r in match p ps cfg r with | Result.ok a i c s _ := manyAux k ff ps cfg (mkResultOk i c s) | Result.error _ _ c _ _ := Result.ok () i₀ c s₀ fst @[inline] def many (p : parserM Unit) : parserM Unit := λ ps cfg r, manyAux p (inputSize cfg) tt ps cfg r @[inline] def many1 (p : parserM Unit) : parserM Unit := p *> many p def dummyParserCore : parserCore := λ cfg r, mkError r "dummy" def testParser {α : Type} (x : parserM α) (input : String) : String := let r := x { cmdParser := dummyParserCore, termParser := λ _, dummyParserCore } { filename := "test", input := input, FileMap := FileMap.fromString input, tokens := Lean.Parser.Trie.mk } (mkResultOk 0 {} {messages := MessageLog.Empty}) in match r with | Result.ok _ i _ _ _ := "Ok at " ++ toString i | Result.error msg i _ _ _ := "Error at " ++ toString i ++ ": " ++ msg /- mutual def recCmd, recTerm (parseCmd : Parser) (parseTerm : Nat → Parser) (parseLvl : Nat → parserCore) with recCmd : Nat → parserCore | 0 cfg r := mkError r "Parser: no progress" | (n+1) cfg r := parseCmd ⟨recCmd n, parseLvl, recTerm n⟩ cfg r with recTerm : Nat → Nat → parserCore | 0 rbp cfg r := mkError r "Parser: no progress" | (n+1) rbp cfg r := parseTerm rbp ⟨recCmd n, parseLvl, recTerm n⟩ cfg r -/ /- def runParser (x : Parser) (parseCmd : Parser) (parseLvl : Nat → Parser) (parseTerm : Nat → Parser) (input : Iterator) (cfg : ParserConfig) : Result Syntax := let it := input in let n := it.remaining in let r := mkResultOk it {} {messages := MessageLog.Empty} in let pl := recLvl (parseLvl) n in let ps : recParsers := { cmdParser := recCmd parseCmd parseTerm pl n, lvlParser := pl, termParser := recTerm parseCmd parseTerm pl n } in x ps cfg r -/ structure parsingTables := (leadingTermParsers : TokenMap Parser) (trailingTermParsers : TokenMap trailingParser) abbreviation CommandParserM (α : Type) := parsingTables → parserM α end flatParser end Lean def mkBigString : Nat → String → String | 0 s := s | (n+1) s := mkBigString n (s ++ "-- new comment\n") section open Lean.flatParser def flatP : parserM Unit := many1 (str "--" *> takeUntil (= '\n') *> any *> pure ()) end section open Lean.Parser open Lean.Parser.MonadParsec @[reducible] def Parser (α : Type) : Type := ReaderT Lean.flatParser.recParsers (ReaderT Lean.flatParser.ParserConfig (ParsecT Syntax (StateT ParserCache id))) α def testParsec (p : Parser Unit) (input : String) : String := let ps : Lean.flatParser.recParsers := { cmdParser := Lean.flatParser.dummyParserCore, termParser := λ _, Lean.flatParser.dummyParserCore } in let cfg : Lean.flatParser.ParserConfig := { filename := "test", input := input, FileMap := Lean.flatParser.FileMap.fromString input, tokens := Lean.Parser.Trie.mk } in let r := p ps cfg input.mkIterator {} in match r with | (Parsec.Result.ok _ it _, _) := "OK at " ++ toString it.offset | (Parsec.Result.error msg _, _) := "Error " ++ msg.toString def parsecP : Parser Unit := many1' (str "--" *> takeUntil (λ c, c = '\n') *> any *> pure ()) end @[noinline] def testFlatP (s : String) : IO Unit := IO.println (Lean.flatParser.testParser flatP s) @[noinline] def testParsecP (s : String) : IO Unit := IO.println (testParsec parsecP s) def prof {α : Type} (msg : String) (p : IO α) : IO α := let msg₁ := "Time for '" ++ msg ++ "':" in let msg₂ := "Memory usage for '" ++ msg ++ "':" in allocprof msg₂ (timeit msg₁ p) def main (xs : List String) : IO UInt32 := let s₁ := mkBigString xs.head.toNat "" in let s₂ := s₁ ++ "bad" ++ mkBigString 20 "" in prof "flat Parser 1" (testFlatP s₁) *> prof "flat Parser 2" (testFlatP s₂) *> -- prof "Parsec 1" (testParsecP s₁) *> -- prof "Parsec 2" (testParsecP s₂) *> pure 0
39835314e7ddfc85b93f8a5c47356cab1c7442b6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/matrix.lean
a4a043dd3870a657b74e7b350c2649b3fd0683f3
[ "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
20,619
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Eric Wieser -/ import analysis.normed_space.basic import analysis.normed_space.pi_Lp import analysis.inner_product_space.pi_L2 /-! # Matrices as a normed space In this file we provide the following non-instances for norms on matrices: * The elementwise norm: * `matrix.seminormed_add_comm_group` * `matrix.normed_add_comm_group` * `matrix.normed_space` * The Frobenius norm: * `matrix.frobenius_seminormed_add_comm_group` * `matrix.frobenius_normed_add_comm_group` * `matrix.frobenius_normed_space` * `matrix.frobenius_normed_ring` * `matrix.frobenius_normed_algebra` * The $L^\infty$ operator norm: * `matrix.linfty_op_seminormed_add_comm_group` * `matrix.linfty_op_normed_add_comm_group` * `matrix.linfty_op_normed_space` * `matrix.linfty_op_non_unital_semi_normed_ring` * `matrix.linfty_op_semi_normed_ring` * `matrix.linfty_op_non_unital_normed_ring` * `matrix.linfty_op_normed_ring` * `matrix.linfty_op_normed_algebra` These are not declared as instances because there are several natural choices for defining the norm of a matrix. -/ noncomputable theory open_locale big_operators nnreal matrix namespace matrix variables {R l m n α β : Type*} [fintype l] [fintype m] [fintype n] /-! ### The elementwise supremum norm -/ section linf_linf section seminormed_add_comm_group variables [seminormed_add_comm_group α] [seminormed_add_comm_group β] /-- Seminormed group instance (using sup norm of sup norm) for matrices over a seminormed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ protected def seminormed_add_comm_group : seminormed_add_comm_group (matrix m n α) := pi.seminormed_add_comm_group local attribute [instance] matrix.seminormed_add_comm_group lemma norm_le_iff {r : ℝ} (hr : 0 ≤ r) {A : matrix m n α} : ∥A∥ ≤ r ↔ ∀ i j, ∥A i j∥ ≤ r := by simp [pi_norm_le_iff hr] lemma nnnorm_le_iff {r : ℝ≥0} {A : matrix m n α} : ∥A∥₊ ≤ r ↔ ∀ i j, ∥A i j∥₊ ≤ r := by simp [pi_nnnorm_le_iff] lemma norm_lt_iff {r : ℝ} (hr : 0 < r) {A : matrix m n α} : ∥A∥ < r ↔ ∀ i j, ∥A i j∥ < r := by simp [pi_norm_lt_iff hr] lemma nnnorm_lt_iff {r : ℝ≥0} (hr : 0 < r) {A : matrix m n α} : ∥A∥₊ < r ↔ ∀ i j, ∥A i j∥₊ < r := by simp [pi_nnnorm_lt_iff hr] lemma norm_entry_le_entrywise_sup_norm (A : matrix m n α) {i : m} {j : n} : ∥A i j∥ ≤ ∥A∥ := (norm_le_pi_norm (A i) j).trans (norm_le_pi_norm A i) lemma nnnorm_entry_le_entrywise_sup_nnnorm (A : matrix m n α) {i : m} {j : n} : ∥A i j∥₊ ≤ ∥A∥₊ := (nnnorm_le_pi_nnnorm (A i) j).trans (nnnorm_le_pi_nnnorm A i) @[simp] lemma nnnorm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ∥f a∥₊ = ∥a∥₊) : ∥A.map f∥₊ = ∥A∥₊ := by simp_rw [pi.nnnorm_def, matrix.map_apply, hf] @[simp] lemma norm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ∥f a∥ = ∥a∥) : ∥A.map f∥ = ∥A∥ := (congr_arg (coe : ℝ≥0 → ℝ) $ nnnorm_map_eq A f $ λ a, subtype.ext $ hf a : _) @[simp] lemma nnnorm_transpose (A : matrix m n α) : ∥Aᵀ∥₊ = ∥A∥₊ := by { simp_rw [pi.nnnorm_def], exact finset.sup_comm _ _ _ } @[simp] lemma norm_transpose (A : matrix m n α) : ∥Aᵀ∥ = ∥A∥ := congr_arg coe $ nnnorm_transpose A @[simp] lemma nnnorm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ∥Aᴴ∥₊ = ∥A∥₊ := (nnnorm_map_eq _ _ nnnorm_star).trans A.nnnorm_transpose @[simp] lemma norm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ∥Aᴴ∥ = ∥A∥ := congr_arg coe $ nnnorm_conj_transpose A instance [star_add_monoid α] [normed_star_group α] : normed_star_group (matrix m m α) := ⟨norm_conj_transpose⟩ @[simp] lemma nnnorm_col (v : m → α) : ∥col v∥₊ = ∥v∥₊ := by simp [pi.nnnorm_def] @[simp] lemma norm_col (v : m → α) : ∥col v∥ = ∥v∥ := congr_arg coe $ nnnorm_col v @[simp] lemma nnnorm_row (v : n → α) : ∥row v∥₊ = ∥v∥₊ := by simp [pi.nnnorm_def] @[simp] lemma norm_row (v : n → α) : ∥row v∥ = ∥v∥ := congr_arg coe $ nnnorm_row v @[simp] lemma nnnorm_diagonal [decidable_eq n] (v : n → α) : ∥diagonal v∥₊ = ∥v∥₊ := begin simp_rw pi.nnnorm_def, congr' 1 with i : 1, refine le_antisymm (finset.sup_le $ λ j hj, _) _, { obtain rfl | hij := eq_or_ne i j, { rw diagonal_apply_eq }, { rw [diagonal_apply_ne _ hij, nnnorm_zero], exact zero_le _ }, }, { refine eq.trans_le _ (finset.le_sup (finset.mem_univ i)), rw diagonal_apply_eq } end @[simp] lemma norm_diagonal [decidable_eq n] (v : n → α) : ∥diagonal v∥ = ∥v∥ := congr_arg coe $ nnnorm_diagonal v /-- Note this is safe as an instance as it carries no data. -/ instance [nonempty n] [decidable_eq n] [has_one α] [norm_one_class α] : norm_one_class (matrix n n α) := ⟨(norm_diagonal _).trans $ norm_one⟩ end seminormed_add_comm_group /-- Normed group instance (using sup norm of sup norm) for matrices over a normed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ protected def normed_add_comm_group [normed_add_comm_group α] : normed_add_comm_group (matrix m n α) := pi.normed_add_comm_group section normed_space local attribute [instance] matrix.seminormed_add_comm_group variables [normed_field R] [seminormed_add_comm_group α] [normed_space R α] /-- Normed space instance (using sup norm of sup norm) for matrices over a normed space. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ protected def normed_space : normed_space R (matrix m n α) := pi.normed_space end normed_space end linf_linf /-! ### The $L_\infty$ operator norm This section defines the matrix norm $\|A\|_\infty = \operatorname{sup}_i (\sum_j \|A_{ij}\|)$. Note that this is equivalent to the operator norm, considering $A$ as a linear map between two $L^\infty$ spaces. -/ section linfty_op /-- Seminormed group instance (using sup norm of L1 norm) for matrices over a seminormed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_seminormed_add_comm_group [seminormed_add_comm_group α] : seminormed_add_comm_group (matrix m n α) := (by apply_instance : seminormed_add_comm_group (m → pi_Lp 1 (λ j : n, α))) /-- Normed group instance (using sup norm of L1 norm) for matrices over a normed ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_add_comm_group [normed_add_comm_group α] : normed_add_comm_group (matrix m n α) := (by apply_instance : normed_add_comm_group (m → pi_Lp 1 (λ j : n, α))) /-- Normed space instance (using sup norm of L1 norm) for matrices over a normed space. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_space [normed_field R] [seminormed_add_comm_group α] [normed_space R α] : normed_space R (matrix m n α) := (by apply_instance : normed_space R (m → pi_Lp 1 (λ j : n, α))) section seminormed_add_comm_group variables [seminormed_add_comm_group α] lemma linfty_op_norm_def (A : matrix m n α) : ∥A∥ = ((finset.univ : finset m).sup (λ i : m, ∑ j : n, ∥A i j∥₊) : ℝ≥0) := by simp [pi.norm_def, pi_Lp.nnnorm_eq_sum ennreal.one_ne_top] lemma linfty_op_nnnorm_def (A : matrix m n α) : ∥A∥₊ = (finset.univ : finset m).sup (λ i : m, ∑ j : n, ∥A i j∥₊) := subtype.ext $ linfty_op_norm_def A @[simp] lemma linfty_op_nnnorm_col (v : m → α) : ∥col v∥₊ = ∥v∥₊ := begin rw [linfty_op_nnnorm_def, pi.nnnorm_def], simp, end @[simp] lemma linfty_op_norm_col (v : m → α) : ∥col v∥ = ∥v∥ := congr_arg coe $ linfty_op_nnnorm_col v @[simp] lemma linfty_op_nnnorm_row (v : n → α) : ∥row v∥₊ = ∑ i, ∥v i∥₊ := by simp [linfty_op_nnnorm_def] @[simp] lemma linfty_op_norm_row (v : n → α) : ∥row v∥ = ∑ i, ∥v i∥ := (congr_arg coe $ linfty_op_nnnorm_row v).trans $ by simp [nnreal.coe_sum] @[simp] lemma linfty_op_nnnorm_diagonal [decidable_eq m] (v : m → α) : ∥diagonal v∥₊ = ∥v∥₊ := begin rw [linfty_op_nnnorm_def, pi.nnnorm_def], congr' 1 with i : 1, refine (finset.sum_eq_single_of_mem _ (finset.mem_univ i) $ λ j hj hij, _).trans _, { rw [diagonal_apply_ne' _ hij, nnnorm_zero] }, { rw [diagonal_apply_eq] }, end @[simp] lemma linfty_op_norm_diagonal [decidable_eq m] (v : m → α) : ∥diagonal v∥ = ∥v∥ := congr_arg coe $ linfty_op_nnnorm_diagonal v end seminormed_add_comm_group section non_unital_semi_normed_ring variables [non_unital_semi_normed_ring α] lemma linfty_op_nnnorm_mul (A : matrix l m α) (B : matrix m n α) : ∥A ⬝ B∥₊ ≤ ∥A∥₊ * ∥B∥₊ := begin simp_rw [linfty_op_nnnorm_def, matrix.mul_apply], calc finset.univ.sup (λ i, ∑ k, ∥∑ j, A i j * B j k∥₊) ≤ finset.univ.sup (λ i, ∑ k j, ∥A i j∥₊ * ∥B j k∥₊) : finset.sup_mono_fun $ λ i hi, finset.sum_le_sum $ λ k hk, nnnorm_sum_le_of_le _ $ λ j hj, nnnorm_mul_le _ _ ... = finset.univ.sup (λ i, ∑ j, (∥A i j∥₊ * ∑ k, ∥B j k∥₊)) : by simp_rw [@finset.sum_comm _ m n, finset.mul_sum] ... ≤ finset.univ.sup (λ i, ∑ j, ∥A i j∥₊ * finset.univ.sup (λ i, ∑ j, ∥B i j∥₊)) : finset.sup_mono_fun $ λ i hi, finset.sum_le_sum $ λ j hj, mul_le_mul_of_nonneg_left (finset.le_sup hj) (zero_le _) ... ≤ finset.univ.sup (λ i, ∑ j, ∥A i j∥₊) * finset.univ.sup (λ i, ∑ j, ∥B i j∥₊) : by simp_rw [←finset.sum_mul, ←nnreal.finset_sup_mul], end lemma linfty_op_norm_mul (A : matrix l m α) (B : matrix m n α) : ∥A ⬝ B∥ ≤ ∥A∥ * ∥B∥ := linfty_op_nnnorm_mul _ _ lemma linfty_op_nnnorm_mul_vec (A : matrix l m α) (v : m → α) : ∥A.mul_vec v∥₊ ≤ ∥A∥₊ * ∥v∥₊ := begin rw [←linfty_op_nnnorm_col (A.mul_vec v), ←linfty_op_nnnorm_col v], exact linfty_op_nnnorm_mul A (col v), end lemma linfty_op_norm_mul_vec (A : matrix l m α) (v : m → α) : ∥matrix.mul_vec A v∥ ≤ ∥A∥ * ∥v∥ := linfty_op_nnnorm_mul_vec _ _ end non_unital_semi_normed_ring /-- Seminormed non-unital ring instance (using sup norm of L1 norm) for matrices over a semi normed non-unital ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_non_unital_semi_normed_ring [non_unital_semi_normed_ring α] : non_unital_semi_normed_ring (matrix n n α) := { norm_mul := linfty_op_norm_mul, .. matrix.linfty_op_seminormed_add_comm_group, .. matrix.non_unital_ring } /-- The `L₁-L∞` norm preserves one on non-empty matrices. Note this is safe as an instance, as it carries no data. -/ instance linfty_op_norm_one_class [semi_normed_ring α] [norm_one_class α] [decidable_eq n] [nonempty n] : norm_one_class (matrix n n α) := { norm_one := (linfty_op_norm_diagonal _).trans norm_one } /-- Seminormed ring instance (using sup norm of L1 norm) for matrices over a semi normed ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_semi_normed_ring [semi_normed_ring α] [decidable_eq n] : semi_normed_ring (matrix n n α) := { .. matrix.linfty_op_non_unital_semi_normed_ring, .. matrix.ring } /-- Normed non-unital ring instance (using sup norm of L1 norm) for matrices over a normed non-unital ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_non_unital_normed_ring [non_unital_normed_ring α] : non_unital_normed_ring (matrix n n α) := { ..matrix.linfty_op_non_unital_semi_normed_ring } /-- Normed ring instance (using sup norm of L1 norm) for matrices over a normed ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_ring [normed_ring α] [decidable_eq n] : normed_ring (matrix n n α) := { ..matrix.linfty_op_semi_normed_ring } /-- Normed algebra instance (using sup norm of L1 norm) for matrices over a normed algebra. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_algebra [normed_field R] [semi_normed_ring α] [normed_algebra R α] [decidable_eq n] : normed_algebra R (matrix n n α) := { ..matrix.linfty_op_normed_space } end linfty_op /-! ### The Frobenius norm This is defined as $\|A\| = \sqrt{\sum_{i,j} \|A_{ij}\|^2}$. When the matrix is over the real or complex numbers, this norm is submultiplicative. -/ section frobenius open_locale matrix big_operators /-- Seminormed group instance (using frobenius norm) for matrices over a seminormed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_seminormed_add_comm_group [seminormed_add_comm_group α] : seminormed_add_comm_group (matrix m n α) := (by apply_instance : seminormed_add_comm_group (pi_Lp 2 (λ i : m, pi_Lp 2 (λ j : n, α)))) /-- Normed group instance (using frobenius norm) for matrices over a normed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_add_comm_group [normed_add_comm_group α] : normed_add_comm_group (matrix m n α) := (by apply_instance : normed_add_comm_group (pi_Lp 2 (λ i : m, pi_Lp 2 (λ j : n, α)))) /-- Normed space instance (using frobenius norm) for matrices over a normed space. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_space [normed_field R] [seminormed_add_comm_group α] [normed_space R α] : normed_space R (matrix m n α) := (by apply_instance : normed_space R (pi_Lp 2 (λ i : m, pi_Lp 2 (λ j : n, α)))) section seminormed_add_comm_group variables [seminormed_add_comm_group α] [seminormed_add_comm_group β] lemma frobenius_nnnorm_def (A : matrix m n α) : ∥A∥₊ = (∑ i j, ∥A i j∥₊ ^ (2 : ℝ)) ^ (1/2 : ℝ) := by simp_rw [pi_Lp.nnnorm_eq_of_L2, nnreal.sq_sqrt, nnreal.sqrt_eq_rpow, nnreal.rpow_two] lemma frobenius_norm_def (A : matrix m n α) : ∥A∥ = (∑ i j, ∥A i j∥ ^ (2 : ℝ)) ^ (1/2 : ℝ) := (congr_arg coe (frobenius_nnnorm_def A)).trans $ by simp [nnreal.coe_sum] @[simp] lemma frobenius_nnnorm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ∥f a∥₊ = ∥a∥₊) : ∥A.map f∥₊ = ∥A∥₊ := by simp_rw [frobenius_nnnorm_def, matrix.map_apply, hf] @[simp] lemma frobenius_norm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ∥f a∥ = ∥a∥) : ∥A.map f∥ = ∥A∥ := (congr_arg (coe : ℝ≥0 → ℝ) $ frobenius_nnnorm_map_eq A f $ λ a, subtype.ext $ hf a : _) @[simp] lemma frobenius_nnnorm_transpose (A : matrix m n α) : ∥Aᵀ∥₊ = ∥A∥₊ := by { rw [frobenius_nnnorm_def, frobenius_nnnorm_def, finset.sum_comm], refl } @[simp] lemma frobenius_norm_transpose (A : matrix m n α) : ∥Aᵀ∥ = ∥A∥ := congr_arg coe $ frobenius_nnnorm_transpose A @[simp] lemma frobenius_nnnorm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ∥Aᴴ∥₊ = ∥A∥₊ := (frobenius_nnnorm_map_eq _ _ nnnorm_star).trans A.frobenius_nnnorm_transpose @[simp] lemma frobenius_norm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ∥Aᴴ∥ = ∥A∥ := congr_arg coe $ frobenius_nnnorm_conj_transpose A instance frobenius_normed_star_group [star_add_monoid α] [normed_star_group α] : normed_star_group (matrix m m α) := ⟨frobenius_norm_conj_transpose⟩ @[simp] lemma frobenius_norm_row (v : m → α) : ∥row v∥ = ∥(pi_Lp.equiv 2 _).symm v∥ := begin rw [frobenius_norm_def, fintype.sum_unique, pi_Lp.norm_eq_of_L2, real.sqrt_eq_rpow], simp only [row_apply, real.rpow_two, pi_Lp.equiv_symm_apply'], end @[simp] lemma frobenius_nnnorm_row (v : m → α) : ∥row v∥₊ = ∥(pi_Lp.equiv 2 _).symm v∥₊ := subtype.ext $ frobenius_norm_row v @[simp] lemma frobenius_norm_col (v : n → α) : ∥col v∥ = ∥(pi_Lp.equiv 2 _).symm v∥ := begin simp_rw [frobenius_norm_def, fintype.sum_unique, pi_Lp.norm_eq_of_L2, real.sqrt_eq_rpow], simp only [col_apply, real.rpow_two, pi_Lp.equiv_symm_apply'] end @[simp] lemma frobenius_nnnorm_col (v : n → α) : ∥col v∥₊ = ∥(pi_Lp.equiv 2 _).symm v∥₊ := subtype.ext $ frobenius_norm_col v @[simp] lemma frobenius_nnnorm_diagonal [decidable_eq n] (v : n → α) : ∥diagonal v∥₊ = ∥(pi_Lp.equiv 2 _).symm v∥₊ := begin simp_rw [frobenius_nnnorm_def, ←finset.sum_product', finset.univ_product_univ, pi_Lp.nnnorm_eq_of_L2], let s := (finset.univ : finset n).map ⟨λ i : n, (i, i), λ i j h, congr_arg prod.fst h⟩, rw ←finset.sum_subset (finset.subset_univ s) (λ i hi his, _), { rw [finset.sum_map, nnreal.sqrt_eq_rpow], dsimp, simp_rw [diagonal_apply_eq, nnreal.rpow_two] }, { suffices : i.1 ≠ i.2, { rw [diagonal_apply_ne _ this, nnnorm_zero, nnreal.zero_rpow two_ne_zero], }, intro h, exact finset.mem_map.not.mp his ⟨i.1, finset.mem_univ _, prod.ext rfl h⟩ } end @[simp] lemma frobenius_norm_diagonal [decidable_eq n] (v : n → α) : ∥diagonal v∥ = ∥(pi_Lp.equiv 2 _).symm v∥ := (congr_arg coe $ frobenius_nnnorm_diagonal v : _).trans rfl end seminormed_add_comm_group lemma frobenius_nnnorm_one [decidable_eq n] [seminormed_add_comm_group α] [has_one α] : ∥(1 : matrix n n α)∥₊ = nnreal.sqrt (fintype.card n) * ∥(1 : α)∥₊:= begin refine (frobenius_nnnorm_diagonal _).trans _, simp_rw [pi_Lp.nnnorm_equiv_symm_const ennreal.two_ne_top, nnreal.sqrt_eq_rpow], simp only [ennreal.to_real_div, ennreal.one_to_real, ennreal.to_real_bit0], end section is_R_or_C variables [is_R_or_C α] lemma frobenius_nnnorm_mul (A : matrix l m α) (B : matrix m n α) : ∥A ⬝ B∥₊ ≤ ∥A∥₊ * ∥B∥₊ := begin simp_rw [frobenius_nnnorm_def, matrix.mul_apply], rw [←nnreal.mul_rpow, @finset.sum_comm _ n m, finset.sum_mul_sum, finset.sum_product], refine nnreal.rpow_le_rpow _ one_half_pos.le, refine finset.sum_le_sum (λ i hi, finset.sum_le_sum $ λ j hj, _), rw [← nnreal.rpow_le_rpow_iff one_half_pos, ← nnreal.rpow_mul, mul_div_cancel' (1 : ℝ) two_ne_zero, nnreal.rpow_one, nnreal.mul_rpow], dsimp only, have := @nnnorm_inner_le_nnnorm α _ _ _ ((pi_Lp.equiv 2 (λ i, α)).symm (λ j, star (A i j))) ((pi_Lp.equiv 2 (λ i, α)).symm (λ k, B k j)), simpa only [pi_Lp.equiv_symm_apply, pi_Lp.inner_apply, is_R_or_C.inner_apply, star_ring_end_apply, pi.nnnorm_def, pi_Lp.nnnorm_eq_of_L2, star_star, nnnorm_star, nnreal.sqrt_eq_rpow, nnreal.rpow_two] using this, end lemma frobenius_norm_mul (A : matrix l m α) (B : matrix m n α) : ∥A ⬝ B∥ ≤ ∥A∥ * ∥B∥ := frobenius_nnnorm_mul A B /-- Normed ring instance (using frobenius norm) for matrices over `ℝ` or `ℂ`. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_ring [decidable_eq m] : normed_ring (matrix m m α) := { norm := has_norm.norm, norm_mul := frobenius_norm_mul, ..matrix.frobenius_seminormed_add_comm_group } /-- Normed algebra instance (using frobenius norm) for matrices over `ℝ` or `ℂ`. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_algebra [decidable_eq m] [normed_field R] [normed_algebra R α] : normed_algebra R (matrix m m α) := { ..matrix.frobenius_normed_space } end is_R_or_C end frobenius end matrix
12e637a6152f6482fbb36e940045e816371d2fbe
ac1c2a2f522b0fdf854095ba00f882ca849669e7
/library/init/meta/coinductive_predicates.lean
5d8c8c40982b811e520af914a654a8897c4412ad
[ "Apache-2.0" ]
permissive
abliss/lean
b8b336abc8d50dbb0726dcff9dd16793c23bfbe1
fb24cc99573c153f97a1951ee94bbbdda300b6be
refs/heads/master
1,611,536,584,520
1,497,811,981,000
1,497,811,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,618
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 (CMU) -/ prelude import init.meta.expr init.meta.tactic init.meta.constructor_tactic init.meta.attribute import init.meta.interactive namespace name def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace expr open expr meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none meta def local_binder_info : expr → binder_info | (local_const x n bi t) := bi | e := binder_info.default meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] end expr namespace tactic open level expr tactic meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ const n $ ls.map param meta def is_assigned (m : expr): tactic bool := ((get_assignment m >> return ff) <|> return tt) meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) meta def elim_gen_prod : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h, h'], _)] ← induction e [], elim_gen_prod n h' (hs ++ [h]) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h], _), ([h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.taken (n+1)).reverse ++ gs.dropn (n+1), return $ hs.reverse ++ [h'] end tactic section universe u def monotonicity := { user_attribute . name := `monotonicity, descr := "Monotonicity rules for predicates" } run_cmd register_attribute `monotonicity lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := take h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := take h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := take _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, applyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← return p, (expr.pi qn qbi qd qb) ← return q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, apply $ (const `monotonicity.pi [u] : expr) pd p' q') <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, apply $ (const `monotonicity.imp []: expr) pd p' qd q'))) <|> first (hs.map $ λh, apply_core h { md := transparency.none } >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c { md := transparency.none }, skip), all_goals mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ private meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← mk_local_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← mk_local_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binder_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', apply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) { all := tt }, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, is_assigned m), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, constructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h) ← elim_gen_prod pds.length h [], (hs, h) ← elim_gen_prod pds.length h [], apply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do apply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, apply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), apply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do apply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ apply $ pd.destruct.app_of_list ps)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', apply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, apply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, apply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [], if n_eqs > 0 then do (eqs, eq') ← elim_gen_prod (n_eqs - 1) h [], (eqs ++ [eq']).mmap' subst else skip, apply ((const r.func_nm u_params).app_of_list $ ps ++ fs), repeat assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, apply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules (i.e. only a since C -/ meta def coinduction (rule : expr) : tactic unit := focus1 $ do ctxts' ← intros, -- TODO: why do we need to fix the type here? ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binder_info <$> infer_type v), mvars ← apply_core rule { approx := ff, all := tt }, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v ≠ g), tgt ← target, (is, ty) ← mk_local_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars), rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, repeat constructor), -- clean up remaining coinduction steps all_goals (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [], (match eqs with | [] := clear h | (e::eqs) := do (hs, h) ← elim_gen_prod eqs.length h [], (h::(hs.reverse)).mmap' subst end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule, skip end interactive end tactic
3d0076719f00fbfaa08b7e1e94b66b3c32afd39f
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/geometry/algebra/lie_group.lean
279823f040536898e39501acd9b84d9bf1703be3
[ "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
11,347
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import geometry.manifold.times_cont_mdiff /-! # Lie groups A Lie group is a group that is also a smooth manifold, in which the group operations of multiplication and inversion are smooth maps. Smoothness of the group multiplication means that multiplication is a smooth mapping of the product manifold `G` × `G` into `G`. Note that, since a manifold here is not second-countable and Hausdorff a Lie group here is not guaranteed to be second-countable (even though it can be proved it is Hausdorff). Note also that Lie groups here are not necessarily finite dimensional. ## Main definitions and statements * `lie_add_group I G` : a Lie additive group where `G` is a manifold on the model with corners `I`. * `lie_group I G` : a Lie multiplicative group where `G` is a manifold on the model with corners `I`. * `lie_add_group_morphism I I' G G'` : morphism of addittive Lie groups * `lie_group_morphism I I' G G'` : morphism of Lie groups * `lie_add_group_core I G` : allows to define a Lie additive group without first proving it is a topological additive group. * `lie_group_core I G` : allows to define a Lie group without first proving it is a topological group. * `reals_lie_group` : real numbers are a Lie group ## Implementation notes A priori, a Lie group here is a manifold with corners. The definition of Lie group cannot require `I : model_with_corners 𝕜 E E` with the same space as the model space and as the model vector space, as one might hope, beause in the product situation, the model space is `model_prod E E'` and the model vector space is `E × E'`, which are not the same, so the definition does not apply. Hence the definition should be more general, allowing `I : model_with_corners 𝕜 E H`. -/ noncomputable theory section lie_group /-- A Lie (additive) group is a group and a smooth manifold at the same time in which the addition and negation operations are smooth. -/ class lie_add_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [add_group G] [topological_space G] [topological_add_group G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2)) (smooth_neg : smooth I I (λ a:G, -a)) /-- A Lie group is a group and a smooth manifold at the same time in which the multiplication and inverse operations are smooth. -/ @[to_additive] class lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [group G] [topological_space G] [topological_group G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2)) (smooth_inv : smooth I I (λ a:G, a⁻¹)) section lie_group variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space H G] [group G] [topological_group G] [lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] [smooth_manifold_with_corners I' M] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M' : Type*} [topological_space M'] [charted_space H'' M'] [smooth_manifold_with_corners I'' M'] @[to_additive] lemma smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2) := lie_group.smooth_mul @[to_additive] lemma smooth.mul {f : M → G} {g : M → G} (hf : smooth I' I f) (hg : smooth I' I g) : smooth I' I (f * g) := smooth_mul.comp (hf.prod_mk hg) localized "notation `L_add` := left_add" in lie_group localized "notation `R_add` := right_add" in lie_group localized "notation `L` := left_mul" in lie_group localized "notation `R` := right_mul" in lie_group @[to_additive] lemma smooth_left_mul {a : G} : smooth I I (left_mul a) := smooth_mul.comp (smooth_const.prod_mk smooth_id) @[to_additive] lemma smooth_right_mul {a : G} : smooth I I (right_mul a) := smooth_mul.comp (smooth_id.prod_mk smooth_const) @[to_additive] lemma smooth_on.mul {f : M → G} {g : M → G} {s : set M} (hf : smooth_on I' I f s) (hg : smooth_on I' I g s) : smooth_on I' I (f * g) s := (smooth_mul.comp_smooth_on (hf.prod_mk hg) : _) lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n) | 0 := by { simp only [pow_zero], exact smooth_const } | (k+1) := show smooth I I (λ (a : G), a * a ^ k), from smooth_id.mul (smooth_pow _) @[to_additive] lemma smooth_inv : smooth I I (λ x : G, x⁻¹) := lie_group.smooth_inv @[to_additive] lemma smooth.inv {f : M → G} (hf : smooth I' I f) : smooth I' I (λx, (f x)⁻¹) := smooth_inv.comp hf @[to_additive] lemma smooth_on.inv {f : M → G} {s : set M} (hf : smooth_on I' I f s) : smooth_on I' I (λx, (f x)⁻¹) s := smooth_inv.comp_smooth_on hf end lie_group section prod_lie_group /- Instance of product group -/ @[to_additive] instance {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [topological_space G] [charted_space H G] [group G] [topological_group G] [h : lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {G' : Type*} [topological_space G'] [charted_space H' G'] [group G'] [topological_group G'] [h' : lie_group I' G'] : lie_group (I.prod I') (G×G') := { smooth_mul := ((smooth_fst.comp smooth_fst).smooth.mul (smooth_fst.comp smooth_snd)).prod_mk ((smooth_snd.comp smooth_fst).smooth.mul (smooth_snd.comp smooth_snd)), smooth_inv := smooth_fst.inv.prod_mk smooth_snd.inv, } end prod_lie_group section lie_add_group_morphism variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] /-- Morphism of additive Lie groups. -/ structure lie_add_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [add_group G] [topological_add_group G] [lie_add_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [add_group G'] [topological_add_group G'] [lie_add_group I' G'] extends add_monoid_hom G G' := (smooth_to_fun : smooth I I' to_fun) /-- Morphism of Lie groups. -/ @[to_additive] structure lie_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [topological_group G] [lie_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [group G'] [topological_group G'] [lie_group I' G'] extends monoid_hom G G' := (smooth_to_fun : smooth I I' to_fun) variables {I : model_with_corners 𝕜 E E} {I' : model_with_corners 𝕜 E' E'} {G : Type*} [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [topological_group G] [lie_group I G] {G' : Type*} [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [group G'] [topological_group G'] [lie_group I' G'] @[to_additive] instance : has_one (lie_group_morphism I I' G G') := ⟨⟨1, smooth_const⟩⟩ @[to_additive] instance : inhabited (lie_group_morphism I I' G G') := ⟨1⟩ @[to_additive] instance : has_coe_to_fun (lie_group_morphism I I' G G') := ⟨_, λ a, a.to_fun⟩ end lie_add_group_morphism end lie_group section lie_group_core /-- Sometimes one might want to define a Lie additive group `G` without having proved previously that `G` is a topological additive group. In such case it is possible to use `lie_add_group_core` that does not require such instance, and then get a Lie group by invoking `to_lie_add_group`. -/ structure lie_add_group_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [add_group G] [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] : Prop := (smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2)) (smooth_neg : smooth I I (λ a:G, -a)) /-- Sometimes one might want to define a Lie group `G` without having proved previously that `G` is a topological group. In such case it is possible to use `lie_group_core` that does not require such instance, and then get a Lie group by invoking `to_lie_group` defined below. -/ @[to_additive] structure lie_group_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [group G] [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] : Prop := (smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2)) (smooth_inv : smooth I I (λ a:G, a⁻¹)) variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] namespace lie_group_core variables (c : lie_group_core I G) @[to_additive] protected lemma to_topological_group : topological_group G := { continuous_mul := c.smooth_mul.continuous, continuous_inv := c.smooth_inv.continuous, } @[to_additive] protected lemma to_lie_group : @lie_group 𝕜 _ _ _ E _ _ I G _ _ c.to_topological_group _ := { smooth_mul := c.smooth_mul, smooth_inv := c.smooth_inv, } end lie_group_core end lie_group_core /-! ### Real numbers are a Lie group -/ section real_numbers_lie_group instance normed_group_lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] : lie_add_group (model_with_corners_self 𝕜 E) E := { smooth_add := begin rw smooth_iff, refine ⟨continuous_add, λ x y, _⟩, simp only [prod.mk.eta] with mfld_simps, rw times_cont_diff_on_univ, exact times_cont_diff_add, end, smooth_neg := begin rw smooth_iff, refine ⟨continuous_neg, λ x y, _⟩, simp only [prod.mk.eta] with mfld_simps, rw times_cont_diff_on_univ, exact times_cont_diff_neg, end } instance reals_lie_group : lie_add_group (model_with_corners_self ℝ ℝ) ℝ := by apply_instance end real_numbers_lie_group
18546cbda1c921f85114deddf4836128c6239bcf
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/default.lean
a3d2c358a9bfc1d85e974ba3ac2f584f3a703729
[ "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
49
lean
import algebra.group import algebra.module.basic
6b893bc69d0c75eb6255e1bf240158727731a67b
4e39e38e0c2134eafdc7ab6e0f8ca5c27795f7a2
/00_Foundations/example.lean
e99a7ec4e666111f9cf6a7b68a4a51e5feb85e93
[]
no_license
tcmch/cs-dm
a33c4169b8282b54653be72b9600e83ad329953c
4d9e45e398d7ec12538fe0335c007b98f0b32403
refs/heads/master
1,585,694,000,689
1,544,118,938,000
1,544,118,938,000
152,622,502
0
0
null
1,539,275,269,000
1,539,275,269,000
null
UTF-8
Lean
false
false
941
lean
variables P Q : Prop variable pfP : P variable pfQ : Q #check (and.intro pfP pfQ) def and_comm1(P Q: Prop)(pq: P /\ Q) : (Q /\ P) := and.intro (and.elim_right pq) (and.elim_left pq) #check and_comm1 P Q (and.intro pfP pfQ) def and_comm2 : ∀ P Q: Prop, P /\ Q → Q /\ P := λ X Y pq, and.intro (and.elim_right pq) (and.elim_left pq) #check and_comm2 def inc: ℕ → ℕ := λ n : ℕ, 0 def n: nat := 0 #check true def t: true := true.intro #check false def no_contra: ∀ P: Prop, ¬(P /\ ¬ P) := λ P pf, pf.right pf.left #check no_contra theorem foo : ∀ P Q R : Prop, (P → Q) → (Q → R) → (P → R) := λ P Q R pq qr, λ P, qr (pq P) #check foo section se theorem zeqz : 0 = 0 := eq.refl 0 theorem zneqo : 0 ≠ 1 := begin assume zeqo : 0 = 1, show false, from nat.no_confusion zeqo end theorem zneqo' : 0 = 1 → false := λ pf : 0 = 1, nat.no_confusion pf end se
bebad9e94754328edaa3fe7919752950503af355
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/algebra/infinite_sum.lean
635e1ba677e82483812140e741e5b276c42b2b99
[ "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
68,363
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.intervals import algebra.big_operators.nat_antidiagonal import logic.encodable.lattice import topology.algebra.mul_action import topology.algebra.order.monotone_convergence import topology.instances.real /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators nnreal variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 -- see Note [operator precedence of big operators] notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma has_sum_empty [is_empty β] : has_sum f 0 := by convert has_sum_zero lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma summable_empty [is_empty β] : summable f := has_sum_empty.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 := by simp [tsum, h] lemma summable_congr (hfg : ∀b, f b = g b) : summable f ↔ summable g := iff_of_eq (congr_arg summable $ funext hfg) lemma summable.congr (hf : summable f) (hfg : ∀b, f b = g b) : summable g := (summable_congr hfg).mp hf lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator_subset] lemma summable_subtype_iff_indicator {s : set β} : summable (f ∘ coe : s → α) ↔ summable (s.indicator f) := exists_congr (λ _, has_sum_subtype_iff_indicator) @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) : has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a := (equiv.of_injective g hg).has_sum_iff.symm lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) {G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ map_sum g _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) {G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable protected lemma summable.map_iff_of_left_inverse [add_comm_monoid γ] [topological_space γ] {G G'} [add_monoid_hom_class G α γ] [add_monoid_hom_class G' γ α] (g : G) (g' : G') (hg : continuous g) (hg' : continuous g') (hinv : function.left_inverse g' g) : summable (g ∘ f) ↔ summable f := ⟨λ h, begin have := h.map _ hg', rwa [←function.comp.assoc, hinv.id] at this, end, λ h, h.map _ hg⟩ /-- A special case of `summable.map_iff_of_left_inverse` for convenience -/ protected lemma summable.map_iff_of_equiv [add_comm_monoid γ] [topological_space γ] {G} [add_equiv_class G α γ] (g : G) (hg : continuous g) (hg' : continuous (add_equiv_class.inv g : γ → α)) : summable (g ∘ f) ↔ summable f := summable.map_iff_of_left_inverse g (g : α ≃+ γ).symm hg hg' (add_equiv_class.left_inv g) /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma function.surjective.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] {e : α' → α} (hes : function.surjective e) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := hes.exists.trans $ exists_congr $ @he section mul_opposite open mul_opposite lemma has_sum.op (hf : has_sum f a) : has_sum (λ a, op (f a)) (op a) := (hf.map (@op_add_equiv α _) continuous_op : _) lemma summable.op (hf : summable f) : summable (op ∘ f) := hf.has_sum.op.summable lemma has_sum.unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} (hf : has_sum f a) : has_sum (λ a, unop (f a)) (unop a) := (hf.map (@op_add_equiv α _).symm continuous_unop : _) lemma summable.unop {f : β → αᵐᵒᵖ} (hf : summable f) : summable (unop ∘ f) := hf.has_sum.unop.summable @[simp] lemma has_sum_op : has_sum (λ a, op (f a)) (op a) ↔ has_sum f a := ⟨has_sum.unop, has_sum.op⟩ @[simp] lemma has_sum_unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} : has_sum (λ a, unop (f a)) (unop a) ↔ has_sum f a := ⟨has_sum.op, has_sum.unop⟩ @[simp] lemma summable_op : summable (λ a, op (f a)) ↔ summable f := ⟨summable.unop, summable.op⟩ @[simp] lemma summable_unop {f : β → αᵐᵒᵖ} : summable (λ a, unop (f a)) ↔ summable f := ⟨summable.op, summable.unop⟩ end mul_opposite section has_continuous_star variables [star_add_monoid α] [has_continuous_star α] lemma has_sum.star (h : has_sum f a) : has_sum (λ b, star (f b)) (star a) := by simpa only using h.map (star_add_equiv : α ≃+ α) continuous_star lemma summable.star (hf : summable f) : summable (λ b, star (f b)) := hf.has_sum.star.summable lemma summable.of_star (hf : summable (λ b, star (f b))) : summable f := by simpa only [star_star] using hf.star @[simp] lemma summable_star_iff : summable (λ b, star (f b)) ↔ summable f := ⟨summable.of_star, summable.star⟩ @[simp] lemma summable_star_iff' : summable (star f) ↔ summable f := summable_star_iff end has_continuous_star variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff]) (by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp, forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum (f ∘ coe : s ∪ t → α) (a + b) := begin rw has_sum_subtype_iff_indicator at *, rw set.indicator_union_of_disjoint hs, exact ha.add hb end lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum f (a + b) := by simpa [← hs.compl_eq] using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl hb lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl.symm hb lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a) (ho : has_sum (λ k, f (2 * k + 1)) b) : has_sum f (a + b) := begin have := mul_right_injective₀ (@two_ne_zero ℕ _ _), replace he := this.has_sum_range_iff.2 he, replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho, refine he.add_is_compl _ ho, simpa [(∘)] using nat.is_compl_even_odd end lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : summable f := (he.has_sum.even_add_odd ho.has_sum).summable lemma has_sum.sigma [t3_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [t3_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [t3_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [t3_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] lemma tsum_congr_subtype (f : β → α) {s t : set β} (h : s = t) : ∑' (x : s), f x = ∑' (x : t), f x := by rw h lemma tsum_zero' (hz : is_closed ({0} : set α)) : ∑' b : β, (0 : α) = 0 := begin classical, rw [tsum, dif_pos summable_zero], suffices : ∀ (x : α), has_sum (λ (b : β), (0 : α)) x → x = 0, { exact this _ (classical.some_spec _) }, intros x hx, contrapose! hx, simp only [has_sum, tendsto_nhds, finset.sum_const_zero, filter.mem_at_top_sets, ge_iff_le, finset.le_eq_subset, set.mem_preimage, not_forall, not_exists, exists_prop, exists_and_distrib_right], refine ⟨{0}ᶜ, ⟨is_open_compl_iff.mpr hz, _⟩, λ y, ⟨⟨y, subset_refl _⟩, _⟩⟩, { simpa using hx }, { simp } end @[simp] lemma tsum_zero [t1_space α] : ∑' b : β, (0 : α) = 0 := tsum_zero' is_closed_singleton variables [t2_space α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_empty [is_empty β] : ∑'b, f b = 0 := has_sum_empty.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : ∑' b, f b = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α] {f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b := congr_arg tsum (funext hfg) lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b := (has_sum_fintype f).tsum_eq lemma tsum_bool (f : bool → α) : ∑' i : bool, f i = f false + f true := by { rw [tsum_fintype, finset.sum_eq_add]; simp } @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : ∑' x : {x // x ∈ s}, f x = ∑ x in s, f x := (s.has_sum f).tsum_eq @[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) : ∑' x : (s : set β), f x = ∑ x in s, f x := s.tsum_subtype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : ∑'b, f b = f b := (has_sum_single b hf).tsum_eq lemma tsum_tsum_eq_single (f : β → γ → α) (b : β) (c : γ) (hfb : ∀ b' ≠ b, f b' c = 0) (hfc : ∀ (b' : β) (c' : γ), c' ≠ c → f b' c' = 0) : ∑' b' c', f b' c' = f b c := calc ∑' b' c', f b' c' = ∑' b', f b' c : tsum_congr $ λ b', tsum_eq_single _ (hfc b') ... = f b c : tsum_eq_single _ hfb @[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : ∑' b', (if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) : ∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h := by by_cases hP : P; simp [hP] lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) : ∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 := by by_cases hP : P; simp [hP] lemma function.surjective.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] {e : α' → α} (hes : function.surjective e) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : ∑' b, f b = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (hes.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : ∑'b, f b = ∑'c, g c := surjective_id.tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : ∑' x, f x = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : ∑' x:s, f x = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator lemma tsum_op : ∑' x, mul_opposite.op (f x) = mul_opposite.op (∑' x, f x) := begin by_cases h : summable f, { exact h.has_sum.op.tsum_eq, }, { have ho := summable_op.not.mpr h, rw [tsum_eq_zero_of_not_summable h, tsum_eq_zero_of_not_summable ho, mul_opposite.op_zero] }, end lemma tsum_unop {f : β → αᵐᵒᵖ} : ∑' x, mul_opposite.unop (f x) = mul_opposite.unop (∑' x, f x) := mul_opposite.op_injective tsum_op.symm section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : ∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [t3_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [t3_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : ∑'p, f p = ∑'b c, f (b, c) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [t3_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : ∑' c b, f b c = ∑' b c, f b c := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section has_continuous_star variables [star_add_monoid α] [has_continuous_star α] lemma tsum_star : star (∑' b, f b) = ∑' b, star (f b) := begin by_cases hf : summable f, { exact hf.has_sum.star.tsum_eq.symm, }, { rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_star hf), star_zero] }, end end has_continuous_star open encodable section encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode₂ [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode₂ γ i, s b) = ∑' b : γ, m (s b) := begin have H : ∀ n, m (⨆ b ∈ decode₂ γ n, s b) ≠ 0 → (decode₂ γ n).is_some, { intros n h, cases decode₂ γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode₂.1 (option.get_mem (H n hn)), rwa [← e, mem_decode₂.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek₂] at h ⊢, convert h, simp [set.ext_iff, encodek₂] }, { exact option.get_of_mem _ (encodek₂ _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode₂ γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode₂` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode₂ (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : ∑' i, m (⋃ b ∈ decode₂ γ i, s b) = ∑' b, m (s b) := tsum_supr_decode₂ m m0 s end encodable /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ section countable variables [countable γ] /-- If a function is countably sub-additive then it is sub-additive on countable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i)) (s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) := by { casesI nonempty_encodable γ, rw [←supr_decode₂, ←tsum_supr_decode₂ _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { rw [supr_subtype', ←finset.tsum_subtype], exact rel_supr_tsum m m0 R m_supr _ } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end countable variables [has_continuous_add α] lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t) (hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) : (∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) := (hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : (∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k := (he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm end tsum section prod variables [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ] lemma has_sum.prod_mk {f : β → α} {g : β → γ} {a : α} {b : γ} (hf : has_sum f a) (hg : has_sum g b) : has_sum (λ x, (⟨f x, g x⟩ : α × γ)) ⟨a, b⟩ := by simp [has_sum, ← prod_mk_sum, filter.tendsto.prod_mk_nhds hf hg] end prod section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp only [has_sum, tendsto_pi_nhds, sum_apply] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp only [summable, pi.has_sum, skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp only [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma summable.trans_sub (hg : summable g) (hfg : summable (λb, f b - g b)) : summable f := by simpa only [sub_add_cancel] using hfg.add hg lemma summable_iff_of_summable_sub (hfg : summable (λb, f b - g b)) : summable f ↔ summable g := ⟨λ hf, hf.trans_sub $ by simpa only [neg_sub] using hfg.neg, λ hg, hg.trans_sub hfg⟩ lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) : has_sum (update f b a) (a - f b + a₁) := begin convert ((has_sum_ite_eq b _).add hf), ext b', by_cases h : b' = b, { rw [h, update_same], simp only [eq_self_iff_true, if_true, sub_add_cancel] }, simp only [h, update_noteq, if_false, ne.def, zero_add, not_false_iff], end lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) : summable (update f b a) := (hf.has_sum.update b a).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff lemma has_sum_ite_eq_extract [decidable_eq β] (hf : has_sum f a) (b : β) : has_sum (λ n, ite (n = b) 0 (f n)) (a - f b) := begin convert hf.update b 0 using 1, { ext n, rw function.update_apply, }, { rw [sub_add_eq_add_sub, zero_add], }, end section tsum variables [t2_space α] lemma tsum_neg : ∑'b, - f b = - ∑'b, f b := begin by_cases hf : summable f, { exact hf.has_sum.neg.tsum_eq, }, { simp [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_neg hf)] }, end lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b := (hf.has_sum.sub hg.has_sum).tsum_eq lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm /-- Let `f : β → α` be a sequence with summable series and let `b ∈ β` be an index. Lemma `tsum_ite_eq_extract` writes `Σ f n` as the sum of `f b` plus the series of the remaining terms. -/ lemma tsum_ite_eq_extract [decidable_eq β] (hf : summable f) (b : β) : ∑' n, f n = f b + ∑' n, ite (n = b) 0 (f n) := begin rw (has_sum_ite_eq_extract hf.has_sum b).tsum_eq, exact (add_sub_cancel'_right _ _).symm, end end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).surjective.summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i := by simpa only [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : ∑'b, f b = f 0 + ∑'b, f (b + 1) := by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin by_cases hf : summable f, { have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i), { ext1 i, rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] }, have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds, simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat }, { convert tendsto_const_nhds, ext1 i, rw ← summable_nat_add_iff i at hf, { exact tsum_eq_zero_of_not_summable hf }, { apply_instance } } end /-- If `f₀, f₁, f₂, ...` and `g₀, g₁, g₂, ...` are both convergent then so is the `ℤ`-indexed sequence: `..., g₂, g₁, g₀, f₀, f₁, f₂, ...`. -/ lemma has_sum.int_rec {b : α} {f g : ℕ → α} (hf : has_sum f a) (hg : has_sum g b) : @has_sum α _ _ _ (@int.rec (λ _, α) f g : ℤ → α) (a + b) := begin -- note this proof works for any two-case inductive have h₁ : injective (coe : ℕ → ℤ) := @int.of_nat.inj, have h₂ : injective int.neg_succ_of_nat := @int.neg_succ_of_nat.inj, have : is_compl (set.range (coe : ℕ → ℤ)) (set.range int.neg_succ_of_nat), { split, { rintros _ ⟨⟨i, rfl⟩, ⟨j, ⟨⟩⟩⟩ }, { rintros (i | j) h, exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] } }, exact has_sum.add_is_compl this (h₁.has_sum_range_iff.mpr hf) (h₂.has_sum_range_iff.mpr hg), end lemma has_sum.nonneg_add_neg {b : α} {f : ℤ → α} (hnonneg : has_sum (λ n : ℕ, f n) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) : has_sum f (a + b) := begin simp_rw ← int.neg_succ_of_nat_coe at hneg, convert hnonneg.int_rec hneg using 1, ext (i | j); refl, end lemma has_sum.pos_add_zero_add_neg {b : α} {f : ℤ → α} (hpos : has_sum (λ n:ℕ, f(n + 1)) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) : has_sum f (a + f 0 + b) := begin have : ∀ g : ℕ → α, has_sum (λ k, g (k + 1)) a → has_sum g (a + g 0), { intros g hg, simpa using (has_sum_nat_add_iff _).mp hg }, exact (this (λ n, f n) hpos).nonneg_add_neg hneg, end end subtype end topological_group section topological_semiring variables [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma summable.tsum_mul_left (a) (hf : summable f) : ∑'b, a * f b = a * ∑'b, f b := (hf.has_sum.mul_left _).tsum_eq lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq lemma commute.tsum_right (a) (h : ∀ b, commute a (f b)) : commute a (∑' b, f b) := if hf : summable f then (hf.tsum_mul_left a).symm.trans ((congr_arg _ $ funext h).trans (hf.tsum_mul_right a)) else (tsum_eq_zero_of_not_summable hf).symm ▸ commute.zero_right _ lemma commute.tsum_left (a) (h : ∀ b, commute (f b) a) : commute (∑' b, f b) a := (commute.tsum_right _ $ λ b, (h b).symm).symm end tsum end topological_semiring section const_smul variables {R : Type*} [monoid R] [topological_space α] [add_comm_monoid α] [distrib_mul_action R α] [has_continuous_const_smul R α] {f : β → α} lemma has_sum.const_smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) := hf.map (distrib_mul_action.to_add_monoid_hom α r) (continuous_const_smul r) lemma summable.const_smul {r : R} (hf : summable f) : summable (λ z, r • f z) := hf.has_sum.const_smul.summable lemma tsum_const_smul [t2_space α] {r : R} (hf : summable f) : ∑' z, r • f z = r • ∑' z, f z := hf.has_sum.const_smul.tsum_eq end const_smul section smul_const variables {R : Type*} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [module R α] [has_continuous_smul R α] {f : β → R} lemma has_sum.smul_const {a : α} {r : R} (hf : has_sum f r) : has_sum (λ z, f z • a) (r • a) := hf.map ((smul_add_hom R α).flip a) (continuous_id.smul continuous_const) lemma summable.smul_const {a : α} (hf : summable f) : summable (λ z, f z • a) := hf.has_sum.smul_const.summable lemma tsum_smul_const [t2_space α] {a : α} (hf : summable f) : ∑' z, f z • a = (∑' z, f z) • a := hf.has_sum.smul_const.tsum_eq end smul_const section division_ring variables [division_ring α] [topological_space α] [topological_ring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.div_const (h : has_sum f a) (b : α) : has_sum (λ x, f x / b) (a / b) := by simp only [div_eq_mul_inv, h.mul_right b⁻¹] lemma summable.div_const (h : summable f) (b : α) : summable (λ x, f x / b) := (h.has_sum.div_const b).summable lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a⁻¹⟩ lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x := if hf : summable f then hf.tsum_mul_left a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero] lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a := if hf : summable f then hf.tsum_mul_right a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul] end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b @[mono] lemma has_sum_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f ≤ g) : a₁ ≤ a₂ := has_sum_le h hf hg lemma has_sum_le_of_sum_le (hf : has_sum f a) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : a ≤ a₂ := le_of_tendsto' hf h lemma le_has_sum_of_le_sum (hf : has_sum f a) (h : ∀ s : finset β, a₂ ≤ ∑ b in s, f b) : a₂ ≤ a := ge_of_tendsto' hf h lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma is_lub_has_sum (h : ∀ b, 0 ≤ f b) (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto_at_top (finset.sum_mono_set_of_nonneg h) hf lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ ∑' b, f b := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : ∑'b, f b ≤ ∑'b, g b := has_sum_le h hf.has_sum hg.has_sum @[mono] lemma tsum_mono (hf : summable f) (hg : summable g) (h : f ≤ g) : ∑' n, f n ≤ ∑' n, g n := tsum_le_tsum h hf hg lemma tsum_le_of_sum_le (hf : summable f) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := has_sum_le_of_sum_le hf.has_sum h lemma tsum_le_of_sum_le' (ha₂ : 0 ≤ a₂) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := begin by_cases hf : summable f, { exact tsum_le_of_sum_le hf h }, { rw tsum_eq_zero_of_not_summable hf, exact ha₂ } end lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ ∑'b, g b := begin by_cases hg : summable g, { exact hg.has_sum.nonneg h }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : ∑'b, f b ≤ 0 := begin by_cases hf : summable f, { exact hf.has_sum.nonpos h }, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section ordered_topological_group variables [ordered_add_comm_group α] [topological_space α] [topological_add_group α] [order_closed_topology α] {f g : β → α} {a₁ a₂ : α} lemma has_sum_lt {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ < a₂ := have update f i 0 ≤ update g i 0 := update_le_update_iff.mpr ⟨rfl.le, λ i _, h i⟩, have 0 - f i + a₁ ≤ 0 - g i + a₂ := has_sum_le this (hf.update i 0) (hg.update i 0), by simpa only [zero_sub, add_neg_cancel_left] using add_lt_add_of_lt_of_le hi this @[mono] lemma has_sum_strict_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f < g) : a₁ < a₂ := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : summable f) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi hf.has_sum hg.has_sum @[mono] lemma tsum_strict_mono (hf : summable f) (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hf hg lemma tsum_pos (hsum : summable g) (hg : ∀ b, 0 ≤ g b) (i : β) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum hg hi summable_zero hsum } lemma has_sum_zero_iff_of_nonneg (hf : ∀ i, 0 ≤ f i) : has_sum f 0 ↔ f = 0 := begin split, { intros hf', ext i, by_contra hi', have hi : 0 < f i := lt_of_le_of_ne (hf i) (ne.symm hi'), simpa using has_sum_lt hf hi has_sum_zero hf' }, { rintros rfl, exact has_sum_zero }, end end ordered_topological_group section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] lemma tsum_ne_zero_iff (hf : summable f) : ∑' i, f i ≠ 0 ↔ ∃ x, f x ≠ 0 := by rw [ne.def, tsum_eq_zero_iff hf, not_forall] lemma is_lub_has_sum' (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto_at_top (finset.sum_mono_set f) hf end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] /-- The **Cauchy criterion** for infinite sums, also known as the **Cauchy convergence test** -/ lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_of_le_left le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end local attribute [instance] topological_add_group.t3_space /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero [t1_space α] (f : β → α) : tendsto (λ (s : finset β), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin by_cases H : summable f, { assume e he, rcases nhds_is_closed he with ⟨o, ho, oe, o_closed⟩, simp only [le_eq_subset, set.mem_preimage, mem_at_top_sets, filter.mem_map, ge_iff_le], obtain ⟨s, hs⟩ : ∃ (s : finset β), ∀ (t : finset β), disjoint t s → ∑ (b : β) in t, f b ∈ o := cauchy_seq_finset_iff_vanishing.1 (tendsto.cauchy_seq H.has_sum) o ho, refine ⟨s, λ a sa, oe _⟩, have A : summable (λ b : {x // x ∉ a}, f b) := a.summable_compl_iff.2 H, apply is_closed.mem_of_tendsto o_closed A.has_sum (eventually_of_forall (λ b, _)), have : disjoint (finset.image (λ (i : {x // x ∉ a}), (i : β)) b) s, { apply disjoint_left.2 (λ i hi his, _), rcases mem_image.1 hi with ⟨i', hi', rfl⟩, exact i'.2 (sa his), }, convert hs _ this using 1, rw sum_image, assume i hi j hj hij, exact subtype.ext hij }, { convert tendsto_const_nhds, ext s, apply tsum_eq_zero_of_not_summable, rwa finset.summable_compl_iff } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [t1_space α] {f : β × γ → α} (h : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_prod' h h.prod_factor lemma tsum_comm [t1_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : ∑' c b, f b c = ∑' b c, f b c := tsum_comm' h h.prod_factor h.prod_symm.prod_factor lemma has_sum.sum_nat_of_sum_int [t2_space α] {f : ℤ → α} (hf : has_sum f a) : has_sum (λ n:ℕ, f(n + 1) + f(-n.succ)) (a - f 0) := begin obtain ⟨b₁, h₁⟩ : summable (λ n : ℕ, f(n + 1)) := hf.summable.comp_injective (λ x₁ x₂, by simp), obtain ⟨b₂, h₂⟩ : summable (λ n : ℕ, f(-n.succ)) := hf.summable.comp_injective (λ x₁ x₂, by simp), convert h₁.add h₂, rw hf.unique (h₁.pos_add_zero_add_neg h₂), abel, end end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_comm_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (disjoint_singleton_left.2 hx) end lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero } lemma summable.tendsto_top_of_pos {α : Type*} [linear_ordered_field α] [topological_space α] [order_topology α] {f : ℕ → α} (hf : summable f⁻¹) (hf' : ∀ n, 0 < f n) : tendsto f at_top at_top := begin rw [show f = f⁻¹⁻¹, by { ext, simp }], apply filter.tendsto.inv_tendsto_zero, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (summable.tendsto_at_top_zero hf), rw eventually_iff_exists_mem, refine ⟨set.Ioi 0, Ioi_mem_at_top _, λ _ _, _⟩, rw [set.mem_Ioi, inv_eq_one_div, one_div, pi.inv_apply, _root_.inv_pos], exact hf' _, end end topological_group section linear_order /-! For infinite sums taking values in a linearly ordered monoid, the existence of a least upper bound for the finite sums is a criterion for summability. This criterion is useful when applied in a linearly ordered monoid which is also a complete or conditionally complete linear order, such as `ℝ`, `ℝ≥0`, `ℝ≥0∞`, because it is then easy to check the existence of a least upper bound. -/ lemma has_sum_of_is_lub_of_nonneg [linear_ordered_add_comm_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (h : ∀ b, 0 ≤ f b) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set_of_nonneg h) hf lemma has_sum_of_is_lub [canonically_linear_ordered_add_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set f) hf lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, |f x|) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, |f x| = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, |f x| = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, |f x|) ↔ summable (λ x : {x | 0 ≤ f x}, |f x|) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, |f x|) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs lemma finite_of_summable_const [linear_ordered_add_comm_group β] [archimedean β] [topological_space β] [order_closed_topology β] {b : β} (hb : 0 < b) (hf : summable (λ a : α, b)) : set.finite (set.univ : set α) := begin have H : ∀ s : finset α, s.card • b ≤ ∑' a : α, b, { intros s, simpa using sum_le_has_sum s (λ a ha, hb.le) hf.has_sum }, obtain ⟨n, hn⟩ := archimedean.arch (∑' a : α, b) hb, have : ∀ s : finset α, s.card ≤ n, { intros s, simpa [nsmul_le_nsmul_iff hb] using (H s).trans hn }, haveI : fintype α := fintype_of_finset_card_le n this, exact set.finite_univ end end linear_order section cauchy_seq open filter /-- If the extended distance between consecutive points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [pseudo_emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, add_tsub_cancel_left] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consecutive points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ |∑ x in Ico N n, d x| : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_rfl) h lemma dist_le_tsum_of_dist_le_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_rfl) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq /-! ## Multipliying two infinite sums In this section, we prove various results about `(∑' x : β, f x) * (∑' y : γ, g y)`. Note that we always assume that the family `λ x : β × γ, f x.1 * g x.2` is summable, since there is no way to deduce this from the summmabilities of `f` and `g` in general, but if you are working in a normed space, you may want to use the analogous lemmas in `analysis/normed_space/basic` (e.g `tsum_mul_tsum_of_summable_norm`). We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to `β = γ = ℕ` to prove the Cauchy product formula (see `tsum_mul_tsum_eq_tsum_sum_antidiagonal`). ### Arbitrary index types -/ section tsum_mul_tsum variables [topological_space α] [t3_space α] [non_unital_non_assoc_semiring α] [topological_semiring α] {f : β → α} {g : γ → α} {s t u : α} lemma has_sum.mul_eq (hf : has_sum f s) (hg : has_sum g t) (hfg : has_sum (λ (x : β × γ), f x.1 * g x.2) u) : s * t = u := have key₁ : has_sum (λ b, f b * t) (s * t), from hf.mul_right t, have this : ∀ b : β, has_sum (λ c : γ, f b * g c) (f b * t), from λ b, hg.mul_left (f b), have key₂ : has_sum (λ b, f b * t) u, from has_sum.prod_fiberwise hfg this, key₁.unique key₂ lemma has_sum.mul (hf : has_sum f s) (hg : has_sum g t) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : has_sum (λ (x : β × γ), f x.1 * g x.2) (s * t) := let ⟨u, hu⟩ := hfg in (hf.mul_eq hg hu).symm ▸ hu /-- Product of two infinites sums indexed by arbitrary types. See also `tsum_mul_tsum_of_summable_norm` if `f` and `g` are abolutely summable. -/ lemma tsum_mul_tsum (hf : summable f) (hg : summable g) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : (∑' x, f x) * (∑' y, g y) = (∑' z : β × γ, f z.1 * g z.2) := hf.has_sum.mul_eq hg.has_sum hfg.has_sum end tsum_mul_tsum section cauchy_product /-! ### `ℕ`-indexed families (Cauchy product) We prove two versions of the Cauchy product formula. The first one is `tsum_mul_tsum_eq_tsum_sum_range`, where the `n`-th term is a sum over `finset.range (n+1)` involving `nat` substraction. In order to avoid `nat` substraction, we also provide `tsum_mul_tsum_eq_tsum_sum_antidiagonal`, where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the `finset` `finset.nat.antidiagonal n` -/ variables {f : ℕ → α} {g : ℕ → α} open finset variables [topological_space α] [non_unital_non_assoc_semiring α] /- The family `(k, l) : ℕ × ℕ ↦ f k * g l` is summable if and only if the family `(n, k, l) : Σ (n : ℕ), nat.antidiagonal n ↦ f k * g l` is summable. -/ lemma summable_mul_prod_iff_summable_mul_sigma_antidiagonal {f g : ℕ → α} : summable (λ x : ℕ × ℕ, f x.1 * g x.2) ↔ summable (λ x : (Σ (n : ℕ), nat.antidiagonal n), f (x.2 : ℕ × ℕ).1 * g (x.2 : ℕ × ℕ).2) := nat.sigma_antidiagonal_equiv_prod.summable_iff.symm variables [t3_space α] [topological_semiring α] lemma summable_sum_mul_antidiagonal_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin rw summable_mul_prod_iff_summable_mul_sigma_antidiagonal at h, conv {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, exact h.sigma' (λ n, (has_sum_fintype _).summable), end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.nat.antidiagonal`. See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin conv_rhs {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, rw [tsum_mul_tsum hf hg hfg, ← nat.sigma_antidiagonal_equiv_prod.tsum_eq (_ : ℕ × ℕ → α)], exact tsum_sigma' (λ n, (has_sum_fintype _).summable) (summable_mul_prod_iff_summable_mul_sigma_antidiagonal.mp hfg) end lemma summable_sum_mul_range_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact summable_sum_mul_antidiagonal_of_summable_mul h end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.range`. See also `tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_range (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact tsum_mul_tsum_eq_tsum_sum_antidiagonal hf hg hfg end end cauchy_product
c4df947fc5a9f3f642a55804781cf5b473dc3094
c8b4b578b2fe61d500fbca7480e506f6603ea698
/src/flt_regular.lean
15c3fcd3fe1da1827baf600e847df71802bae111
[]
no_license
leanprover-community/flt-regular
aa7e564f2679dfd2e86015a5a9674a6e1197f7cc
67fb3e176584bbc03616c221a7be6fa28c5ccd32
refs/heads/master
1,692,188,905,751
1,691,766,312,000
1,691,766,312,000
421,021,216
19
4
null
1,694,532,115,000
1,635,166,136,000
Lean
UTF-8
Lean
false
false
649
lean
import caseI.statement import caseII.statement open flt_regular /-- Statement of Fermat's last theorem for regular primes. -/ def flt_regular.statement : Prop := ∀ ⦃a b c : ℤ⦄ ⦃p : ℕ⦄ [hpri : fact p.prime] (hreg : @is_regular_prime p hpri) (hodd : p ≠ 2) (hprod : a * b * c ≠ 0), a ^ p + b ^ p ≠ c ^ p /-- Fermat's last theorem for regular primes.. -/ theorem flt_regular {a b c : ℤ} {p : ℕ} [fact p.prime] (hreg : is_regular_prime p) (hodd : p ≠ 2) (hprod : a * b * c ≠ 0) : a ^ p + b ^ p ≠ c ^ p := begin by_cases case : ↑p ∣ a * b * c, exact caseII hreg hodd hprod case, exact caseI hreg case end
f2169532b4e52df1226b4a42b16eb7abadc580db
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/localization/basic.lean
aff3a6372c8cc0afb3cfac71ad875ae260e12770
[ "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
45,667
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import algebra.algebra.equiv import algebra.ring.equiv import group_theory.monoid_localization import ring_theory.ideal.basic import ring_theory.non_zero_divisors import tactic.ring_exp /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. In the following, let `R, P` be commutative rings, `S, Q` be `R`- and `P`-algebras and `M, T` be submonoids of `R` and `P` respectively, e.g.: ``` variables (R S P Q : Type*) [comm_ring R] [comm_ring S] [comm_ring P] [comm_ring Q] variables [algebra R S] [algebra P Q] (M : submonoid R) (T : submonoid P) ``` ## Main definitions * `is_localization (M : submonoid R) (S : Type*)` is a typeclass expressing that `S` is a localization of `R` at `M`, i.e. the canonical map `algebra_map R S : R →+* S` is a localization map (satisfying the above properties). * `is_localization.mk' S` is a surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹` * `is_localization.lift` is the ring homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. * `is_localization.map S Q` is the ring homomorphism from `S` to `Q` which maps elements of `M` to elements of `T` * `is_localization.ring_equiv_of_ring_equiv`: if `R` and `P` are isomorphic by an isomorphism sending `M` to `T`, then `S` and `Q` are isomorphic * `is_localization.alg_equiv`: if `Q` is another localization of `R` at `M`, then `S` and `Q` are isomorphic as `R`-algebras ## Main results * `localization M S`, a construction of the localization as a quotient type, defined in `group_theory.monoid_localization`, has `comm_ring`, `algebra R` and `is_localization M` instances if `R` is a ring. `localization.away`, `localization.at_prime` and `fraction_ring` are abbreviations for `localization`s and have their corresponding `is_localization` instances ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A previous version of this file used a fully bundled type of ring localization maps, then used a type synonym `f.codomain` for `f : localization_map M S` to instantiate the `R`-algebra structure on `S`. This results in defining ad-hoc copies for everything already defined on `S`. By making `is_localization` a predicate on the `algebra_map R S`, we can ensure the localization map commutes nicely with other `algebra_map`s. To prove most lemmas about a localization map `algebra_map R S` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `is_localization.to_localization_map M S`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `algebra_map : R →+* localization M`. The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ open function open_locale big_operators section comm_semiring variables {R : Type*} [comm_semiring R] (M : submonoid R) (S : Type*) [comm_semiring S] variables [algebra R S] {P : Type*} [comm_semiring P] /-- The typeclass `is_localization (M : submodule R) S` where `S` is an `R`-algebra expresses that `S` is isomorphic to the localization of `R` at `M`. -/ class is_localization : Prop := (map_units [] : ∀ y : M, is_unit (algebra_map R S y)) (surj [] : ∀ z : S, ∃ x : R × M, z * algebra_map R S x.2 = algebra_map R S x.1) (eq_iff_exists [] : ∀ {x y}, algebra_map R S x = algebra_map R S y ↔ ∃ c : M, x * c = y * c) variables {M S} namespace is_localization section is_localization variables [is_localization M S] section variables (M) lemma of_le (N : submonoid R) (h₁ : M ≤ N) (h₂ : ∀ r ∈ N, is_unit (algebra_map R S r)) : is_localization N S := { map_units := λ r, h₂ r r.2, surj := λ s, by { obtain ⟨⟨x, y, hy⟩, H⟩ := is_localization.surj M s, exact ⟨⟨x, y, h₁ hy⟩, H⟩ }, eq_iff_exists := λ x y, begin split, { rw is_localization.eq_iff_exists M, rintro ⟨c, hc⟩, exact ⟨⟨c, h₁ c.2⟩, hc⟩ }, { rintro ⟨c, h⟩, simpa only [set_like.coe_mk, map_mul, (h₂ c c.2).mul_left_inj] using congr_arg (algebra_map R S) h } end } variables (S) /-- `is_localization.to_localization_with_zero_map M S` shows `S` is the monoid localization of `R` at `M`. -/ @[simps] def to_localization_with_zero_map : submonoid.localization_with_zero_map M S := { to_fun := algebra_map R S, map_units' := is_localization.map_units _, surj' := is_localization.surj _, eq_iff_exists' := λ _ _, is_localization.eq_iff_exists _ _, .. algebra_map R S } /-- `is_localization.to_localization_map M S` shows `S` is the monoid localization of `R` at `M`. -/ abbreviation to_localization_map : submonoid.localization_map M S := (to_localization_with_zero_map M S).to_localization_map @[simp] lemma to_localization_map_to_map : (to_localization_map M S).to_map = (algebra_map R S : R →*₀ S) := rfl lemma to_localization_map_to_map_apply (x) : (to_localization_map M S).to_map x = algebra_map R S x := rfl end variables (M) /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ noncomputable def sec (z : S) : R × M := classical.some $ is_localization.surj _ z @[simp] lemma to_localization_map_sec : (to_localization_map M S).sec = sec M := rfl /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec (z : S) : z * algebra_map R S (is_localization.sec M z).2 = algebra_map R S (is_localization.sec M z).1 := classical.some_spec $ is_localization.surj _ z /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' (z : S) : algebra_map R S (is_localization.sec M z).1 = algebra_map R S (is_localization.sec M z).2 * z := by rw [mul_comm, sec_spec] variables {R M} lemma map_right_cancel {x y} {c : M} (h : algebra_map R S (c * x) = algebra_map R S (c * y)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : algebra_map R S (x * c) = algebra_map R S (y * c)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * algebra_map R S y = algebra_map R S x) (hx : x = 0) : z = 0 := by { rw [hx, (algebra_map R S).map_zero] at h, exact (is_unit.mul_left_eq_zero (is_localization.map_units S y)).1 h} variables (M S) lemma map_eq_zero_iff (r : R) : algebra_map R S r = 0 ↔ ∃ m : M, r * m = 0 := begin split, intro h, { obtain ⟨m, hm⟩ := (is_localization.eq_iff_exists M S).mp ((algebra_map R S).map_zero.trans h.symm), exact ⟨m, by simpa using hm.symm⟩ }, { rintro ⟨m, hm⟩, rw [← (is_localization.map_units S m).mul_left_inj, zero_mul, ← ring_hom.map_mul, hm, ring_hom.map_zero] } end variables {M} /-- `is_localization.mk' S` is the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (x : R) (y : M) : S := (to_localization_map M S).mk' x y @[simp] lemma mk'_sec (z : S) : mk' S (is_localization.sec M z).1 (is_localization.sec M z).2 = z := (to_localization_map M S).mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * x₂) (y₁ * y₂) = mk' S x₁ y₁ * mk' S x₂ y₂ := (to_localization_map M S).mk'_mul _ _ _ _ lemma mk'_one (x) : mk' S x (1 : M) = algebra_map R S x := (to_localization_map M S).mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : mk' S x y * algebra_map R S y = algebra_map R S x := (to_localization_map M S).mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : algebra_map R S y * mk' S x y = algebra_map R S x := (to_localization_map M S).mk'_spec' _ _ @[simp] lemma mk'_spec_mk (x) (y : R) (hy : y ∈ M) : mk' S x ⟨y, hy⟩ * algebra_map R S y = algebra_map R S x := mk'_spec S x ⟨y, hy⟩ @[simp] lemma mk'_spec'_mk (x) (y : R) (hy : y ∈ M) : algebra_map R S y * mk' S x ⟨y, hy⟩ = algebra_map R S x := mk'_spec' S x ⟨y, hy⟩ variables {S} theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = mk' S x y ↔ z * algebra_map R S y = algebra_map R S x := (to_localization_map M S).eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : mk' S x y = z ↔ algebra_map R S x = z * algebra_map R S y := (to_localization_map M S).mk'_eq_iff_eq_mul theorem mk'_add_eq_iff_add_mul_eq_mul {x} {y : M} {z₁ z₂} : mk' S x y + z₁ = z₂ ↔ algebra_map R S x + z₁ * algebra_map R S y = z₂ * algebra_map R S y := by rw [←mk'_spec S x y, ←is_unit.mul_left_inj (is_localization.map_units S y), right_distrib] variables (M) lemma mk'_surjective (z : S) : ∃ x (y : M), mk' S x y = z := let ⟨r, hr⟩ := is_localization.surj _ z in ⟨r.1, r.2, (eq_mk'_iff_mul_eq.2 hr).symm⟩ variables (S) include M /-- The localization of a `fintype` is a `fintype`. Cannot be an instance. -/ noncomputable def fintype' [fintype R] : fintype S := have _ := classical.prop_decidable, by exactI fintype.of_surjective (function.uncurry $ is_localization.mk' S) (λ a, prod.exists'.mpr $ is_localization.mk'_surjective M a) omit M variables {M S} /-- Localizing at a submonoid with 0 inside it leads to the trivial ring. -/ def unique_of_zero_mem (h : (0 : R) ∈ M) : unique S := unique_of_zero_eq_one $ by simpa using is_localization.map_units S ⟨0, h⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ algebra_map R S (x₁ * y₂) = algebra_map R S (x₂ * y₁) := (to_localization_map M S).mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : mk' S x y ∈ I ↔ algebra_map R S x ∈ I := begin split; intro h, { rw [← mk'_spec S x y, mul_comm], exact I.mul_mem_left ((algebra_map R S) y) h }, { rw ← mk'_spec S x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units S y), have := I.mul_mem_left b h, rwa [mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : mk' S a₁ a₂ = mk' S b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := (to_localization_map M S).eq lemma mk'_eq_zero_iff (x : R) (s : M) : mk' S x s = 0 ↔ ∃ (m : M), x * m = 0 := by rw [← (map_units S s).mul_left_inj, mk'_spec, zero_mul, map_eq_zero_iff M] @[simp] lemma mk'_zero (s : M) : is_localization.mk' S 0 s = 0 := by rw [eq_comm, is_localization.eq_mk'_iff_mul_eq, zero_mul, map_zero] lemma ne_zero_of_mk'_ne_zero {x : R} {y : M} (hxy : is_localization.mk' S x y ≠ 0) : x ≠ 0 := begin rintro rfl, exact hxy (is_localization.mk'_zero _) end section ext variables [algebra R P] [is_localization M P] lemma eq_iff_eq {x y} : algebra_map R S x = algebra_map R S y ↔ algebra_map R P x = algebra_map R P y := (to_localization_map M S).eq_iff_eq (to_localization_map M P) lemma mk'_eq_iff_mk'_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ mk' P x₁ y₁ = mk' P x₂ y₂ := (to_localization_map M S).mk'_eq_iff_mk'_eq (to_localization_map M P) lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : mk' S a₁ a₂ = mk' S b₁ b₂ := (to_localization_map M S).mk'_eq_of_eq H variables (S) @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : mk' S x ⟨x, hx⟩ = 1 := (to_localization_map M S).mk'_self _ hx @[simp] lemma mk'_self' {x : M} : mk' S (x : R) x = 1 := (to_localization_map M S).mk'_self' _ lemma mk'_self'' {x : M} : mk' S x.1 x = 1 := mk'_self' _ end ext lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : (algebra_map R S) x * mk' S y z = mk' S (x * y) z := (to_localization_map M S).mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : mk' S x y = (algebra_map R S) x * mk' S 1 y := ((to_localization_map M S).mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : mk' S (y * x : R) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : mk' S (x * y) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : mk' S (x : R) y * mk' S (y : R) x = 1 := by rw [←mk'_mul, mul_comm]; exact mk'_self _ _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : mk' S x y * mk' S (y : R) ⟨x, h⟩ = 1 := mk'_mul_mk'_eq_one ⟨x, h⟩ _ section variables (M) lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp (algebra_map R S) y) := (to_localization_map M S).is_unit_comp j.to_monoid_hom _ end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : (algebra_map R S) x = (algebra_map R S) y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = mk' S x₁ y₁ + mk' S x₂ y₂ := mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul, mul_comm (_ * _), ←mul_assoc, add_comm, ←map_mul, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul], simp only [map_add, submonoid.coe_mul, map_mul], ring end lemma mul_add_inv_left {g : R →+* P} (h : ∀ y : M, is_unit (g y)) (y : M) (w z₁ z₂ : P) : w * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) h y)⁻¹ + z₁ = z₂ ↔ w + g y * z₁ = g y * z₂ := begin rw [mul_comm, ←one_mul z₁, ←units.inv_mul (is_unit.lift_right (g.to_monoid_hom.restrict M) h y), mul_assoc, ←mul_add, units.inv_mul_eq_iff_eq_mul, units.inv_mul_cancel_left, is_unit.coe_lift_right], simp only [ring_hom.to_monoid_hom_eq_coe, monoid_hom.restrict_apply, ring_hom.coe_monoid_hom] end lemma lift_spec_mul_add {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) (z w w' v) : ((to_localization_with_zero_map M S).lift g.to_monoid_with_zero_hom hg) z * w + w' = v ↔ g ((to_localization_map M S).sec z).1 * w + g ((to_localization_map M S).sec z).2 * w' = g ((to_localization_map M S).sec z).2 * v := begin show (_ * _) * _ + _ = _ ↔ _ = _, erw [mul_comm, ←mul_assoc, mul_add_inv_left hg, mul_comm], refl end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := { map_add' := begin intros x y, erw [(to_localization_map M S).lift_spec, mul_add, mul_comm, eq_comm, lift_spec_mul_add, add_comm, mul_comm,mul_assoc,mul_comm,mul_assoc, lift_spec_mul_add], simp_rw ←mul_assoc, show g _ * g _ * g _ + g _ * g _ * g _ = g _ * g _ * g _, simp_rw [←map_mul g, ←map_add g], apply @eq_of_eq _ _ _ S _ _ _ _ _ g hg, simp only [sec_spec', to_localization_map_sec, map_add, map_mul], ring end, .. @submonoid.localization_with_zero_map.lift _ _ _ _ _ _ _ (to_localization_with_zero_map M S) g.to_monoid_with_zero_hom hg } variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : lift hg (mk' S x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) hg y)⁻¹ := (to_localization_map M S).lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : lift hg (mk' S x y) = v ↔ g x = g y * v := (to_localization_map M S).lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : lift hg ((algebra_map R S) x) = g x := (to_localization_map M S).lift_eq _ _ lemma lift_eq_iff {x y : R × M} : lift hg (mk' S x.1 x.2) = lift hg (mk' S y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := (to_localization_map M S).lift_eq_iff _ @[simp] lemma lift_comp : (lift hg).comp (algebra_map R S) = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : lift (is_unit_comp M j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_of_comp j.to_monoid_hom variables (M) /-- See note [partially-applied ext lemmas] -/ lemma monoid_hom_ext ⦃j k : S →* P⦄ (h : j.comp (algebra_map R S : R →* S) = k.comp (algebra_map R S)) : j = k := submonoid.localization_map.epic_of_localization_map (to_localization_map M S) $ monoid_hom.congr_fun h /-- See note [partially-applied ext lemmas] -/ lemma ring_hom_ext ⦃j k : S →+* P⦄ (h : j.comp (algebra_map R S) = k.comp (algebra_map R S)) : j = k := ring_hom.coe_monoid_hom_injective $ monoid_hom_ext M $ monoid_hom.ext $ ring_hom.congr_fun h /- This is not an instance because the submonoid `M` would become a metavariable in typeclass search. -/ lemma alg_hom_subsingleton [algebra R P] : subsingleton (S →ₐ[R] P) := ⟨λ f g, alg_hom.coe_ring_hom_injective $ is_localization.ring_hom_ext M $ by rw [f.comp_algebra_map, g.comp_algebra_map]⟩ /-- To show `j` and `k` agree on the whole localization, it suffices to show they agree on the image of the base ring, if they preserve `1` and `*`. -/ protected lemma ext (j k : S → P) (hj1 : j 1 = 1) (hk1 : k 1 = 1) (hjm : ∀ a b, j (a * b) = j a * j b) (hkm : ∀ a b, k (a * b) = k a * k b) (h : ∀ a, j (algebra_map R S a) = k (algebra_map R S a)) : j = k := monoid_hom.mk.inj (monoid_hom_ext M $ monoid_hom.ext h : (⟨j, hj1, hjm⟩ : S →* P) = ⟨k, hk1, hkm⟩) variables {M} lemma lift_unique {j : S →+* P} (hj : ∀ x, j ((algebra_map R S) x) = g x) : lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : lift (map_units S : ∀ y : M, is_unit _) x = x := (to_localization_map M S).lift_id _ lemma lift_surjective_iff : surjective (lift hg : S → P) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := (to_localization_map M S).lift_surjective_iff hg lemma lift_injective_iff : injective (lift hg : S → P) ↔ ∀ x y, algebra_map R S x = algebra_map R S y ↔ g x = g y := (to_localization_map M S).lift_injective_iff hg section map variables {T : submonoid P} {Q : Type*} [comm_semiring Q] (hy : M ≤ T.comap g) variables [algebra P Q] [is_localization T Q] section variables (Q) /-- Map a homomorphism `g : R →+* P` to `S →+* Q`, where `S` and `Q` are localizations of `R` and `P` at `M` and `T` respectively, such that `g(M) ⊆ T`. We send `z : S` to `algebra_map P Q (g x) * (algebra_map P Q (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : R →+* P) (hy : M ≤ T.comap g) : S →+* Q := @lift R _ M _ _ _ _ _ _ ((algebra_map P Q).comp g) (λ y, map_units _ ⟨g y, hy y.2⟩) end lemma map_eq (x) : map Q g hy ((algebra_map R S) x) = algebra_map P Q (g x) := lift_eq (λ y, map_units _ ⟨g y, hy y.2⟩) x @[simp] lemma map_comp : (map Q g hy).comp (algebra_map R S) = (algebra_map P Q).comp g := lift_comp $ λ y, map_units _ ⟨g y, hy y.2⟩ lemma map_mk' (x) (y : M) : map Q g hy (mk' S x y) = mk' Q (g x) ⟨g y, hy y.2⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom _ (λ y, hy y.2) _ _ (to_localization_map T Q) _ _ @[simp] lemma map_id (z : S) (h : M ≤ M.comap (ring_hom.id R) := le_refl M) : map S (ring_hom.id _) h z = z := lift_id _ lemma map_unique (j : S →+* Q) (hj : ∀ x : R, j (algebra_map R S x) = algebra_map P Q (g x)) : map Q g hy = j := lift_unique (λ y, map_units _ ⟨g y, hy y.2⟩) hj /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) : (map W l hl).comp (map Q g hy : S →+* _) = map W (l.comp g) (λ x hx, hl (hy hx)) := ring_hom.ext $ λ x, @submonoid.localization_map.map_map _ _ _ _ _ P _ (to_localization_map M S) g _ _ _ _ _ _ _ _ _ _ (to_localization_map U W) l _ x /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) (x : S) : map W l hl (map Q g hy x) = map W (l.comp g) (λ x hx, hl (hy hx)) x := by rw ←map_comp_map hy hl; refl lemma map_smul (x : S) (z : R) : map Q g hy (z • x : S) = g z • map Q g hy x := by rw [algebra.smul_def, algebra.smul_def, ring_hom.map_mul, map_eq] section variables (S Q) /-- If `S`, `Q` are localizations of `R` and `P` at submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ @[simps] noncomputable def ring_equiv_of_ring_equiv (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := have H' : T.map h.symm.to_monoid_hom = M, by { rw [← M.map_id, ← H, submonoid.map_map], congr, ext, apply h.symm_apply_apply }, { to_fun := map Q (h : R →+* P) (M.le_comap_of_map_le (le_of_eq H)), inv_fun := map S (h.symm : P →+* R) (T.le_comap_of_map_le (le_of_eq H')), left_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map R S) (h.symm_apply_apply x).symm }, right_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map P Q) (h.apply_symm_apply x).symm }, .. map Q (h : R →+* P) _ } end lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (ring_equiv_of_ring_equiv S Q j H : S →+* Q) = map Q (j : R →+* P) (M.le_comap_of_map_le (le_of_eq H)) := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : ring_equiv_of_ring_equiv S Q j H ((algebra_map R S) x) = algebra_map P Q (j x) := map_eq _ _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x : R) (y : M) : ring_equiv_of_ring_equiv S Q j H (mk' S x y) = mk' Q (j x) ⟨j y, show j y ∈ T, from H ▸ set.mem_image_of_mem j y.2⟩ := map_mk' _ _ _ end map section alg_equiv variables {Q : Type*} [comm_semiring Q] [algebra R Q] [is_localization M Q] section variables (M S Q) /-- If `S`, `Q` are localizations of `R` at the submonoid `M` respectively, there is an isomorphism of localizations `S ≃ₐ[R] Q`. -/ @[simps] noncomputable def alg_equiv : S ≃ₐ[R] Q := { commutes' := ring_equiv_of_ring_equiv_eq _, .. ring_equiv_of_ring_equiv S Q (ring_equiv.refl R) M.map_id } end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S Q (mk' S x y) = mk' Q x y:= map_mk' _ _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S Q).symm (mk' Q x y) = mk' S x y:= map_mk' _ _ _ end alg_equiv end is_localization section variables (M) lemma is_localization_of_alg_equiv [algebra R P] [is_localization M S] (h : S ≃ₐ[R] P) : is_localization M P := begin constructor, { intro y, convert (is_localization.map_units S y).map h.to_alg_hom.to_ring_hom.to_monoid_hom, exact (h.commutes y).symm }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M (h.symm y), apply_fun h at e, simp only [h.map_mul, h.apply_symm_apply, h.commutes] at e, exact ⟨⟨x, s⟩, e⟩ }, { intros x y, rw [← h.symm.to_equiv.injective.eq_iff, ← is_localization.eq_iff_exists M S, ← h.symm.commutes, ← h.symm.commutes], refl } end lemma is_localization_iff_of_alg_equiv [algebra R P] (h : S ≃ₐ[R] P) : is_localization M S ↔ is_localization M P := ⟨λ _, by exactI is_localization_of_alg_equiv M h, λ _, by exactI is_localization_of_alg_equiv M h.symm⟩ lemma is_localization_iff_of_ring_equiv (h : S ≃+* P) : is_localization M S ↔ @@is_localization _ M P _ (h.to_ring_hom.comp $ algebra_map R S).to_algebra := begin letI := (h.to_ring_hom.comp $ algebra_map R S).to_algebra, exact is_localization_iff_of_alg_equiv M { commutes' := λ _, rfl, ..h }, end variable (S) lemma is_localization_of_base_ring_equiv [is_localization M S] (h : R ≃+* P) : @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin constructor, { rintros ⟨_, ⟨y, hy, rfl⟩⟩, convert is_localization.map_units S ⟨y, hy⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply], exact congr_arg _ (h.symm_apply_apply _) }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M y, refine ⟨⟨h x, _, _, s.prop, rfl⟩, _⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply] at ⊢ e, convert e; exact h.symm_apply_apply _ }, { intros x y, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply, ring_hom.comp_apply, is_localization.eq_iff_exists M S], simp_rw ← h.to_equiv.apply_eq_iff_eq, change (∃ (c : M), h (h.symm x * c) = h (h.symm y * c)) ↔ _, simp only [ring_equiv.apply_symm_apply, ring_equiv.map_mul], exact ⟨λ ⟨c, e⟩, ⟨⟨_, _, c.prop, rfl⟩, e⟩, λ ⟨⟨_, c, h, e₁⟩, e₂⟩, ⟨⟨_, h⟩, e₁.symm ▸ e₂⟩⟩ } end lemma is_localization_iff_of_base_ring_equiv (h : R ≃+* P) : is_localization M S ↔ @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin refine ⟨λ _, by exactI is_localization_of_base_ring_equiv _ _ h, _⟩, letI := ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra, intro H, convert @@is_localization_of_base_ring_equiv _ _ _ _ _ _ H h.symm, { erw [submonoid.map_equiv_eq_comap_symm, submonoid.comap_map_eq_of_injective], exact h.to_equiv.injective }, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_assoc], simp only [ring_hom.comp_id, ring_equiv.symm_symm, ring_equiv.symm_to_ring_hom_comp_to_ring_hom], apply algebra.algebra_ext, intro r, rw ring_hom.algebra_map_to_algebra end end variables (M S) include M lemma non_zero_divisors_le_comap [is_localization M S] : non_zero_divisors R ≤ (non_zero_divisors S).comap (algebra_map R S) := begin rintros a ha b (e : b * algebra_map R S a = 0), obtain ⟨x, s, rfl⟩ := mk'_surjective M b, rw [← @mk'_one R _ M, ← mk'_mul, ← (algebra_map R S).map_zero, ← @mk'_one R _ M, is_localization.eq] at e, obtain ⟨c, e⟩ := e, rw [zero_mul, zero_mul, submonoid.coe_one, mul_one, mul_comm x a, mul_assoc, mul_comm] at e, rw mk'_eq_zero_iff, exact ⟨c, ha _ e⟩ end lemma map_non_zero_divisors_le [is_localization M S] : (non_zero_divisors R).map (algebra_map R S) ≤ non_zero_divisors S := submonoid.map_le_iff_le_comap.mpr (non_zero_divisors_le_comap M S) end is_localization namespace localization open is_localization /-! ### Constructing a localization at a given submonoid -/ variables {M} section instance [subsingleton R] : unique (localization M) := ⟨⟨1⟩, begin intro a, induction a, induction default, congr, refl, refl end⟩ /-- Addition in a ring localization is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨b * c + d * a, b * d⟩`. Should not be confused with `add_localization.add`, which is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨a + c, b + d⟩`. -/ @[irreducible] protected def add (z w : localization M) : localization M := localization.lift_on₂ z w (λ a b c d, mk ((b : R) * c + d * a) (b * d)) $ λ a a' b b' c c' d d' h1 h2, mk_eq_mk_iff.2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((b : R) * c + d * a) * (b' * d') * (t₆ * t₅) = (c * d' * t₆) * (b * b' * t₅) + (a * b' * t₅) * (d * d' * t₆) : by ring ... = (b' * c' + d' * a') * (b * d) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end instance : has_add (localization M) := ⟨localization.add⟩ lemma add_mk (a b c d) : (mk a b : localization M) + mk c d = mk (b * c + d * a) (b * d) := by { unfold has_add.add localization.add, apply lift_on₂_mk } lemma add_mk_self (a b c) : (mk a b : localization M) + mk c b = mk (a + c) b := begin rw [add_mk, mk_eq_mk_iff, r_eq_r'], refine (r' M).symm ⟨1, _⟩, simp only [submonoid.coe_one, submonoid.coe_mul], ring end private meta def tac := `[ { intros, simp only [add_mk, localization.mk_mul, ← localization.mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring }] instance : comm_semiring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), npow := localization.npow _, nsmul := (•), nsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_nsmul, mk_zero]), nsmul_succ' := λ n x, localization.induction_on x (λ x, by simp only [smul_mk, succ_nsmul, add_mk_self]), add_assoc := λ m n k, localization.induction_on₃ m n k (by tac), zero_add := λ y, localization.induction_on y (by tac), add_zero := λ y, localization.induction_on y (by tac), add_comm := λ y z, localization.induction_on₂ z y (by tac), left_distrib := λ m n k, localization.induction_on₃ m n k (by tac), right_distrib := λ m n k, localization.induction_on₃ m n k (by tac), .. localization.comm_monoid_with_zero M } /--For any given denominator `b : M`, the map `a ↦ a / b` is an `add_monoid_hom` from `R` to `localization M`-/ @[simps] def mk_add_monoid_hom (b : M) : R →+ localization M := { to_fun := λ a, mk a b, map_zero' := mk_zero _, map_add' := λ x y, (add_mk_self _ _ _).symm } lemma mk_sum {ι : Type*} (f : ι → R) (s : finset ι) (b : M) : mk (∑ i in s, f i) b = ∑ i in s, mk (f i) b := (mk_add_monoid_hom b).map_sum f s lemma mk_list_sum (l : list R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_list_sum l lemma mk_multiset_sum (l : multiset R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_multiset_sum l instance {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] : distrib_mul_action S (localization M) := { smul_zero := λ s, by simp only [←localization.mk_zero 1, localization.smul_mk, smul_zero], smul_add := λ s x y, localization.induction_on₂ x y $ prod.rec $ by exact λ r₁ x₁, prod.rec $ by exact λ r₂ x₂, by simp only [localization.smul_mk, localization.add_mk, smul_add, mul_comm _ (s • _), mul_comm _ r₁, mul_comm _ r₂, smul_mul_assoc] } instance {S : Type*} [semiring S] [mul_semiring_action S R] [is_scalar_tower S R R] : mul_semiring_action S (localization M) := { ..localization.mul_distrib_mul_action } instance {S : Type*} [semiring S] [module S R] [is_scalar_tower S R R] : module S (localization M) := { zero_smul := localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, zero_smul, mk_zero] }, add_smul := λ s₁ s₂, localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, add_smul, add_mk_self] }, ..localization.distrib_mul_action } instance {S : Type*} [comm_semiring S] [algebra S R] : algebra S (localization M) := { to_ring_hom := ring_hom.comp { to_fun := (monoid_of M).to_map, map_zero' := by rw [← mk_zero (1 : M), mk_one_eq_monoid_of_mk], map_add' := λ x y, by simp only [← mk_one_eq_monoid_of_mk, add_mk, submonoid.coe_one, one_mul, add_comm], .. localization.monoid_of M } (algebra_map S R), smul_def' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, algebra.smul_def], end, commutes' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, mul_one, algebra.commutes], end } instance : is_localization M (localization M) := { map_units := (localization.monoid_of M).map_units, surj := (localization.monoid_of M).surj, eq_iff_exists := λ _ _, (localization.monoid_of M).eq_iff_exists } end @[simp] lemma to_localization_map_eq_monoid_of : to_localization_map M (localization M) = monoid_of M := rfl lemma monoid_of_eq_algebra_map (x) : (monoid_of M).to_map x = algebra_map R (localization M) x := rfl lemma mk_one_eq_algebra_map (x) : mk x 1 = algebra_map R (localization M) x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = is_localization.mk' (localization M) x y := by rw [mk_eq_monoid_of_mk'_apply, mk', to_localization_map_eq_monoid_of] @[simp] lemma mk_eq_mk' : (mk : R → M → localization M) = is_localization.mk' (localization M) := mk_eq_monoid_of_mk' lemma mk_algebra_map {A : Type*} [comm_semiring A] [algebra A R] (m : A) : mk (algebra_map A R m) 1 = algebra_map A (localization M) m := by rw [mk_eq_mk', mk'_eq_iff_eq_mul, submonoid.coe_one, map_one, mul_one]; refl lemma mk_nat_cast (m : ℕ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℕ _ _ m variables [is_localization M S] section variables (M S) /-- The localization of `R` at `M` as a quotient type is isomorphic to any other localization. -/ @[simps] noncomputable def alg_equiv : localization M ≃ₐ[R] S := is_localization.alg_equiv M _ _ /-- The localization of a singleton is a singleton. Cannot be an instance due to metavariables. -/ noncomputable def _root_.is_localization.unique (R Rₘ) [comm_semiring R] [comm_semiring Rₘ] (M : submonoid R) [subsingleton R] [algebra R Rₘ] [is_localization M Rₘ] : unique Rₘ := have inhabited Rₘ := ⟨1⟩, by exactI (alg_equiv M Rₘ).symm.injective.unique end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S (mk' (localization M) x y) = mk' S x y := alg_equiv_mk' _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk' (localization M) x y := alg_equiv_symm_mk' _ _ lemma alg_equiv_mk (x y) : alg_equiv M S (mk x y) = mk' S x y := by rw [mk_eq_mk', alg_equiv_mk'] lemma alg_equiv_symm_mk (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk x y := by rw [mk_eq_mk', alg_equiv_symm_mk'] end localization end comm_semiring section comm_ring variables {R : Type*} [comm_ring R] {M : submonoid R} (S : Type*) [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] namespace localization /-- Negation in a ring localization is defined as `-⟨a, b⟩ = ⟨-a, b⟩`. -/ @[irreducible] protected def neg (z : localization M) : localization M := localization.lift_on z (λ a b, mk (-a) b) $ λ a b c d h, mk_eq_mk_iff.2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul, neg_mul, ht], ring_nf, end instance : has_neg (localization M) := ⟨localization.neg⟩ lemma neg_mk (a b) : -(mk a b : localization M) = mk (-a) b := by { unfold has_neg.neg localization.neg, apply lift_on_mk } instance : comm_ring (localization M) := { zsmul := (•), zsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_zsmul, mk_zero]), zsmul_succ' := λ n x, localization.induction_on x (λ x, by simp [smul_mk, add_mk_self, -mk_eq_monoid_of_mk', add_comm (n : ℤ) 1, add_smul]), zsmul_neg' := λ n x, localization.induction_on x (λ x, by { rw [smul_mk, smul_mk, neg_mk, ← neg_smul], refl }), neg := has_neg.neg, sub := λ x y, x + -y, sub_eq_add_neg := λ x y, rfl, add_left_neg := λ y, by exact localization.induction_on y begin intros, simp only [add_mk, localization.mk_mul, neg_mk, ← mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring end, .. localization.comm_semiring } lemma sub_mk (a c) (b d) : (mk a b : localization M) - mk c d = mk (d * a - b * c) (b * d) := calc mk a b - mk c d = mk a b + (- mk c d) : sub_eq_add_neg _ _ ... = mk a b + (mk (-c) d) : by rw neg_mk ... = mk (b * (-c) + d * a) (b * d) : add_mk _ _ _ _ ... = mk (d * a - b * c) (b * d) : by congr'; ring lemma mk_int_cast (m : ℤ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℤ _ _ m end localization namespace is_localization variables {R M} (S) {K : Type*} [is_localization M S] lemma to_map_eq_zero_iff {x : R} (hM : M ≤ non_zero_divisors R) : algebra_map R S x = 0 ↔ x = 0 := begin rw ← (algebra_map R S).map_zero, split; intro h, { cases (eq_iff_exists M S).mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end protected lemma injective (hM : M ≤ non_zero_divisors R) : injective (algebra_map R S) := begin rw injective_iff_map_eq_zero (algebra_map R S), intros a ha, rwa to_map_eq_zero_iff S hM at ha end protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] (hM : M ≤ non_zero_divisors R) {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R S x ≠ 0 := show (algebra_map R S).to_monoid_with_zero_hom x ≠ 0, from map_ne_zero_of_mem_non_zero_divisors (algebra_map R S) (is_localization.injective S hM) hx variables {S} lemma sec_snd_ne_zero [nontrivial R] (hM : M ≤ non_zero_divisors R) (x : S) : ((sec M x).snd : R) ≠ 0 := non_zero_divisors.coe_ne_zero ⟨(sec M x).snd.val, hM (sec M x).snd.property⟩ lemma sec_fst_ne_zero [nontrivial R] [no_zero_divisors S] (hM : M ≤ non_zero_divisors R) {x : S} (hx : x ≠ 0) : (sec M x).fst ≠ 0 := begin have hsec := sec_spec M x, intro hfst, rw [hfst, map_zero, mul_eq_zero, _root_.map_eq_zero_iff] at hsec, { exact or.elim hsec hx (sec_snd_ne_zero hM x) }, { exact is_localization.injective S hM } end variables (S M) (Q : Type*) [comm_ring Q] {g : R →+* P} [algebra P Q] /-- Injectivity of a map descends to the map induced on localizations. -/ lemma map_injective_of_injective (hg : function.injective g) [is_localization (M.map g : submonoid P) Q] : function.injective (map Q g M.le_comap_map : S → Q) := begin rw injective_iff_map_eq_zero, intros z hz, obtain ⟨a, b, rfl⟩ := mk'_surjective M z, rw [map_mk', mk'_eq_zero_iff] at hz, obtain ⟨⟨m', hm'⟩, hm⟩ := hz, rw submonoid.mem_map at hm', obtain ⟨n, hn, hnm⟩ := hm', rw [subtype.coe_mk, ← hnm, ← map_mul, ← map_zero g] at hm, rw [mk'_eq_zero_iff], exact ⟨⟨n, hn⟩, hg hm⟩, end variables {S Q M} variables (A : Type*) [comm_ring A] [is_domain A] /-- A `comm_ring` `S` which is the localization of a ring `R` without zero divisors at a subset of non-zero elements does not have zero divisors. See note [reducible non-instances]. -/ @[reducible] theorem no_zero_divisors_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S] (hM : M ≤ non_zero_divisors A) : no_zero_divisors S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases surj M z with x hx, cases surj M w with y hy, have : z * w * algebra_map A S y.2 * algebra_map A S x.2 = algebra_map A S x.1 * algebra_map A S y.1, by rw [mul_assoc z, hy, ←hx]; ring, rw [h, zero_mul, zero_mul, ← (algebra_map A S).map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff S hM).mp this.symm) with H H, { exact or.inl (eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (eq_zero_of_fst_eq_zero hy H) }, end } /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S] (hM : M ≤ non_zero_divisors A) : is_domain S := begin apply no_zero_divisors.to_is_domain _, { exact ⟨⟨(algebra_map A S) 0, (algebra_map A S) 1, λ h, zero_ne_one (is_localization.injective S hM h)⟩⟩ }, { exact no_zero_divisors_of_le_non_zero_divisors _ hM } end variables {A} /-- The localization at of an integral domain to a set of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : is_domain (localization M) := is_domain_of_le_non_zero_divisors _ hM end is_localization open is_localization /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma is_field.localization_map_bijective {R Rₘ : Type*} [comm_ring R] [comm_ring Rₘ] {M : submonoid R} (hM : (0 : R) ∉ M) (hR : is_field R) [algebra R Rₘ] [is_localization M Rₘ] : function.bijective (algebra_map R Rₘ) := begin letI := hR.to_field, replace hM := le_non_zero_divisors_of_no_zero_divisors hM, refine ⟨is_localization.injective _ hM, λ x, _⟩, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M x, obtain ⟨n, hn⟩ := hR.mul_inv_cancel (non_zero_divisors.ne_zero $ hM hm), exact ⟨r * n, by erw [eq_mk'_iff_mul_eq, ←map_mul, mul_assoc, mul_comm n, hn, mul_one]⟩ end /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma field.localization_map_bijective {K Kₘ : Type*} [field K] [comm_ring Kₘ] {M : submonoid K} (hM : (0 : K) ∉ M) [algebra K Kₘ] [is_localization M Kₘ] : function.bijective (algebra_map K Kₘ) := (field.to_is_field K).localization_map_bijective hM -- this looks weird due to the `letI` inside the above lemma, but trying to do it the other -- way round causes issues with defeq of instances, so this is actually easier. section algebra variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] variables [algebra R Rₘ] [is_localization M Rₘ] variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ] section variables (S M) /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps -/ noncomputable def localization_algebra : algebra Rₘ Sₘ := (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* Sₘ).to_algebra end lemma algebra_map_mk' (r : R) (m : M) : (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) (mk' Rₘ r m) = mk' Sₘ (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ := map_mk' _ _ _ variables (Rₘ Sₘ) /-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization. -/ lemma localization_algebra_injective (hRS : function.injective (algebra_map R S)) : function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) := is_localization.map_injective_of_injective M Rₘ Sₘ hRS end algebra end comm_ring
77788110416b71f8d6ad1ad6b165a25570986ea3
3f1a1d97c03bb24b55a1b9969bb4b3c619491d5a
/library/init/meta/coinductive_predicates.lean
2d731813cccc34066318d9f3ddfcc9e14c0d6978
[ "Apache-2.0" ]
permissive
praveenmunagapati/lean
00c3b4496cef8e758396005013b9776bb82c4f56
fc760f57d20e0a486d14bc8a08d89147b60f530c
refs/heads/master
1,630,692,342,183
1,515,626,222,000
1,515,626,222,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,250
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 (CMU) -/ prelude import init.meta.expr init.meta.tactic init.meta.constructor_tactic init.meta.attribute import init.meta.interactive namespace name def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace expr open expr meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none meta def local_binder_info : expr → binder_info | (local_const x n bi t) := bi | e := binder_info.default meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] end expr namespace tactic open level expr tactic meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ const n $ ls.map param meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) meta def elim_gen_prod : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h, h'], _)] ← induction e [], elim_gen_prod n h' (hs ++ [h]) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] end tactic section universe u @[user_attribute] meta def monotonicity : user_attribute := { name := `monotonicity, descr := "Monotonicity rules for predicates" } lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := assume h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := assume h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, eapplyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← whnf p, (expr.pi qn qbi qd qb) ← whnf q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, eapply ((const `monotonicity.pi [u] : expr) pd p' q'), skip) <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, eapply ((const `monotonicity.imp []: expr) pd p' qd q'), skip))) <|> first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip), all_goals mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ private meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← mk_local_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← mk_local_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binder_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all}, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m.2), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, econstructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h) ← elim_gen_prod pds.length h [], (hs, h) ← elim_gen_prod pds.length h [], eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do eapply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, eapply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ eapply (pd.destruct.app_of_list ps) >> skip)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, eapply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, eapply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [], if n_eqs > 0 then do (eqs, eq') ← elim_gen_prod (n_eqs - 1) h [], (eqs ++ [eq']).mmap' subst else skip, eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs), iterate assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, eapply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework open lean.parser open interactive @[user_command] meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do decl ← inductive_decl.parse meta_info, add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros), decl.decls.mmap' $ λ d, do { get_env >>= λ env, set_env $ env.add_namespace d.name, meta_info.attrs.apply d.name, d.attrs.apply d.name, some doc_string ← pure meta_info.doc_string | skip, add_doc_string d.name doc_string } /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules (i.e. only a since C -/ meta def coinduction (rule : expr) : tactic unit := focus1 $ do ctxts' ← intros, -- TODO: why do we need to fix the type here? ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binder_info <$> infer_type v), mvars ← apply_core rule {approx := ff, new_goals := new_goals.all}, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v.2 ≠ g), tgt ← target, (is, ty) ← mk_local_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m.2)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars), rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, iterate (econstructor >> skip)), -- clean up remaining coinduction steps all_goals (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [], (match eqs with | [] := clear h | (e::eqs) := do (hs, h) ← elim_gen_prod eqs.length h [], (h::(hs.reverse)).mmap' subst end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule, skip end interactive end tactic
6e2bb397a2c169f245397f52bdbf0f60cabbe237
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/uniform_space/pi.lean
7b0bedb535794c345cb7f00fc58ef46ab8fb93a5
[ "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
1,910
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 variable {α} lemma uniform_continuous_pi {β : Type*} [uniform_space β] {f : β → Π i, α i} : uniform_continuous f ↔ ∀ i, uniform_continuous (λ x, f x i) := by simp only [uniform_continuous, Pi.uniformity, tendsto_infi, tendsto_comap_iff] variable (α) lemma Pi.uniform_continuous_proj (i : ι) : uniform_continuous (λ (a : Π (i : ι), α i), a i) := uniform_continuous_pi.1 uniform_continuous_id i 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, rwa [nhds_pi, le_pi], 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
3760198b173fd0a311725d50a18ee7966d027a87
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/congr_tactic.lean
340317e2899eeebf226026d75f68aca1d4de78fc
[ "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
1,222
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam -/ prelude import init.meta.tactic init.meta.congr_lemma init.meta.relation_tactics init.function namespace tactic meta def apply_congr_core (clemma : congr_lemma) : tactic unit := do assert `H_congr_lemma clemma.type, exact clemma.proof, get_local `H_congr_lemma >>= apply, all_goals' $ do try (applyc `heq_of_eq), get_local `H_congr_lemma >>= clear meta def apply_eq_congr_core (tgt : expr) : tactic unit := do (lhs, rhs) ← match_eq tgt, guard lhs.is_app, clemma ← mk_specialized_congr_lemma lhs, apply_congr_core clemma meta def apply_heq_congr_core : tactic unit := do try (applyc `eq_of_heq), (α, lhs, β, rhs) ← target >>= match_heq, guard lhs.is_app, clemma ← mk_hcongr_lemma lhs.get_app_fn lhs.get_app_num_args, apply_congr_core clemma meta def congr_core : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core <|> fail "congr tactic failed" meta def congr : tactic unit := do focus1 (try assumption >> congr_core >> all_goals' (try reflexivity >> try congr)) end tactic
82ad24a6379b3b43a908ea4343c4049ca5ba03ee
c777c32c8e484e195053731103c5e52af26a25d1
/src/category_theory/preadditive/biproducts.lean
b6f15e50a9d78437925ee1f9a72b60cc628e2bdc
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
46,175
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.group.ext import category_theory.limits.shapes.biproducts import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.preserves.shapes.biproducts import category_theory.limits.preserves.shapes.products import category_theory.preadditive.basic import tactic.abel /-! # Basic facts about biproducts in preadditive categories. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In (or between) preadditive categories, * Any biproduct satisfies the equality `total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)`, or, in the binary case, `total : fst ≫ inl + snd ≫ inr = 𝟙 X`. * Any (binary) `product` or (binary) `coproduct` is a (binary) `biproduct`. * In any category (with zero morphisms), if `biprod.map f g` is an isomorphism, then both `f` and `g` are isomorphisms. * If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. * As a corollary of the previous two facts, if we have an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, we can construct an isomorphism `X₂ ≅ Y₂`. * If `f : W ⊞ X ⟶ Y ⊞ Z` is an isomorphism, either `𝟙 W = 0`, or at least one of the component maps `W ⟶ Y` and `W ⟶ Z` is nonzero. * If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, then every column (corresponding to a nonzero summand in the domain) has some nonzero matrix entry. * A functor preserves a biproduct if and only if it preserves the corresponding product if and only if it preserves the corresponding coproduct. -/ open category_theory open category_theory.preadditive open category_theory.limits open category_theory.functor open category_theory.preadditive open_locale classical open_locale big_operators universes v v' u u' noncomputable theory namespace category_theory variables {C : Type u} [category.{v} C] [preadditive C] namespace limits variables {J : Type} [fintype J] /-- In a preadditive category, we can construct a biproduct for `f : J → C` from any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ def is_bilimit_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) : b.is_bilimit := { is_limit := { lift := λ s, ∑ (j : J), s.π.app ⟨j⟩ ≫ b.ι j, uniq' := λ s m h, begin erw [←category.comp_id m, ←total, comp_sum], apply finset.sum_congr rfl, intros j m, erw [reassoc_of (h ⟨j⟩)], end, fac' := λ s j, begin cases j, simp only [sum_comp, category.assoc, bicone.to_cone_π_app, b.ι_π, comp_dite], -- See note [dsimp, simp]. dsimp, simp, end }, is_colimit := { desc := λ s, ∑ (j : J), b.π j ≫ s.ι.app ⟨j⟩, uniq' := λ s m h, begin erw [←category.id_comp m, ←total, sum_comp], apply finset.sum_congr rfl, intros j m, erw [category.assoc, h ⟨j⟩], end, fac' := λ s j, begin cases j, simp only [comp_sum, ←category.assoc, bicone.to_cocone_ι_app, b.ι_π, dite_comp], dsimp, simp, end } } lemma is_bilimit.total {f : J → C} {b : bicone f} (i : b.is_bilimit) : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X := i.is_limit.hom_ext (λ j, by { cases j, simp [sum_comp, b.ι_π, comp_dite] }) /-- In a preadditive category, we can construct a biproduct for `f : J → C` from any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_biproduct_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) : has_biproduct f := has_biproduct.mk { bicone := b, is_bilimit := is_bilimit_of_total b total } /-- In a preadditive category, any finite bicone which is a limit cone is in fact a bilimit bicone. -/ def is_bilimit_of_is_limit {f : J → C} (t : bicone f) (ht : is_limit t.to_cone) : t.is_bilimit := is_bilimit_of_total _ $ ht.hom_ext $ λ j, by { cases j, simp [sum_comp, t.ι_π, dite_comp, comp_dite] } /-- We can turn any limit cone over a pair into a bilimit bicone. -/ def bicone_is_bilimit_of_limit_cone_of_is_limit {f : J → C} {t : cone (discrete.functor f)} (ht : is_limit t) : (bicone.of_limit_cone ht).is_bilimit := is_bilimit_of_is_limit _ $ is_limit.of_iso_limit ht $ cones.ext (iso.refl _) (by { rintro ⟨j⟩, tidy }) /-- In a preadditive category, if the product over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_product {J : Type} [finite J] (f : J → C) [has_product f] : has_biproduct f := by casesI nonempty_fintype J; exact has_biproduct.mk { bicone := _, is_bilimit := bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) } /-- In a preadditive category, any finite bicone which is a colimit cocone is in fact a bilimit bicone. -/ def is_bilimit_of_is_colimit {f : J → C} (t : bicone f) (ht : is_colimit t.to_cocone) : t.is_bilimit := is_bilimit_of_total _ $ ht.hom_ext $ λ j, begin cases j, simp_rw [bicone.to_cocone_ι_app, comp_sum, ← category.assoc, t.ι_π, dite_comp], tidy end /-- We can turn any limit cone over a pair into a bilimit bicone. -/ def bicone_is_bilimit_of_colimit_cocone_of_is_colimit {f : J → C} {t : cocone (discrete.functor f)} (ht : is_colimit t) : (bicone.of_colimit_cocone ht).is_bilimit := is_bilimit_of_is_colimit _ $ is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) (by { rintro ⟨j⟩, tidy }) /-- In a preadditive category, if the coproduct over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_coproduct {J : Type} [finite J] (f : J → C) [has_coproduct f] : has_biproduct f := by casesI nonempty_fintype J; exact has_biproduct.mk { bicone := _, is_bilimit := bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) } /-- A preadditive category with finite products has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_products [has_finite_products C] : has_finite_biproducts C := ⟨λ n, { has_biproduct := λ F, has_biproduct.of_has_product _ }⟩ /-- A preadditive category with finite coproducts has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_coproducts [has_finite_coproducts C] : has_finite_biproducts C := ⟨λ n, { has_biproduct := λ F, has_biproduct.of_has_coproduct _ }⟩ section variables {f : J → C} [has_biproduct f] /-- In any preadditive category, any biproduct satsifies `∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` -/ @[simp] lemma biproduct.total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f) := is_bilimit.total (biproduct.is_bilimit _) lemma biproduct.lift_eq {T : C} {g : Π j, T ⟶ f j} : biproduct.lift g = ∑ j, g j ≫ biproduct.ι f j := begin ext j, simp only [sum_comp, biproduct.ι_π, comp_dite, biproduct.lift_π, category.assoc, comp_zero, finset.sum_dite_eq', finset.mem_univ, eq_to_hom_refl, category.comp_id, if_true], end lemma biproduct.desc_eq {T : C} {g : Π j, f j ⟶ T} : biproduct.desc g = ∑ j, biproduct.π f j ≫ g j := begin ext j, simp [comp_sum, biproduct.ι_π_assoc, dite_comp], end @[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : Π j, T ⟶ f j} {h : Π j, f j ⟶ U} : biproduct.lift g ≫ biproduct.desc h = ∑ j : J, g j ≫ h j := by simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.ι_π_assoc, comp_dite, dite_comp] lemma biproduct.map_eq [has_finite_biproducts C] {f g : J → C} {h : Π j, f j ⟶ g j} : biproduct.map h = ∑ j : J, biproduct.π f j ≫ h j ≫ biproduct.ι g j := begin ext, simp [biproduct.ι_π, biproduct.ι_π_assoc, comp_sum, sum_comp, comp_dite, dite_comp], end @[simp, reassoc] lemma biproduct.matrix_desc {K : Type} [fintype K] [has_finite_biproducts C] {f : J → C} {g : K → C} (m : Π j k, f j ⟶ g k) {P} (x : Π k, g k ⟶ P) : biproduct.matrix m ≫ biproduct.desc x = biproduct.desc (λ j, ∑ k, m j k ≫ x k) := by { ext, simp, } @[simp, reassoc] lemma biproduct.lift_matrix {K : Type} [fintype K] [has_finite_biproducts C] {f : J → C} {g : K → C} {P} (x : Π j, P ⟶ f j) (m : Π j k, f j ⟶ g k) : biproduct.lift x ≫ biproduct.matrix m = biproduct.lift (λ k, ∑ j, x j ≫ m j k) := by { ext, simp, } @[reassoc] lemma biproduct.matrix_map {K : Type} [fintype K] [has_finite_biproducts C] {f : J → C} {g : K → C} {h : K → C} (m : Π j k, f j ⟶ g k) (n : Π k, g k ⟶ h k) : biproduct.matrix m ≫ biproduct.map n = biproduct.matrix (λ j k, m j k ≫ n k) := by { ext, simp, } @[reassoc] lemma biproduct.map_matrix {K : Type} [fintype K] [has_finite_biproducts C] {f : J → C} {g : J → C} {h : K → C} (m : Π k, f k ⟶ g k) (n : Π j k, g j ⟶ h k) : biproduct.map m ≫ biproduct.matrix n = biproduct.matrix (λ j k, m j ≫ n j k) := by { ext, simp, } end /-- Reindex a categorical biproduct via an equivalence of the index types. -/ @[simps] def biproduct.reindex {β γ : Type} [fintype β] [decidable_eq β] [decidable_eq γ] (ε : β ≃ γ) (f : γ → C) [has_biproduct f] [has_biproduct (f ∘ ε)] : (⨁ (f ∘ ε)) ≅ (⨁ f) := { hom := biproduct.desc (λ b, biproduct.ι f (ε b)), inv := biproduct.lift (λ b, biproduct.π f (ε b)), hom_inv_id' := by { ext b b', by_cases h : b = b', { subst h, simp, }, { simp [h], }, }, inv_hom_id' := begin ext g g', by_cases h : g = g'; simp [preadditive.sum_comp, preadditive.comp_sum, biproduct.ι_π, biproduct.ι_π_assoc, comp_dite, equiv.apply_eq_iff_eq_symm_apply, finset.sum_dite_eq' finset.univ (ε.symm g') _, h], end, } /-- In a preadditive category, we can construct a binary biproduct for `X Y : C` from any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ def is_binary_bilimit_of_total {X Y : C} (b : binary_bicone X Y) (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : b.is_bilimit := { is_limit := { lift := λ s, binary_fan.fst s ≫ b.inl + binary_fan.snd s ≫ b.inr, uniq' := λ s m h, by erw [←category.comp_id m, ←total, comp_add, reassoc_of (h ⟨walking_pair.left⟩), reassoc_of (h ⟨walking_pair.right⟩)], fac' := λ s j, by rcases j with ⟨⟨⟩⟩; simp, }, is_colimit := { desc := λ s, b.fst ≫ binary_cofan.inl s + b.snd ≫ binary_cofan.inr s, uniq' := λ s m h, by erw [←category.id_comp m, ←total, add_comp, category.assoc, category.assoc, h ⟨walking_pair.left⟩, h ⟨walking_pair.right⟩], fac' := λ s j, by rcases j with ⟨⟨⟩⟩; simp, } } lemma is_bilimit.binary_total {X Y : C} {b : binary_bicone X Y} (i : b.is_bilimit) : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X := i.is_limit.hom_ext (λ j, by { rcases j with ⟨⟨⟩⟩; simp, }) /-- In a preadditive category, we can construct a binary biproduct for `X Y : C` from any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_binary_biproduct_of_total {X Y : C} (b : binary_bicone X Y) (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := b, is_bilimit := is_binary_bilimit_of_total b total } /-- We can turn any limit cone over a pair into a bicone. -/ @[simps] def binary_bicone.of_limit_cone {X Y : C} {t : cone (pair X Y)} (ht : is_limit t) : binary_bicone X Y := { X := t.X, fst := t.π.app ⟨walking_pair.left⟩, snd := t.π.app ⟨walking_pair.right⟩, inl := ht.lift (binary_fan.mk (𝟙 X) 0), inr := ht.lift (binary_fan.mk 0 (𝟙 Y)) } lemma inl_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) : t.inl = ht.lift (binary_fan.mk (𝟙 X) 0) := by apply ht.uniq (binary_fan.mk (𝟙 X) 0); rintro ⟨⟨⟩⟩; dsimp; simp lemma inr_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) : t.inr = ht.lift (binary_fan.mk 0 (𝟙 Y)) := by apply ht.uniq (binary_fan.mk 0 (𝟙 Y)); rintro ⟨⟨⟩⟩; dsimp; simp /-- In a preadditive category, any binary bicone which is a limit cone is in fact a bilimit bicone. -/ def is_binary_bilimit_of_is_limit {X Y : C} (t : binary_bicone X Y) (ht : is_limit t.to_cone) : t.is_bilimit := is_binary_bilimit_of_total _ (by refine binary_fan.is_limit.hom_ext ht _ _; simp) /-- We can turn any limit cone over a pair into a bilimit bicone. -/ def binary_bicone_is_bilimit_of_limit_cone_of_is_limit {X Y : C} {t : cone (pair X Y)} (ht : is_limit t) : (binary_bicone.of_limit_cone ht).is_bilimit := is_binary_bilimit_of_total _ $ binary_fan.is_limit.hom_ext ht (by simp) (by simp) /-- In a preadditive category, if the product of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_product (X Y : C) [has_binary_product X Y] : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := _, is_bilimit := binary_bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) } /-- In a preadditive category, if all binary products exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_products [has_binary_products C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_product X Y, } /-- We can turn any colimit cocone over a pair into a bicone. -/ @[simps] def binary_bicone.of_colimit_cocone {X Y : C} {t : cocone (pair X Y)} (ht : is_colimit t) : binary_bicone X Y := { X := t.X, fst := ht.desc (binary_cofan.mk (𝟙 X) 0), snd := ht.desc (binary_cofan.mk 0 (𝟙 Y)), inl := t.ι.app ⟨walking_pair.left⟩, inr := t.ι.app ⟨walking_pair.right⟩ } lemma fst_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) : t.fst = ht.desc (binary_cofan.mk (𝟙 X) 0) := begin apply ht.uniq (binary_cofan.mk (𝟙 X) 0), rintro ⟨⟨⟩⟩; dsimp; simp end lemma snd_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) : t.snd = ht.desc (binary_cofan.mk 0 (𝟙 Y)) := begin apply ht.uniq (binary_cofan.mk 0 (𝟙 Y)), rintro ⟨⟨⟩⟩; dsimp; simp end /-- In a preadditive category, any binary bicone which is a colimit cocone is in fact a bilimit bicone. -/ def is_binary_bilimit_of_is_colimit {X Y : C} (t : binary_bicone X Y) (ht : is_colimit t.to_cocone) : t.is_bilimit := is_binary_bilimit_of_total _ begin refine binary_cofan.is_colimit.hom_ext ht _ _; simp, { rw [category.comp_id t.inl] }, { rw [category.comp_id t.inr] } end /-- We can turn any colimit cocone over a pair into a bilimit bicone. -/ def binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit {X Y : C} {t : cocone (pair X Y)} (ht : is_colimit t) : (binary_bicone.of_colimit_cocone ht).is_bilimit := is_binary_bilimit_of_is_colimit (binary_bicone.of_colimit_cocone ht) $ is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) $ λ j, by { rcases j with ⟨⟨⟩⟩, tidy } /-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_coproduct (X Y : C) [has_binary_coproduct X Y] : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := _, is_bilimit := binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) } /-- In a preadditive category, if all binary coproducts exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_coproducts [has_binary_coproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_coproduct X Y, } section variables {X Y : C} [has_binary_biproduct X Y] /-- In any preadditive category, any binary biproduct satsifies `biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y)`. -/ @[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) := begin ext; simp [add_comp], end lemma biprod.lift_eq {T : C} {f : T ⟶ X} {g : T ⟶ Y} : biprod.lift f g = f ≫ biprod.inl + g ≫ biprod.inr := begin ext; simp [add_comp], end lemma biprod.desc_eq {T : C} {f : X ⟶ T} {g : Y ⟶ T} : biprod.desc f g = biprod.fst ≫ f + biprod.snd ≫ g := begin ext; simp [add_comp], end @[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} : biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i := by simp [biprod.lift_eq, biprod.desc_eq] lemma biprod.map_eq [has_binary_biproducts C] {W X Y Z : C} {f : W ⟶ Y} {g : X ⟶ Z} : biprod.map f g = biprod.fst ≫ f ≫ biprod.inl + biprod.snd ≫ g ≫ biprod.inr := by apply biprod.hom_ext; apply biprod.hom_ext'; simp /-- Every split mono `f` with a cokernel induces a binary bicone with `f` as its `inl` and the cokernel map as its `snd`. We will show in `is_bilimit_binary_bicone_of_split_mono_of_cokernel` that this binary bicone is in fact already a biproduct. -/ @[simps] def binary_bicone_of_is_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [is_split_mono f] {c : cokernel_cofork f} (i : is_colimit c) : binary_bicone X c.X := { X := Y, fst := retraction f, snd := c.π, inl := f, inr := let c' : cokernel_cofork (𝟙 Y - (𝟙 Y - retraction f ≫ f)) := cokernel_cofork.of_π (cofork.π c) (by simp) in let i' : is_colimit c' := is_cokernel_epi_comp i (retraction f) (by simp) in let i'' := is_colimit_cofork_of_cokernel_cofork i' in (split_epi_of_idempotent_of_is_colimit_cofork C (by simp) i'').section_, inl_fst' := by simp, inl_snd' := by simp, inr_fst' := begin dsimp only, rw [split_epi_of_idempotent_of_is_colimit_cofork_section_, is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc], dsimp only [cokernel_cofork_of_cofork_of_π], letI := epi_of_is_colimit_cofork i, apply zero_of_epi_comp c.π, simp only [sub_comp, comp_sub, category.comp_id, category.assoc, is_split_mono.id, sub_self, cofork.is_colimit.π_desc_assoc, cokernel_cofork.π_of_π, is_split_mono.id_assoc], apply sub_eq_zero_of_eq, apply category.id_comp end, inr_snd' := by apply split_epi.id } /-- The bicone constructed in `binary_bicone_of_split_mono_of_cokernel` is a bilimit. This is a version of the splitting lemma that holds in all preadditive categories. -/ def is_bilimit_binary_bicone_of_is_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [is_split_mono f] {c : cokernel_cofork f} (i : is_colimit c) : (binary_bicone_of_is_split_mono_of_cokernel i).is_bilimit := is_binary_bilimit_of_total _ begin simp only [binary_bicone_of_is_split_mono_of_cokernel_fst, binary_bicone_of_is_split_mono_of_cokernel_inr, binary_bicone_of_is_split_mono_of_cokernel_snd, split_epi_of_idempotent_of_is_colimit_cofork_section_], dsimp only [binary_bicone_of_is_split_mono_of_cokernel_X], rw [is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc], simp only [binary_bicone_of_is_split_mono_of_cokernel_inl, cofork.is_colimit.π_desc, cokernel_cofork_of_cofork_π, cofork.π_of_π, add_sub_cancel'_right] end /-- If `b` is a binary bicone such that `b.inl` is a kernel of `b.snd`, then `b` is a bilimit bicone. -/ def binary_bicone.is_bilimit_of_kernel_inl {X Y : C} (b : binary_bicone X Y) (hb : is_limit b.snd_kernel_fork) : b.is_bilimit := is_binary_bilimit_of_is_limit _ $ binary_fan.is_limit.mk _ (λ T f g, f ≫ b.inl + g ≫ b.inr) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂, begin have h₁' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.fst = 0 := by simpa using sub_eq_zero.2 h₁, have h₂' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.snd = 0 := by simpa using sub_eq_zero.2 h₂, obtain ⟨q : T ⟶ X, hq : q ≫ b.inl = m - (f ≫ b.inl + g ≫ b.inr)⟩ := kernel_fork.is_limit.lift' hb _ h₂', rw [←sub_eq_zero, ←hq, ←category.comp_id q, ←b.inl_fst, ←category.assoc, hq, h₁', zero_comp] end /-- If `b` is a binary bicone such that `b.inr` is a kernel of `b.fst`, then `b` is a bilimit bicone. -/ def binary_bicone.is_bilimit_of_kernel_inr {X Y : C} (b : binary_bicone X Y) (hb : is_limit b.fst_kernel_fork) : b.is_bilimit := is_binary_bilimit_of_is_limit _ $ binary_fan.is_limit.mk _ (λ T f g, f ≫ b.inl + g ≫ b.inr) (λ t f g, by simp) (λ t f g, by simp) $ λ T f g m h₁ h₂, begin have h₁' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.fst = 0 := by simpa using sub_eq_zero.2 h₁, have h₂' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.snd = 0 := by simpa using sub_eq_zero.2 h₂, obtain ⟨q : T ⟶ Y, hq : q ≫ b.inr = m - (f ≫ b.inl + g ≫ b.inr)⟩ := kernel_fork.is_limit.lift' hb _ h₁', rw [←sub_eq_zero, ←hq, ←category.comp_id q, ←b.inr_snd, ←category.assoc, hq, h₂', zero_comp] end /-- If `b` is a binary bicone such that `b.fst` is a cokernel of `b.inr`, then `b` is a bilimit bicone. -/ def binary_bicone.is_bilimit_of_cokernel_fst {X Y : C} (b : binary_bicone X Y) (hb : is_colimit b.inr_cokernel_cofork) : b.is_bilimit := is_binary_bilimit_of_is_colimit _ $ binary_cofan.is_colimit.mk _ (λ T f g, b.fst ≫ f + b.snd ≫ g) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂, begin have h₁' : b.inl ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₁, have h₂' : b.inr ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₂, obtain ⟨q : X ⟶ T, hq : b.fst ≫ q = m - (b.fst ≫ f + b.snd ≫ g)⟩ := cokernel_cofork.is_colimit.desc' hb _ h₂', rw [←sub_eq_zero, ←hq, ←category.id_comp q, ←b.inl_fst, category.assoc, hq, h₁', comp_zero] end /-- If `b` is a binary bicone such that `b.snd` is a cokernel of `b.inl`, then `b` is a bilimit bicone. -/ def binary_bicone.is_bilimit_of_cokernel_snd {X Y : C} (b : binary_bicone X Y) (hb : is_colimit b.inl_cokernel_cofork) : b.is_bilimit := is_binary_bilimit_of_is_colimit _ $ binary_cofan.is_colimit.mk _ (λ T f g, b.fst ≫ f + b.snd ≫ g) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂, begin have h₁' : b.inl ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₁, have h₂' : b.inr ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₂, obtain ⟨q : Y ⟶ T, hq : b.snd ≫ q = m - (b.fst ≫ f + b.snd ≫ g)⟩ := cokernel_cofork.is_colimit.desc' hb _ h₁', rw [←sub_eq_zero, ←hq, ←category.id_comp q, ←b.inr_snd, category.assoc, hq, h₂', comp_zero] end /-- Every split epi `f` with a kernel induces a binary bicone with `f` as its `snd` and the kernel map as its `inl`. We will show in `binary_bicone_of_is_split_mono_of_cokernel` that this binary bicone is in fact already a biproduct. -/ @[simps] def binary_bicone_of_is_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [is_split_epi f] {c : kernel_fork f} (i : is_limit c) : binary_bicone c.X Y := { X := X, fst := let c' : kernel_fork (𝟙 X - (𝟙 X - f ≫ section_ f)) := kernel_fork.of_ι (fork.ι c) (by simp) in let i' : is_limit c' := is_kernel_comp_mono i (section_ f) (by simp) in let i'' := is_limit_fork_of_kernel_fork i' in (split_mono_of_idempotent_of_is_limit_fork C (by simp) i'').retraction, snd := f, inl := c.ι, inr := section_ f, inl_fst' := by apply split_mono.id, inl_snd' := by simp, inr_fst' := begin dsimp only, rw [split_mono_of_idempotent_of_is_limit_fork_retraction, is_limit_fork_of_kernel_fork_lift, is_kernel_comp_mono_lift], dsimp only [kernel_fork_of_fork_ι], letI := mono_of_is_limit_fork i, apply zero_of_comp_mono c.ι, simp only [comp_sub, category.comp_id, category.assoc, sub_self, fork.is_limit.lift_ι, fork.ι_of_ι, is_split_epi.id_assoc] end, inr_snd' := by simp } /-- The bicone constructed in `binary_bicone_of_is_split_epi_of_kernel` is a bilimit. This is a version of the splitting lemma that holds in all preadditive categories. -/ def is_bilimit_binary_bicone_of_is_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [is_split_epi f] {c : kernel_fork f} (i : is_limit c) : (binary_bicone_of_is_split_epi_of_kernel i).is_bilimit := binary_bicone.is_bilimit_of_kernel_inl _ $ i.of_iso_limit $ fork.ext (iso.refl _) (by simp) end section variables {X Y : C} (f g : X ⟶ Y) /-- The existence of binary biproducts implies that there is at most one preadditive structure. -/ lemma biprod.add_eq_lift_id_desc [has_binary_biproduct X X] : f + g = biprod.lift (𝟙 X) (𝟙 X) ≫ biprod.desc f g := by simp /-- The existence of binary biproducts implies that there is at most one preadditive structure. -/ lemma biprod.add_eq_lift_desc_id [has_binary_biproduct Y Y] : f + g = biprod.lift f g ≫ biprod.desc (𝟙 Y) (𝟙 Y) := by simp end end limits open category_theory.limits section local attribute [ext] preadditive /-- The existence of binary biproducts implies that there is at most one preadditive structure. -/ instance subsingleton_preadditive_of_has_binary_biproducts {C : Type u} [category.{v} C] [has_zero_morphisms C] [has_binary_biproducts C] : subsingleton (preadditive C) := subsingleton.intro $ λ a b, begin ext X Y f g, have h₁ := @biprod.add_eq_lift_id_desc _ _ a _ _ f g (by convert (infer_instance : has_binary_biproduct X X)), have h₂ := @biprod.add_eq_lift_id_desc _ _ b _ _ f g (by convert (infer_instance : has_binary_biproduct X X)), refine h₁.trans (eq.trans _ h₂.symm), congr' 2; exact subsingleton.elim _ _ end end section variables [has_binary_biproducts.{v} C] variables {X₁ X₂ Y₁ Y₂ : C} variables (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) /-- The "matrix" morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` with specified components. -/ def biprod.of_components : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂ := biprod.fst ≫ f₁₁ ≫ biprod.inl + biprod.fst ≫ f₁₂ ≫ biprod.inr + biprod.snd ≫ f₂₁ ≫ biprod.inl + biprod.snd ≫ f₂₂ ≫ biprod.inr @[simp] lemma biprod.inl_of_components : biprod.inl ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₁₁ ≫ biprod.inl + f₁₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.inr_of_components : biprod.inr ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₂₁ ≫ biprod.inl + f₂₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.of_components_fst : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.fst = biprod.fst ≫ f₁₁ + biprod.snd ≫ f₂₁ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_snd : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.snd = biprod.fst ≫ f₁₂ + biprod.snd ≫ f₂₂ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_eq (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) : biprod.of_components (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd) = f := begin ext; simp only [category.comp_id, biprod.inr_fst, biprod.inr_snd, biprod.inl_snd, add_zero, zero_add, biprod.inl_of_components, biprod.inr_of_components, eq_self_iff_true, category.assoc, comp_zero, biprod.inl_fst, preadditive.add_comp], end @[simp] lemma biprod.of_components_comp {X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C} (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) (g₁₁ : Y₁ ⟶ Z₁) (g₁₂ : Y₁ ⟶ Z₂) (g₂₁ : Y₂ ⟶ Z₁) (g₂₂ : Y₂ ⟶ Z₂) : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.of_components g₁₁ g₁₂ g₂₁ g₂₂ = biprod.of_components (f₁₁ ≫ g₁₁ + f₁₂ ≫ g₂₁) (f₁₁ ≫ g₁₂ + f₁₂ ≫ g₂₂) (f₂₁ ≫ g₁₁ + f₂₂ ≫ g₂₁) (f₂₁ ≫ g₁₂ + f₂₂ ≫ g₂₂) := begin dsimp [biprod.of_components], apply biprod.hom_ext; apply biprod.hom_ext'; simp only [add_comp, comp_add, add_comp_assoc, add_zero, zero_add, biprod.inl_fst, biprod.inl_snd, biprod.inr_fst, biprod.inr_snd, biprod.inl_fst_assoc, biprod.inl_snd_assoc, biprod.inr_fst_assoc, biprod.inr_snd_assoc, comp_zero, zero_comp, category.comp_id, category.assoc], end /-- The unipotent upper triangular matrix ``` (1 r) (0 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_upper {X₁ X₂ : C} (r : X₁ ⟶ X₂) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) r 0 (𝟙 _), inv := biprod.of_components (𝟙 _) (-r) 0 (𝟙 _), } /-- The unipotent lower triangular matrix ``` (1 0) (r 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_lower {X₁ X₂ : C} (r : X₂ ⟶ X₁) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) 0 r (𝟙 _), inv := biprod.of_components (𝟙 _) 0 (-r) (𝟙 _), } /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. (This is the version of `biprod.gaussian` written in terms of components.) -/ def biprod.gaussian' [is_iso f₁₁] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂) ≫ R.hom = biprod.map f₁₁ g₂₂ := ⟨biprod.unipotent_lower (-(f₂₁ ≫ inv f₁₁)), biprod.unipotent_upper (-(inv f₁₁ ≫ f₁₂)), f₂₂ - f₂₁ ≫ (inv f₁₁) ≫ f₁₂, by ext; simp; abel⟩ /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. -/ def biprod.gaussian (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f ≫ biprod.fst)] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ f ≫ R.hom = biprod.map (biprod.inl ≫ f ≫ biprod.fst) g₂₂ := begin let := biprod.gaussian' (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd), simpa [biprod.of_components_eq], end /-- If `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` via a two-by-two matrix whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim' [is_iso f₁₁] [is_iso (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂)] : X₂ ≅ Y₂ := begin obtain ⟨L, R, g, w⟩ := biprod.gaussian' f₁₁ f₁₂ f₂₁ f₂₂, letI : is_iso (biprod.map f₁₁ g) := by { rw ←w, apply_instance, }, letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f₁₁ g), exact as_iso g, end /-- If `f` is an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim (f : X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f.hom ≫ biprod.fst)] : X₂ ≅ Y₂ := begin letI : is_iso (biprod.of_components (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd)) := by { simp only [biprod.of_components_eq], apply_instance, }, exact biprod.iso_elim' (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd) end lemma biprod.column_nonzero_of_iso {W X Y Z : C} (f : W ⊞ X ⟶ Y ⊞ Z) [is_iso f] : 𝟙 W = 0 ∨ biprod.inl ≫ f ≫ biprod.fst ≠ 0 ∨ biprod.inl ≫ f ≫ biprod.snd ≠ 0 := begin by_contra' h, rcases h with ⟨nz, a₁, a₂⟩, set x := biprod.inl ≫ f ≫ inv f ≫ biprod.fst, have h₁ : x = 𝟙 W, by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biprod.total], conv_lhs { slice 2 3, rw [comp_add], }, simp only [category.assoc], rw [comp_add_assoc, add_comp], conv_lhs { congr, skip, slice 1 3, rw a₂, }, simp only [zero_comp, add_zero], conv_lhs { slice 1 3, rw a₁, }, simp only [zero_comp], }, exact nz (h₁.symm.trans h₀), end end lemma biproduct.column_nonzero_of_iso' {σ τ : Type} [finite τ] {S : σ → C} [has_biproduct S] {T : τ → C} [has_biproduct T] (s : σ) (f : ⨁ S ⟶ ⨁ T) [is_iso f] : (∀ t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t = 0) → 𝟙 (S s) = 0 := begin casesI nonempty_fintype τ, intro z, set x := biproduct.ι S s ≫ f ≫ inv f ≫ biproduct.π S s, have h₁ : x = 𝟙 (S s), by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biproduct.total], simp only [comp_sum_assoc], conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], }, simp, }, exact h₁.symm.trans h₀, end /-- If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, and `s` is a non-trivial summand of the source, then there is some `t` in the target so that the `s, t` matrix entry of `f` is nonzero. -/ def biproduct.column_nonzero_of_iso {σ τ : Type} [fintype τ] {S : σ → C} [has_biproduct S] {T : τ → C} [has_biproduct T] (s : σ) (nz : 𝟙 (S s) ≠ 0) (f : ⨁ S ⟶ ⨁ T) [is_iso f] : trunc (Σ' t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t ≠ 0) := begin classical, apply trunc_sigma_of_exists, have t := biproduct.column_nonzero_of_iso'.{v} s f, by_contradiction h, simp only [not_exists_not] at h, exact nz (t h) end section preadditive variables {D : Type.{u'}} [category.{v'} D] [preadditive.{v'} D] variables (F : C ⥤ D) [preserves_zero_morphisms F] namespace limits section fintype variables {J : Type} [fintype J] local attribute [tidy] tactic.discrete_cases /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite products. -/ def preserves_product_of_preserves_biproduct {f : J → C} [preserves_biproduct f F] : preserves_limit (discrete.functor f) F := { preserves := λ c hc, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv (discrete.comp_nat_iso_discrete _ _) _).symm (is_bilimit_of_preserves F (bicone_is_bilimit_of_limit_cone_of_is_limit hc)).is_limit) $ cones.ext (iso.refl _) (by tidy) } section local attribute [instance] preserves_product_of_preserves_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite products. -/ def preserves_products_of_shape_of_preserves_biproducts_of_shape [preserves_biproducts_of_shape J F] : preserves_limits_of_shape (discrete J) F := { preserves_limit := λ f, preserves_limit_of_iso_diagram _ discrete.nat_iso_functor.symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) finite products preserves finite biproducts. -/ def preserves_biproduct_of_preserves_product {f : J → C} [preserves_limit (discrete.functor f) F] : preserves_biproduct f F := { preserves := λ b hb, is_bilimit_of_is_limit _ $ is_limit.of_iso_limit ((is_limit.postcompose_hom_equiv (discrete.comp_nat_iso_discrete _ _) (F.map_cone b.to_cone)).symm (is_limit_of_preserves F hb.is_limit)) $ cones.ext (iso.refl _) (by tidy) } /-- If the (product-like) biproduct comparison for `F` and `f` is a monomorphism, then `F` preserves the biproduct of `f`. For the converse, see `map_biproduct`. -/ def preserves_biproduct_of_mono_biproduct_comparison {f : J → C} [has_biproduct f] [has_biproduct (F.obj ∘ f)] [mono (biproduct_comparison F f)] : preserves_biproduct f F := begin have : pi_comparison F f = (F.map_iso (biproduct.iso_product f)).inv ≫ biproduct_comparison F f ≫ (biproduct.iso_product _).hom, { ext, convert pi_comparison_comp_π F f j.as; simp [← functor.map_comp] }, haveI : is_iso (biproduct_comparison F f) := is_iso_of_mono_of_is_split_epi _, haveI : is_iso (pi_comparison F f) := by { rw this, apply_instance }, haveI := preserves_product.of_iso_comparison F f, apply preserves_biproduct_of_preserves_product end /-- If the (coproduct-like) biproduct comparison for `F` and `f` is an epimorphism, then `F` preserves the biproduct of `F` and `f`. For the converse, see `map_biproduct`. -/ def preserves_biproduct_of_epi_biproduct_comparison' {f : J → C} [has_biproduct f] [has_biproduct (F.obj ∘ f)] [epi (biproduct_comparison' F f)] : preserves_biproduct f F := begin haveI : epi ((split_epi_biproduct_comparison F f).section_) := by simpa, haveI : is_iso (biproduct_comparison F f) := is_iso.of_epi_section' (split_epi_biproduct_comparison F f), apply preserves_biproduct_of_mono_biproduct_comparison end /-- A functor between preadditive categories that preserves (zero morphisms and) finite products preserves finite biproducts. -/ def preserves_biproducts_of_shape_of_preserves_products_of_shape [preserves_limits_of_shape (discrete J) F] : preserves_biproducts_of_shape J F := { preserves := λ f, preserves_biproduct_of_preserves_product F } /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite coproducts. -/ def preserves_coproduct_of_preserves_biproduct {f : J → C} [preserves_biproduct f F] : preserves_colimit (discrete.functor f) F := { preserves := λ c hc, is_colimit.of_iso_colimit ((is_colimit.precompose_hom_equiv (discrete.comp_nat_iso_discrete _ _) _).symm (is_bilimit_of_preserves F (bicone_is_bilimit_of_colimit_cocone_of_is_colimit hc)).is_colimit) $ cocones.ext (iso.refl _) (by tidy) } section local attribute [instance] preserves_coproduct_of_preserves_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite coproducts. -/ def preserves_coproducts_of_shape_of_preserves_biproducts_of_shape [preserves_biproducts_of_shape J F] : preserves_colimits_of_shape (discrete J) F := { preserves_colimit := λ f, preserves_colimit_of_iso_diagram _ discrete.nat_iso_functor.symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) finite coproducts preserves finite biproducts. -/ def preserves_biproduct_of_preserves_coproduct {f : J → C} [preserves_colimit (discrete.functor f) F] : preserves_biproduct f F := { preserves := λ b hb, is_bilimit_of_is_colimit _ $ is_colimit.of_iso_colimit ((is_colimit.precompose_inv_equiv (discrete.comp_nat_iso_discrete _ _) (F.map_cocone b.to_cocone)).symm (is_colimit_of_preserves F hb.is_colimit)) $ cocones.ext (iso.refl _) (by tidy) } /-- A functor between preadditive categories that preserves (zero morphisms and) finite coproducts preserves finite biproducts. -/ def preserves_biproducts_of_shape_of_preserves_coproducts_of_shape [preserves_colimits_of_shape (discrete J) F] : preserves_biproducts_of_shape J F := { preserves := λ f, preserves_biproduct_of_preserves_coproduct F } end fintype /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary products. -/ def preserves_binary_product_of_preserves_binary_biproduct {X Y : C} [preserves_binary_biproduct X Y F] : preserves_limit (pair X Y) F := { preserves := λ c hc, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv (by exact diagram_iso_pair _) _).symm (is_binary_bilimit_of_preserves F (binary_bicone_is_bilimit_of_limit_cone_of_is_limit hc)).is_limit) $ cones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) } section local attribute [instance] preserves_binary_product_of_preserves_binary_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary products. -/ def preserves_binary_products_of_preserves_binary_biproducts [preserves_binary_biproducts F] : preserves_limits_of_shape (discrete walking_pair) F := { preserves_limit := λ K, preserves_limit_of_iso_diagram _ (diagram_iso_pair _).symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) binary products preserves binary biproducts. -/ def preserves_binary_biproduct_of_preserves_binary_product {X Y : C} [preserves_limit (pair X Y) F] : preserves_binary_biproduct X Y F := { preserves := λ b hb, is_binary_bilimit_of_is_limit _ $ is_limit.of_iso_limit ((is_limit.postcompose_hom_equiv (by exact diagram_iso_pair _) (F.map_cone b.to_cone)).symm (is_limit_of_preserves F hb.is_limit)) $ cones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) } /-- If the (product-like) biproduct comparison for `F`, `X` and `Y` is a monomorphism, then `F` preserves the biproduct of `X` and `Y`. For the converse, see `map_biprod`. -/ def preserves_binary_biproduct_of_mono_biprod_comparison {X Y : C} [has_binary_biproduct X Y] [has_binary_biproduct (F.obj X) (F.obj Y)] [mono (biprod_comparison F X Y)] : preserves_binary_biproduct X Y F := begin have : prod_comparison F X Y = (F.map_iso (biprod.iso_prod X Y)).inv ≫ biprod_comparison F X Y ≫ (biprod.iso_prod _ _).hom := by { ext; simp [← functor.map_comp] }, haveI : is_iso (biprod_comparison F X Y) := is_iso_of_mono_of_is_split_epi _, haveI : is_iso (prod_comparison F X Y) := by { rw this, apply_instance }, haveI := preserves_limit_pair.of_iso_prod_comparison F X Y, apply preserves_binary_biproduct_of_preserves_binary_product end /-- If the (coproduct-like) biproduct comparison for `F`, `X` and `Y` is an epimorphism, then `F` preserves the biproduct of `X` and `Y`. For the converse, see `map_biprod`. -/ def preserves_binary_biproduct_of_epi_biprod_comparison' {X Y : C} [has_binary_biproduct X Y] [has_binary_biproduct (F.obj X) (F.obj Y)] [epi (biprod_comparison' F X Y)] : preserves_binary_biproduct X Y F := begin haveI : epi ((split_epi_biprod_comparison F X Y).section_) := by simpa, haveI : is_iso (biprod_comparison F X Y) := is_iso.of_epi_section' (split_epi_biprod_comparison F X Y), apply preserves_binary_biproduct_of_mono_biprod_comparison end /-- A functor between preadditive categories that preserves (zero morphisms and) binary products preserves binary biproducts. -/ def preserves_binary_biproducts_of_preserves_binary_products [preserves_limits_of_shape (discrete walking_pair) F] : preserves_binary_biproducts F := { preserves := λ X Y, preserves_binary_biproduct_of_preserves_binary_product F } /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary coproducts. -/ def preserves_binary_coproduct_of_preserves_binary_biproduct {X Y : C} [preserves_binary_biproduct X Y F] : preserves_colimit (pair X Y) F := { preserves := λ c hc, is_colimit.of_iso_colimit ((is_colimit.precompose_hom_equiv (by exact diagram_iso_pair _) _).symm (is_binary_bilimit_of_preserves F (binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit hc)).is_colimit) $ cocones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) } section local attribute [instance] preserves_binary_coproduct_of_preserves_binary_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary coproducts. -/ def preserves_binary_coproducts_of_preserves_binary_biproducts [preserves_binary_biproducts F] : preserves_colimits_of_shape (discrete walking_pair) F := { preserves_colimit := λ K, preserves_colimit_of_iso_diagram _ (diagram_iso_pair _).symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) binary coproducts preserves binary biproducts. -/ def preserves_binary_biproduct_of_preserves_binary_coproduct {X Y : C} [preserves_colimit (pair X Y) F] : preserves_binary_biproduct X Y F := { preserves := λ b hb, is_binary_bilimit_of_is_colimit _ $ is_colimit.of_iso_colimit ((is_colimit.precompose_inv_equiv (by exact diagram_iso_pair _) (F.map_cocone b.to_cocone)).symm (is_colimit_of_preserves F hb.is_colimit)) $ cocones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) } /-- A functor between preadditive categories that preserves (zero morphisms and) binary coproducts preserves binary biproducts. -/ def preserves_binary_biproducts_of_preserves_binary_coproducts [preserves_colimits_of_shape (discrete walking_pair) F] : preserves_binary_biproducts F := { preserves := λ X Y, preserves_binary_biproduct_of_preserves_binary_coproduct F } end limits end preadditive end category_theory
57d7d400d3db01292a68c62a3f7d796105b44ad9
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/finsupp/basic.lean
9346ad0575a094bc939cd432d7937b05093ed16f
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
95,095
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, Scott Morrison -/ import algebra.big_operators.order import algebra.module.pi import group_theory.submonoid.basic import algebra.big_operators.ring import data.finset.preimage import data.indicator_function /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## TODO * This file is currently ~2K lines long, so possibly it should be splitted into smaller chunks; * Add the list of definitions and important lemmas to the module docstring. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## Notation This file defines `α →₀ β` as notation for `finsupp α β`. -/ noncomputable theory open_locale classical big_operators open finset variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance : has_coe_to_fun (α →₀ M) := ⟨λ _, α → M, to_fun⟩ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin change f = g at h, subst h, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end @[simp, norm_cast] lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g := coe_fn_injective.eq_iff @[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, coe_fn_inj] @[ext] lemma ext {f g : α →₀ M} (h : ∀a, f a = g a) : f = g := coe_fn_injective (funext h) lemma ext_iff {f g : α →₀ M} : f = g ↔ (∀a:α, f a = g a) := ⟨by rintros rfl a; refl, ext⟩ lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := by exact_mod_cast @function.support_eq_empty_iff _ _ _ f lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 := by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def] lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 := by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem] lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance finsupp.decidable_eq [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_support (f : α →₀ M) : set.finite (function.support f) := f.fun_support_eq.symm ▸ f.support.finite_to_set lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps apply] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 := by convert rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] lemma single_eq_pi_single : ⇑(single a b) = pi.single a b := single_eq_update @[simp] lemma single_zero : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem /-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `finsupp.single_left_injective` -/ lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end /-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `finsupp.single_injective` -/ lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) := λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff lemma support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := begin have : i ∈ (single i b).support := by simpa using h, intro H, simpa [H] end lemma support_single_disjoint {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : disjoint (single i b).support (single j b').support ↔ i ≠ j := by simpa [support_single_ne_zero, hb, hb'] using ne_comm @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single (default α) x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single (default α) (x (default α)) := ext $ unique.forall_iff.2 single_eq_same.symm lemma unique_ext [unique α] {f g : α →₀ M} (h : f (default α) = g (default α)) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f (default α) = g (default α) := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] end single /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset section of_support_finite variables [has_zero M] /-- The natural `finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def of_support_finite (f : α → M) (hf : (function.support f).finite) : α →₀ M := { support := hf.to_finset, to_fun := f, mem_support_to_fun := λ _, hf.mem_to_finset } lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} : (of_support_finite f hf : α → M) = f := rfl instance : can_lift (α → M) (α →₀ M) := { coe := coe_fn, cond := λ f, (function.support f).finite, prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ } end of_support_finite /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] [has_zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `finsupp.map_range.zero_hom` * `finsupp.map_range.add_monoid_hom` * `finsupp.map_range.add_equiv` * `finsupp.map_range.linear_map` * `finsupp.map_range.linear_equiv` -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] @[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g := ext $ λ _, rfl lemma map_range_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) := ext $ λ _, rfl lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : (α →₀ P) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by rw subsingleton.elim D; exact support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod -- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∑ a in f.support, g a (f a) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } end sum_prod /-! ### Additive monoid structure on `α →₀ M` -/ section add_zero_class variables [add_zero_class M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_zero_class (α →₀ M) := { zero := 0, add := (+), zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero, λ _ _, single_add⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_Union_range_single : add_submonoid.closure (⋃ a : α, set.range (single a : M → α →₀ M)) = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _), simp only [set.mem_Union, set.mem_range] at hf, rcases hf with ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_zero_class N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] end add_zero_class section add_monoid variables [add_monoid M] instance : add_monoid (α →₀ M) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, nsmul := λ n v, v.map_range ((•) n) (nsmul_zero _), nsmul_zero' := λ v, by { ext i, simp }, nsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_nsmul] }, .. finsupp.add_zero_class } end add_monoid end finsupp @[to_additive] lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := h.map_sum _ _ lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp section nat_sub instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩ @[simp] lemma coe_nat_sub (g₁ g₂ : α →₀ ℕ) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma nat_sub_apply (g₁ g₂ : α →₀ ℕ) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma single_nat_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ := begin ext f, by_cases h : (a = f), { rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] }, rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h] end -- These next two lemmas are used in developing -- the partial derivative on `mv_polynomial`. lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, }, { simp [h], } end lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, }, { simp [h], } end @[simp] lemma nat_zero_sub (f : α →₀ ℕ) : 0 - f = 0 := ext $ λ x, nat.zero_sub _ end nat_sub instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := { neg := map_range (has_neg.neg) neg_zero, sub := has_sub.sub, sub_eq_add_neg := λ x y, ext (λ i, sub_eq_add_neg _ _), add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, gsmul := λ n v, v.map_range ((•) n) (gsmul_zero _), gsmul_zero' := λ v, by { ext i, simp }, gsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_gsmul] }, gsmul_neg' := λ n v, by { ext i, simp only [nat.succ_eq_add_one, map_range_apply, gsmul_neg_succ_of_nat, int.coe_nat_succ, neg_inj, add_gsmul, add_nsmul, one_gsmul, gsmul_coe_nat, one_nsmul] }, .. finsupp.add_monoid } instance [add_comm_group G] : add_comm_group (α →₀ G) := { add_comm := add_comm, ..finsupp.add_group } lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group G] {f : α →₀ G} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (apply_add_hom a₂ : (β →₀ N) →+ _).map_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (((monoid_hom.id G)⁻¹).map_prod _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib @[to_additive] lemma prod_add_index [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have hf : f.prod h = ∏ a in f.support ∪ g.support, h a (f a), from f.prod_of_support_subset (subset_union_left _ _) _ $ λ a ha, h_zero a, have hg : g.prod h = ∏ a in f.support ∪ g.support, h a (g a), from g.prod_of_support_subset (subset_union_right _ _) _ $ λ a ha, h_zero a, have hfg : (f + g).prod h = ∏ a in f.support ∪ g.support, h a ((f + g) a), from (f + g).prod_of_support_subset support_add _ $ λ a ha, h_zero a, by simp only [*, add_apply, prod_mul_distrib] @[simp] lemma sum_add_index' [add_comm_monoid M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_add_index' [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs], intros x hx, simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx, obtain ⟨hxi, j, hj, hxj⟩ := hx, have hn : i ≠ j := λ H, hi (H.symm ▸ hj), apply h _ _ hn, simp [hxi, hxj] } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (f.support.sum_hom _).symm lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (f.support.sum_hom multiset.sum).symm section map_range section zero_hom variables [has_zero M] [has_zero N] [has_zero P] /-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism on functions. -/ @[simps] def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero } @[simp] lemma map_range.zero_hom_id : map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) : (map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) = (map_range.zero_hom f).comp (map_range.zero_hom f₂) := zero_hom.ext $ map_range_comp _ _ _ _ _ end zero_hom section add_monoid_hom variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } @[simp] lemma map_range.add_monoid_hom_id : map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext map_range_id lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) : (map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) = (map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) := add_monoid_hom.ext $ map_range_comp _ _ _ _ _ lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _ lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _ /-- `finsupp.map_range.add_monoid_hom` as an equiv. -/ @[simps apply] def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end, ..(map_range.add_monoid_hom f.to_add_monoid_hom) } @[simp] lemma map_range.add_equiv_refl : map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) := add_equiv.ext map_range_id lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) = (map_range.add_equiv f).trans (map_range.add_equiv f₂) := add_equiv.ext $ map_range_comp _ _ _ _ _ lemma map_range.add_equiv_symm (f : M ≃+ N) : ((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm := add_equiv.ext $ λ x, rfl end add_monoid_hom end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum $ λa, single (f a) lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] } end lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end @[simp] lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end @[simp] lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) @[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : map_domain f x a = x (f.symm a) := begin conv_lhs { rw ←f.apply_symm_apply a }, exact map_domain_apply f.injective _ _, end /-- `finsupp.map_domain` is an `add_monoid_hom`. -/ @[simps] def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) := { to_fun := map_domain f, map_zero' := map_domain_zero, map_add' := λ _ _, map_domain_add} @[simp] lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext $ λ _, map_domain_id lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) : (map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) = (map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) := add_monoid_hom.ext $ λ _, map_domain_comp lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _ lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _ lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $ by rw [finset.bUnion_singleton]; exact subset.refl _ @[to_additive] lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (map_domain f s).prod h = s.prod (λa m, h (f a) m) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) /-- A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`, rather than separate linearity hypotheses. -/ -- Note that in `prod_map_domain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `monoid_hom`. @[simp] lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : (map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) := @sum_map_domain_index _ _ _ _ _ _ _ _ (λ b m, h b m) (λ b, (h b).map_zero) (λ b m₁ m₂, (h b).map_add _ _) lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end @[to_additive] lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain] lemma map_domain_injective {f : α → β} (hf : function.injective f) : function.injective (map_domain f : (α →₀ M) → (β →₀ M)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) : (map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) = (map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) := by { ext, simp } /-- When `g` preserves addition, `map_range` and `map_domain` commute. -/ lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) := let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α →₀ M := { support := l.support.preimage f hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain [has_zero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp only [sum, comap_domain_apply, (∘)], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end comap_domain /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M := { to_fun := λ a, if p a then f a else 0, support := f.support.filter (λ a, p a), mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } } lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 := by rw subsingleton.elim D; refl lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter [D : decidable_pred p] : (f.filter p).support = f.support.filter p := by rw subsingleton.elim D; refl lemma filter_zero : (0 : α →₀ M).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := coe_fn_injective $ by simp [filter_eq_indicator, set.subset_def, mem_support_single, h] @[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 := ext $ by simp [filter_eq_indicator, single_apply_eq_zero, @imp.swap (p _), h] end has_zero lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := coe_fn_injective $ set.indicator_self_add_compl {x | p x} f end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : finset M := finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain section zero variables [has_zero M] {p : α → Prop} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) := ⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} : (subtype_domain p f).support = f.support.subtype p := by rw subsingleton.elim D; refl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 := rfl lemma subtype_domain_eq_zero_iff' {f : α →₀ M} : f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 := by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff] lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) : f.subtype_domain p = 0 ↔ f = 0 := subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x, if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩ @[to_additive] lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section add_zero_class variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M} @[simp] lemma subtype_domain_add {v v' : α →₀ M} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl instance subtype_domain.is_add_monoid_hom : is_add_monoid_hom (subtype_domain p : (α →₀ M) → subtype p →₀ M) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) := { to_fun := filter p, map_zero' := filter_zero p, map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g } @[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filter_add_hom p).map_add v v' end add_zero_class section comm_monoid variables [add_comm_monoid M] {p : α → Prop} lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filter_add_hom p : (α →₀ M) →+ _).map_sum f s lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $ λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end comm_monoid section group variables [add_group G] {p : α → Prop} {v v' : α →₀ G} @[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl @[simp] lemma single_neg {a : α} {b : G} : single a (-b) = -single a b := (single_add_hom a : G →+ _).map_neg b @[simp] lemma single_sub {a : α} {b₁ b₂ : G} : single a (b₁ - b₂) = single a b₁ - single a b₂ := (single_add_hom a : G →+ _).map_sub b₁ b₂ end group end subtype_domain /-! ### Declarations relating `finsupp` to `multiset` -/ section multiset /-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. We define this function as an `add_equiv`. -/ def to_multiset : (α →₀ ℕ) ≃+ multiset α := { to_fun := λ f, f.sum (λa n, n • {a}), inv_fun := λ s, ⟨s.to_finset, λ a, s.count a, λ a, by simp⟩, left_inv := λ f, ext $ λ a, suffices (if f a = 0 then 0 else f a) = f a, by simpa [finsupp.sum, multiset.count_sum', multiset.count_cons], by split_ifs with h; [rw h, refl], right_inv := λ s, by simp [finsupp.sum], map_add' := λ f g, sum_add_index (λ a, zero_nsmul _) (λ a, add_nsmul _) } lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := to_multiset.map_add m n lemma to_multiset_apply (f : α →₀ ℕ) : f.to_multiset = f.sum (λ a n, n • {a}) := rfl @[simp] lemma to_multiset_symm_apply (s : multiset α) (x : α) : finsupp.to_multiset.symm s x = s.count x := rfl @[simp] lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n • {a} := by rw [to_multiset_apply, sum_single_index]; apply zero_nsmul lemma to_multiset_sum {ι : Type*} {f : ι → α →₀ ℕ} (s : finset ι) : finsupp.to_multiset (∑ i in s, f i) = ∑ i in s, finsupp.to_multiset (f i) := add_equiv.map_sum _ _ _ lemma to_multiset_sum_single {ι : Type*} (s : finset ι) (n : ℕ) : finsupp.to_multiset (∑ i in s, single i n) = n • s.val := by simp_rw [to_multiset_sum, finsupp.to_multiset_single, multiset.singleton_eq_singleton, sum_nsmul, sum_multiset_singleton] lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) := by simp [to_multiset_apply, add_monoid_hom.map_finsupp_sum, function.id_def] lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, is_add_monoid_hom.map_nsmul (multiset.map g)], refl } end @[simp] lemma prod_to_multiset [comm_monoid M] (f : M →₀ ℕ) : f.to_multiset.prod = f.prod (λa n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index, finsupp.prod_single_index, multiset.prod_nsmul, multiset.singleton_eq_singleton, multiset.prod_singleton], { exact pow_zero a }, { exact pow_zero }, { exact pow_add } } end @[simp] lemma to_finset_to_multiset [decidable_eq α] (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn, multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero], refl, refine disjoint.mono_left support_single_subset _, rwa [finset.singleton_disjoint] } end @[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (n • {x} : multiset α).count a) : (f.support.sum_hom $ multiset.count a).symm ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_nsmul] ... = f.sum (λx n, n * (x ::ₘ 0 : multiset α).count a) : rfl ... = f a * (a ::ₘ 0 : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] lemma mem_support_multiset_sum [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ @[simp] lemma mem_to_multiset (f : α →₀ ℕ) (i : α) : i ∈ f.to_multiset ↔ i ∈ f.support := by rw [← multiset.count_ne_zero, finsupp.count_to_multiset, finsupp.mem_support_iff] end multiset /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry variables [add_comm_monoid M] [add_comm_monoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) := f.sum $ λp c, single p.1 (single p.2 c) @[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := begin have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0, { rintros ⟨b₁, b₂⟩, simp [single_apply, ite_apply, prod.ext_iff, ite_and], split_ifs; simp [single_apply, *] }, rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl], { intros b hb b_ne, rw [this b, if_neg b_ne] }, { intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] } end lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter (λa:α×β, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [decidable_eq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bUnion_singleton, refine finset.subset.trans support_sum _, refine finset.bUnion_mono (assume a _, support_single_subset) end end curry_uncurry section sum /-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ := on_finset ((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩) (sum.elim f g) (λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa }) @[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl lemma sum_elim_apply {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl lemma sum_elim_inl {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl lemma sum_elim_inr {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] : ((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) := { to_fun := λ f, ⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _), f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩, inv_fun := λ fg, sum_elim fg.1 fg.2, left_inv := λ f, by { ext ab, cases ab with a b; simp }, right_inv := λ fg, by { ext; simp } } lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (x : α) : (sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (y : β) : (sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl variables [add_monoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { map_add' := by { intros, ext; simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply, snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] }, .. sum_finsupp_equiv_prod_finsupp } lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl end sum section variables [group G] [mul_action G α] [add_comm_monoid M] /-- Scalar multiplication by a group element g, given by precomposition with the action of g⁻¹ on the domain. -/ def comap_has_scalar : has_scalar G (α →₀ M) := { smul := λ g f, f.comap_domain (λ a, g⁻¹ • a) (λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) } local attribute [instance] comap_has_scalar /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is multiplicative in g. -/ def comap_mul_action : mul_action G (α →₀ M) := { one_smul := λ f, by { ext, dsimp [(•)], simp, }, mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, } local attribute [instance] comap_mul_action /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is additive in the second argument. -/ def comap_distrib_mul_action : distrib_mul_action G (α →₀ M) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, } /-- Scalar multiplication by a group element on finitely supported functions on a group, given by precomposition with the action of g⁻¹. -/ def comap_distrib_mul_action_self : distrib_mul_action G (G →₀ M) := @finsupp.comap_distrib_mul_action G M G _ (monoid.to_mul_action G) _ @[simp] lemma comap_smul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := begin ext a', dsimp [(•)], by_cases h : g • a = a', { subst h, simp [←mul_smul], }, { simp [single_eq_of_ne h], rw [single_eq_of_ne], rintro rfl, simpa [←mul_smul] using h, } end @[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := rfl end section instance [semiring R] [add_comm_monoid M] [module R M] : has_scalar R (α →₀ M) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ /-! Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] lemma coe_smul {_ : semiring R} [add_comm_monoid M] [module R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl lemma smul_apply {_ : semiring R} [add_comm_monoid M] [module R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl variables (α M) instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, zero_smul := λ x, ext $ λ _, zero_smul _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } instance [semiring R] [semiring S] [add_comm_monoid M] [module R M] [module S M] [has_scalar R S] [is_scalar_tower R S M] : is_scalar_tower R S (α →₀ M) := { smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ } instance [semiring R] [semiring S] [add_comm_monoid M] [module R M] [module S M] [smul_comm_class R S M] : smul_comm_class R S (α →₀ M) := { smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ } variables {α M} {R} lemma support_smul {_ : semiring R} [add_comm_monoid M] [module R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := λ a, by simp only [smul_apply, mem_support_iff, ne.def]; exact mt (λ h, h.symm ▸ smul_zero _) section variables {p : α → Prop} @[simp] lemma filter_smul {_ : semiring R} [add_comm_monoid M] [module R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := coe_fn_injective $ set.indicator_smul {x | p x} b v end lemma map_domain_smul {_ : semiring R} [add_comm_monoid M] [module R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] }, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {_ : semiring R} [add_comm_monoid M] [module R M] (c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) := map_range_single @[simp] lemma smul_single' {_ : semiring R} (c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ lemma map_range_smul {_ : semiring R} [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : map_range f hf (c • v) = c • map_range f hf v := begin erw ←map_range_comp, have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul, simp_rw this, apply map_range_comp, rw [function.comp_apply, smul_zero, hf], end lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b := by rw [smul_single, smul_eq_mul, mul_one] end lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 /-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/ lemma sum_smul_index_add_monoid_hom [semiring R] [add_comm_monoid M] [add_comm_monoid N] [module R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : (b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) := sum_map_range_index (λ i, (h i).map_zero) instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*} [no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) := ⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext (λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩ section variables [semiring R] [semiring S] lemma sum_mul (b : S) (s : α →₀ R) {f : α → R → S} : (s.sum f) * b = s.sum (λ a c, (f a c) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum (b : S) (s : α →₀ R) {f : α → R → S} : b * (s.sum f) = s.sum (λ a c, b * (f a c)) := by simp only [finsupp.sum, finset.mul_sum] instance unique_of_right [subsingleton R] : unique (α →₀ R) := { uniq := λ l, ext $ λ i, subsingleton.elim _ _, .. finsupp.inhabited } end /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] : {f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) := begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. -/ @[simps apply] protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := { to_fun := map_domain e, inv_fun := map_domain e.symm, left_inv := begin assume v, simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply], exact map_domain_id end, right_inv := begin assume v, simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply], exact map_domain_id end, map_add' := λ a b, map_domain_add, } @[simp] lemma dom_congr_refl [add_comm_monoid M] : finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) := add_equiv.ext $ λ _, map_domain_id @[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) : (finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):= add_equiv.ext $ λ _, rfl @[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) : (finsupp.dom_congr e).trans (finsupp.dom_congr f) = (finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) := add_equiv.ext $ λ _, map_domain_comp.symm end finsupp namespace finsupp /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `finsupp` version of `sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] /-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `finsupp` version of `equiv.Pi_curry`. -/ noncomputable def sigma_finsupp_equiv_pi_finsupp : ((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) := { to_fun := split, inv_fun := λ f, on_finset (finset.univ.sigma (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩), left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl /-- On a `fintype η`, `finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_add_equiv_pi_finsupp {α : Type*} {ιs : η → Type*} [add_monoid α] : ((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) := { map_add' := λ f g, by { ext, simp }, .. sigma_finsupp_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply {α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl end sigma end finsupp /-! ### Declarations relating `multiset` to `finsupp` -/ namespace multiset /-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ def to_finsupp : multiset α ≃+ (α →₀ ℕ) := finsupp.to_multiset.symm @[simp] lemma to_finsupp_support [D : decidable_eq α] (s : multiset α) : s.to_finsupp.support = s.to_finset := by rw subsingleton.elim D; refl @[simp] lemma to_finsupp_apply [D : decidable_eq α] (s : multiset α) (a : α) : to_finsupp s a = s.count a := by rw subsingleton.elim D; refl lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := add_equiv.map_zero _ lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := to_finsupp.map_add s t @[simp] lemma to_finsupp_singleton (a : α) : to_finsupp (a ::ₘ 0) = finsupp.single a 1 := finsupp.to_multiset.symm_apply_eq.2 $ by simp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := finsupp.to_multiset.apply_symm_apply s lemma to_finsupp_eq_iff {s : multiset α} {f : α →₀ ℕ} : s.to_finsupp = f ↔ s = f.to_multiset := finsupp.to_multiset.symm_apply_eq end multiset @[simp] lemma finsupp.to_multiset_to_finsupp (f : α →₀ ℕ) : f.to_multiset.to_finsupp = f := finsupp.to_multiset.symm_apply_apply f /-! ### Declarations about order(ed) instances on `finsupp` -/ namespace finsupp instance [preorder M] [has_zero M] : preorder (α →₀ M) := { le := λ f g, ∀ s, f s ≤ g s, le_refl := λ f s, le_refl _, le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) } instance [partial_order M] [has_zero M] : partial_order (α →₀ M) := { le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s), .. finsupp.preorder } instance [ordered_cancel_add_comm_monoid M] : ordered_cancel_add_comm_monoid (α →₀ M) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s), add_left_cancel := λ a b c h, ext $ λ s, add_left_cancel (ext_iff.1 h s), .. finsupp.add_comm_monoid, .. finsupp.partial_order } lemma le_def [preorder M] [has_zero M] {f g : α →₀ M} : f ≤ g ↔ ∀ x, f x ≤ g x := iff.rfl lemma le_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ @[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [ext_iff, forall_and_distrib] /-- `finsupp.to_multiset` as an order isomorphism. -/ def order_iso_multiset : (α →₀ ℕ) ≃o multiset α := { to_equiv := to_multiset.to_equiv, map_rel_iff' := λ f g, by simp [multiset.le_iff_count, le_def] } @[simp] lemma coe_order_iso_multiset : ⇑(@order_iso_multiset α) = to_multiset := rfl @[simp] lemma coe_order_iso_multiset_symm : ⇑(@order_iso_multiset α).symm = multiset.to_finsupp := rfl lemma to_multiset_strict_mono : strict_mono (@to_multiset α) := order_iso_multiset.strict_mono lemma sum_id_lt_of_lt (m n : α →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [← card_to_multiset, ← card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (α) /-- The order on `σ →₀ ℕ` is well-founded.-/ lemma lt_wf : well_founded (@has_lt.lt (α →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf instance decidable_le : decidable_rel (@has_le.le (α →₀ ℕ) _) := λ m n, by rw le_iff; apply_instance variable {α} @[simp] lemma nat_add_sub_cancel (f g : α →₀ ℕ) : f + g - g = f := ext $ λ a, nat.add_sub_cancel _ _ @[simp] lemma nat_add_sub_cancel_left (f g : α →₀ ℕ) : f + g - f = g := ext $ λ a, nat.add_sub_cancel_left _ _ lemma nat_add_sub_of_le {f g : α →₀ ℕ} (h : f ≤ g) : f + (g - f) = g := ext $ λ a, nat.add_sub_of_le (h a) lemma nat_sub_add_cancel {f g : α →₀ ℕ} (h : f ≤ g) : g - f + f = g := ext $ λ a, nat.sub_add_cancel (h a) instance : canonically_ordered_add_monoid (α →₀ ℕ) := { bot := 0, bot_le := λ f s, zero_le (f s), le_iff_exists_add := λ f g, ⟨λ H, ⟨g - f, (nat_add_sub_of_le H).symm⟩, λ ⟨c, hc⟩, hc.symm ▸ λ x, by simp⟩, .. (infer_instance : ordered_add_comm_monoid (α →₀ ℕ)) } end finsupp namespace multiset lemma to_finsuppstrict_mono : strict_mono (@to_finsupp α) := finsupp.order_iso_multiset.symm.strict_mono end multiset
4b8bf32c67638e31a61acfbc839855e35a3a868e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/interactive/1313.lean
6f729d946a5d1b81e50cfd2a0a841804c346d108
[ "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
556
lean
example (p q : Prop) (a : p) (b : q) : p ∧ q ∧ p := begin --^ "command": "info" end example (p q : Prop) (a : p) (b : q) : p ∧ q ∧ p := begin apply and.intro, --^ "command": "info" end example (p q : Prop) (a : p) (b : q) : p ∧ q ∧ p := begin apply and.intro, --^ "command": "info" end example (p q : Prop) (a : p) (b : q) : p ∧ q ∧ p := begin apply and.intro, --^ "command": "info" end example (p q : Prop) (a : p) (b : q) : p ∧ q ∧ p := begin apply and.intro, --^ "command": "info" {exact a}, end
cca05ea957c99c27b15ca6283ae578f46b8f5778
51241b440c9d9e72556bd50c272c2654f722af28
/20170116_POPL/assoc/ac_by_simp.lean
6bfa04d0237ed95d2401153d8dae58f08301d599
[ "Apache-2.0" ]
permissive
jroesch/presentations
deb419a483a788fa6bf3c5b4949e151186e9ea6d
b64fd2bf65a64faf16c52729cde0436f0d2f2cca
refs/heads/master
1,610,543,247,969
1,484,284,236,000
1,484,284,236,000
78,833,725
0
0
null
1,484,298,759,000
1,484,298,759,000
null
UTF-8
Lean
false
false
4,352
lean
import data.set /- The Lean simplifer can be also use to "flat" nested application of associatiave operators, and "sort" associative/commutative ones. The Lean simplifier can be viewed as a ordered rewriting system. It can be customized with user provided lemmas. It is well-known that we can use ordered rewriting to "sort" nested applications of associative-commutative (AC) operators. Let's assume we have an AC operator op. -/ constant α : Type constant op : α → α → α axiom h_comm : ∀ x y, op x y = op y x axiom h_assoc : ∀ x y z, op (op x y) z = op x (op y z) /- To "sort" the nested op-applications, we also need the following lemma that follows from h_comm and h_assoc. -/ lemma h_left_comm : ∀ x y z, op x (op y z) = op y (op x z) := left_comm _ h_comm h_assoc /- Now, we declare notation for (op a b) -/ infix `∙`:65 := op example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) := by simp [h_comm, h_assoc, h_left_comm] /- We can add h_comm, h_assoc and h_left_comm to the main simp_lemmas (set of simplification rules) -/ attribute [simp] h_comm h_assoc h_left_comm /- Now, these lemmas are automatically used. -/ example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) := by simp /- We can also locally remove lemmas from the [simp] -/ local attribute [-simp] h_comm h_assoc h_left_comm example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) := /- Now, the following will fail since h_comm, h_assoc and h_left_comm have been removed from the simp set [simp] -/ by simp /- We can declare our own simp sets. The command mk_simp_attr is implemented in Lean using the attribute manager API. We discuss the attribute manager later. -/ run_command mk_simp_attr `sort_op attribute [sort_op] h_comm h_assoc h_left_comm example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) := /- The modifier 'with' instructs simp to use the given simp set -/ by simp with sort_op open tactic /- Note that (left_comm op h_comm h_assoc) is not recognized as the rewrite rule we expect -/ check left_comm op h_comm h_assoc -- : left_commutative f /- So, we define an auxiliary lemma with the "right" type. -/ lemma {u} left_comm_rw {α : Type u} (f : α → α → α) (h_comm : commutative f) (h_assoc : associative f) : ∀ x y z, f x (f y z) = f y (f x z) := left_comm f h_comm h_assoc /- The simp sets are first-class citizens in Lean, we can write functions that create them. Given proof terms h_comm and h_assoc, the tactic (mk_sort_simp_set h_comm h_assoc) returns a simp set containing h_comm, h_assoc and the associated left_comm lemma implied by h_comm and h_assoc. -/ meta def mk_sort_simp_set (op : expr) (h_comm : expr) (h_assoc : expr) : tactic simp_lemmas := do S ← return simp_lemmas.mk, S ← S^.add h_comm, S ← S^.add h_assoc, h_left_comm ← to_expr `(left_comm_rw %%op %%h_comm %%h_assoc) >>= whnf, S^.add h_left_comm declare_trace sort_ac meta def sort_ac_core (op : expr) (h_comm : expr) (h_assoc : expr) : tactic unit := do S ← mk_sort_simp_set op h_comm h_assoc, /- When tracing sort_ac, we pretty print the generated simp_set. -/ when_tracing `sort_ac (S^.pp >>= trace), simplify_goal S, try reflexivity open expr meta def is_bin_app : expr → tactic (expr × expr × expr) | (app (app fn a1) a2) := return (fn, a1, a2) | _ := failed /- Now, we use type class resolution to retrieve the comm and assoc lemmas. -/ meta def sort_ac : tactic unit := do (lhs, rhs) ← target >>= match_eq, (op, _, _) ← is_bin_app lhs, h_assoc ← to_expr `(is_associative.assoc %%op), h_comm ← to_expr `(is_commutative.comm %%op), sort_ac_core op h_comm h_assoc /- We still did not declare the instances is_associative and is_commutative for op. We have to mark them as noncomputable because we did not define them. -/ noncomputable instance : is_associative _ op := ⟨h_assoc⟩ noncomputable instance : is_commutative _ op := ⟨h_comm⟩ example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) := by sort_ac example (s₁ s₂ s₃ : set nat) : s₁ ∪ s₂ ∪ s₃ = s₃ ∪ s₁ ∪ s₂ := by sort_ac set_option trace.sort_ac true example (a b c : nat) : a + b + c = c + b + a := by sort_ac
5193267b75ab799f9a688ef99708ec3844f0ab7e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/mk_iff_of_inductive_prop.lean
c478455bd69608f90e93081f9985810779951f37
[]
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
4,891
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.tactic.lint.default import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # mk_iff_of_inductive_prop This file defines a tactic `tactic.mk_iff_of_inductive_prop` that generates `iff` rules for inductive `Prop`s. For example, when applied to `list.chain`, it creates a declaration with the following type: ```lean ∀{α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` This tactic can be called using either the `mk_iff_of_inductive_prop` user command or the `mk_iff` attribute. -/ namespace mk_iff /-- `select m n` runs `tactic.right` `m` times, and then `tactic.left` `(n-m)` times. Fails if `n < m`. -/ /-- `compact_relation bs as_ps`: Produce a relation of the form: ```lean R as := ∃ bs, Λ_i a_i = p_i[bs] ``` This relation is user-visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. TODO: this is a variant of `compact_relation` in `coinductive_predicates.lean`, export it there. -/ /-- Iterate over two lists, if the first element of the first list is `none`, insert `none` into the result and continue with the tail of first list. Otherwise, wrap the first element of the second list with `some` and continue with the tails of both lists. Return when either list is empty. Example: ``` list_option_merge [none, some (), none, some ()] [0, 1, 2, 3, 4] = [none, (some 0), none, (some 1)] ``` -/ def list_option_merge {α : Type u_1} {β : Type u_2} : List (Option α) → List β → List (Option β) := sorry end mk_iff namespace tactic /-- `mk_iff_of_inductive_prop i r` makes an `iff` rule for the inductively-defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each of the constructors, and the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example, `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` -/ end tactic /-- `mk_iff_of_inductive_prop i r` makes an `iff` rule for the inductively-defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each of the constructors, and the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example, `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` See also the `mk_iff` user attribute. -/ /-- Applying the `mk_iff` attribute to an inductively-defined proposition `mk_iff` makes an `iff` rule `r` with the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each of the constructors, and the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example, if we try the following: ```lean @[mk_iff] structure foo (m n : ℕ) : Prop := (equal : m = n) (sum_eq_two : m + n = 2) ``` Then `#check foo_iff` returns: ```lean foo_iff : ∀ (m n : ℕ), foo m n ↔ m = n ∧ m + n = 2 ``` You can add an optional string after `mk_iff` to change the name of the generated lemma. For example, if we try the following: ```lean @[mk_iff bar] structure foo (m n : ℕ) : Prop := (equal : m = n) (sum_eq_two : m + n = 2) ``` Then `#check bar` returns: ```lean bar : ∀ (m n : ℕ), foo m n ↔ m = n ∧ m + n = 2 ``` See also the user command `mk_iff_of_inductive_prop`. -/
ee7fb9898726c046e638344f561074eb434fbef1
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/ring_theory/dedekind_domain.lean
732a640b190c3ac260ed1660e75c4ab0bf17da10
[ "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
44,361
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.discrete_valuation_ring import ring_theory.fractional_ideal import ring_theory.ideal.over import ring_theory.integrally_closed import ring_theory.polynomial.rational_root import ring_theory.trace import algebra.associated /-! # Dedekind domains This file defines the notion of a Dedekind domain (or Dedekind ring), giving three equivalent definitions (TODO: and shows that they are equivalent). ## Main definitions - `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is Noetherian, integrally closed in its field of fractions and has Krull dimension at most one. `is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions. - `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that is Noetherian, and the localization at every nonzero prime ideal is a DVR. - `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain where every nonzero fractional ideal is invertible. - `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of fractions. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K] open_locale non_zero_divisors /-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/ def ring.dimension_le_one : Prop := ∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal open ideal ring namespace ring lemma dimension_le_one.principal_ideal_ring [is_domain A] [is_principal_ideal_ring A] : dimension_le_one A := λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero } lemma dimension_le_one.is_integral_closure (B : Type*) [comm_ring B] [is_domain B] [nontrivial R] [algebra R A] [algebra R B] [algebra B A] [is_scalar_tower R B A] [is_integral_closure B R A] (h : dimension_le_one R) : dimension_le_one B := λ p ne_bot prime, by exactI is_integral_closure.is_maximal_of_is_maximal_comap A p (h _ (is_integral_closure.comap_ne_bot A ne_bot) infer_instance) lemma dimension_le_one.integral_closure [nontrivial R] [is_domain A] [algebra R A] (h : dimension_le_one R) : dimension_le_one (integral_closure R A) := h.is_integral_closure R A (integral_closure R A) end ring variables [is_domain A] /-- A Dedekind domain is an integral domain that is Noetherian, integrally closed, and has Krull dimension at most one. This is definition 3.2 of [Neukirch1992]. The integral closure condition is independent of the choice of field of fractions: use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`. This is the default implementation, but there are equivalent definitions, `is_dedekind_domain_dvr` and `is_dedekind_domain_inv`. TODO: Prove that these are actually equivalent definitions. -/ class is_dedekind_domain : Prop := (is_noetherian_ring : is_noetherian_ring A) (dimension_le_one : dimension_le_one A) (is_integrally_closed : is_integrally_closed A) -- See library note [lower instance priority] attribute [instance, priority 100] is_dedekind_domain.is_noetherian_ring is_dedekind_domain.is_integrally_closed /-- An integral domain is a Dedekind domain iff and only if it is Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field. In particular, this definition does not depend on the choice of this fraction field. -/ lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] : is_dedekind_domain A ↔ is_noetherian_ring A ∧ dimension_le_one A ∧ (∀ {x : K}, is_integral A x → ∃ y, algebra_map A K y = x) := ⟨λ ⟨hr, hd, hi⟩, ⟨hr, hd, λ x, (is_integrally_closed_iff K).mp hi⟩, λ ⟨hr, hd, hi⟩, ⟨hr, hd, (is_integrally_closed_iff K).mpr @hi⟩⟩ @[priority 100] -- See library note [lower instance priority] instance is_principal_ideal_ring.is_dedekind_domain [is_principal_ideal_ring A] : is_dedekind_domain A := ⟨principal_ideal_ring.is_noetherian_ring, ring.dimension_le_one.principal_ideal_ring A, unique_factorization_monoid.is_integrally_closed⟩ /-- A Dedekind domain is an integral domain that is Noetherian, and the localization at every nonzero prime is a discrete valuation ring. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_dvr : Prop := (is_noetherian_ring : is_noetherian_ring A) (is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime → discrete_valuation_ring (localization.at_prime P)) section inverse variables {R₁ : Type*} [comm_ring R₁] [is_domain R₁] [algebra R₁ K] [is_fraction_ring R₁ K] variables {I J : fractional_ideal R₁⁰ K} noncomputable instance : has_inv (fractional_ideal R₁⁰ K) := ⟨λ I, 1 / I⟩ lemma inv_eq : I⁻¹ = 1 / I := rfl lemma inv_zero' : (0 : fractional_ideal R₁⁰ K)⁻¹ = 0 := fractional_ideal.div_zero lemma inv_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : J⁻¹ = ⟨(1 : fractional_ideal R₁⁰ K) / J, fractional_ideal.fractional_div_of_nonzero h⟩ := fractional_ideal.div_nonzero _ lemma coe_inv_of_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (↑J⁻¹ : submodule R₁ K) = is_localization.coe_submodule K ⊤ / J := by { rwa inv_nonzero _, refl, assumption } variables {K} lemma mem_inv_iff (hI : I ≠ 0) {x : K} : x ∈ I⁻¹ ↔ ∀ y ∈ I, x * y ∈ (1 : fractional_ideal R₁⁰ K) := fractional_ideal.mem_div_iff_of_nonzero hI lemma inv_anti_mono (hI : I ≠ 0) (hJ : J ≠ 0) (hIJ : I ≤ J) : J⁻¹ ≤ I⁻¹ := λ x, by { simp only [mem_inv_iff hI, mem_inv_iff hJ], exact λ h y hy, h y (hIJ hy) } lemma le_self_mul_inv {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * I⁻¹ := fractional_ideal.le_self_mul_one_div hI variables (K) lemma coe_ideal_le_self_mul_inv (I : ideal R₁) : (I : fractional_ideal R₁⁰ K) ≤ I * I⁻¹ := le_self_mul_inv fractional_ideal.coe_ideal_le_one /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply fractional_ideal.mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply fractional_ideal.mul_left_mono I, apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact fractional_ideal.mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa ← right_inverse_eq K I J hJ⟩ lemma mul_inv_cancel_iff_is_unit {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ is_unit I := (mul_inv_cancel_iff K).trans is_unit_iff_exists_inv.symm variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_inv (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I⁻¹).map (h : K →ₐ[R₁] K') = (I.map h)⁻¹ := by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq] open submodule submodule.is_principal @[simp] lemma span_singleton_inv (x : K) : (fractional_ideal.span_singleton R₁⁰ x)⁻¹ = fractional_ideal.span_singleton _ (x⁻¹) := fractional_ideal.one_div_span_singleton x lemma mul_generator_self_inv {R₁ : Type*} [comm_ring R₁] [algebra R₁ K] [is_localization R₁⁰ K] (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I }, rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel, fractional_ideal.span_singleton_one], intro generator_I_eq_zero, apply h, rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero, fractional_ideal.span_singleton_zero] end lemma invertible_of_principal (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * I⁻¹ = 1 := (fractional_ideal.mul_div_self_cancel_iff).mpr ⟨fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹, mul_generator_self_inv _ I h⟩ lemma invertible_iff_generator_nonzero (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] : I * I⁻¹ = 1 ↔ generator (I : submodule R₁ K) ≠ 0 := begin split, { intros hI hg, apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI, rw [fractional_ideal.eq_span_singleton_of_principal I, hg, fractional_ideal.span_singleton_zero] }, { intro hg, apply invertible_of_principal, rw [fractional_ideal.eq_span_singleton_of_principal I], intro hI, have := fractional_ideal.mem_span_singleton_self _ (generator (I : submodule R₁ K)), rw [hI, fractional_ideal.mem_zero_iff] at this, contradiction } end lemma is_principal_inv (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : submodule.is_principal (I⁻¹).1 := begin rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff], use (generator (I : submodule R₁ K))⁻¹, have hI : I * fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹) = 1, apply mul_generator_self_inv _ I h, exact (right_inverse_eq _ I (fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹)) hI).symm end @[simp] lemma fractional_ideal.one_inv : (1⁻¹ : fractional_ideal R₁⁰ K) = 1 := fractional_ideal.div_one /-- A Dedekind domain is an integral domain such that every fractional ideal has an inverse. This is equivalent to `is_dedekind_domain`. In particular we provide a `fractional_ideal.comm_group_with_zero` instance, assuming `is_dedekind_domain A`, which implies `is_dedekind_domain_inv`. For **integral** ideals, `is_dedekind_domain`(`_inv`) implies only `ideal.comm_cancel_monoid_with_zero`. -/ def is_dedekind_domain_inv : Prop := ∀ I ≠ (⊥ : fractional_ideal A⁰ (fraction_ring A)), I * I⁻¹ = 1 open fractional_ideal variables {R A K} lemma is_dedekind_domain_inv_iff [algebra A K] [is_fraction_ring A K] : is_dedekind_domain_inv A ↔ (∀ I ≠ (⊥ : fractional_ideal A⁰ K), I * I⁻¹ = 1) := begin set h := fraction_ring.alg_equiv A K, split; rintros hi I hI, { refine fractional_ideal.map_injective h.symm.to_alg_hom h.symm.injective _, rw [alg_equiv.to_alg_hom_eq_coe, inv_eq, fractional_ideal.map_mul, fractional_ideal.map_one_div, fractional_ideal.map_one, ← inv_eq, hi], exact fractional_ideal.map_ne_zero _ hI }, { refine fractional_ideal.map_injective h.to_alg_hom h.injective _, rw [alg_equiv.to_alg_hom_eq_coe, inv_eq, fractional_ideal.map_mul, fractional_ideal.map_one_div, fractional_ideal.map_one, ← inv_eq, hi], exact fractional_ideal.map_ne_zero _ hI }, end lemma fractional_ideal.adjoin_integral_eq_one_of_is_unit [algebra A K] [is_fraction_ring A K] (x : K) (hx : is_integral A x) (hI : is_unit (adjoin_integral A⁰ x hx)) : adjoin_integral A⁰ x hx = 1 := begin set I := adjoin_integral A⁰ x hx, have mul_self : I * I = I, { apply fractional_ideal.coe_to_submodule_injective, simp }, convert congr_arg (* I⁻¹) mul_self; simp only [(mul_inv_cancel_iff_is_unit K).mpr hI, mul_assoc, mul_one], end namespace is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] (h : is_dedekind_domain_inv A) include h lemma mul_inv_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I * I⁻¹ = 1 := is_dedekind_domain_inv_iff.mp h I hI lemma inv_mul_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I⁻¹ * I = 1 := (mul_comm _ _).trans (h.mul_inv_eq_one hI) protected lemma is_unit {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : is_unit I := is_unit_of_mul_eq_one _ _ (h.mul_inv_eq_one hI) lemma is_noetherian_ring : is_noetherian_ring A := begin refine is_noetherian_ring_iff.mpr ⟨λ (I : ideal A), _⟩, by_cases hI : I = ⊥, { rw hI, apply submodule.fg_bot }, have hI : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, exact I.fg_of_is_unit (is_fraction_ring.injective A (fraction_ring A)) (h.is_unit hI) end lemma integrally_closed : is_integrally_closed A := begin -- It suffices to show that for integral `x`, -- `A[x]` (which is a fractional ideal) is in fact equal to `A`. refine ⟨λ x hx, _⟩, rw [← set.mem_range, ← algebra.mem_bot, ← subalgebra.mem_to_submodule, algebra.to_submodule_bot, ← coe_span_singleton A⁰ (1 : fraction_ring A), fractional_ideal.span_singleton_one, ← fractional_ideal.adjoin_integral_eq_one_of_is_unit x hx (h.is_unit _)], { exact mem_adjoin_integral_self A⁰ x hx }, { exact λ h, one_ne_zero (eq_zero_iff.mp h 1 (subalgebra.one_mem _)) }, end lemma dimension_le_one : dimension_le_one A := begin -- We're going to show that `P` is maximal because any (maximal) ideal `M` -- that is strictly larger would be `⊤`. rintros P P_ne hP, refine ideal.is_maximal_def.mpr ⟨hP.ne_top, λ M hM, _⟩, -- We may assume `P` and `M` (as fractional ideals) are nonzero. have P'_ne : (P : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr P_ne, have M'_ne : (M : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr (lt_of_le_of_lt bot_le hM).ne', -- In particular, we'll show `M⁻¹ * P ≤ P` suffices : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ P, { rw [eq_top_iff, ← coe_ideal_le_coe_ideal (fraction_ring A), fractional_ideal.coe_ideal_top], calc (1 : fractional_ideal A⁰ (fraction_ring A)) = _ * _ * _ : _ ... ≤ _ * _ : mul_right_mono (P⁻¹ * M : fractional_ideal A⁰ (fraction_ring A)) this ... = M : _, { rw [mul_assoc, ← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul, h.inv_mul_eq_one M'_ne] }, { rw [← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul] }, { apply_instance } }, -- Suppose we have `x ∈ M⁻¹ * P`, then in fact `x = algebra_map _ _ y` for some `y`. intros x hx, have le_one : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ 1, { rw [← h.inv_mul_eq_one M'_ne], exact fractional_ideal.mul_left_mono _ ((coe_ideal_le_coe_ideal (fraction_ring A)).mpr hM.le) }, obtain ⟨y, hy, rfl⟩ := (mem_coe_ideal _).mp (le_one hx), -- Since `M` is strictly greater than `P`, let `z ∈ M \ P`. obtain ⟨z, hzM, hzp⟩ := set_like.exists_of_lt hM, -- We have `z * y ∈ M * (M⁻¹ * P) = P`. have zy_mem := fractional_ideal.mul_mem_mul (mem_coe_ideal_of_mem A⁰ hzM) hx, rw [← ring_hom.map_mul, ← mul_assoc, h.mul_inv_eq_one M'_ne, one_mul] at zy_mem, obtain ⟨zy, hzy, zy_eq⟩ := (mem_coe_ideal A⁰).mp zy_mem, rw is_fraction_ring.injective A (fraction_ring A) zy_eq at hzy, -- But `P` is a prime ideal, so `z ∉ P` implies `y ∈ P`, as desired. exact mem_coe_ideal_of_mem A⁰ (or.resolve_left (hP.mem_or_mem hzy) hzp) end /-- Showing one side of the equivalence between the definitions `is_dedekind_domain_inv` and `is_dedekind_domain` of Dedekind domains. -/ theorem is_dedekind_domain : is_dedekind_domain A := ⟨h.is_noetherian_ring, h.dimension_le_one, h.integrally_closed⟩ end is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] /-- Specialization of `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` to Dedekind domains: Let `I : ideal A` be a nonzero ideal, where `A` is a Dedekind domain that is not a field. Then `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` states we can find a product of prime ideals that is contained within `I`. This lemma extends that result by making the product minimal: let `M` be a maximal ideal that contains `I`, then the product including `M` is contained within `I` and the product excluding `M` is not contained within `I`. -/ lemma exists_multiset_prod_cons_le_and_prod_not_le [is_dedekind_domain A] (hNF : ¬ is_field A) {I M : ideal A} (hI0 : I ≠ ⊥) (hIM : I ≤ M) [hM : M.is_maximal] : ∃ (Z : multiset (prime_spectrum A)), (M ::ₘ (Z.map prime_spectrum.as_ideal)).prod ≤ I ∧ ¬ (multiset.prod (Z.map prime_spectrum.as_ideal) ≤ I) := begin -- Let `Z` be a minimal set of prime ideals such that their product is contained in `J`. obtain ⟨Z₀, hZ₀⟩ := exists_prime_spectrum_prod_le_and_ne_bot_of_domain hNF hI0, obtain ⟨Z, ⟨hZI, hprodZ⟩, h_eraseZ⟩ := multiset.well_founded_lt.has_min (λ Z, (Z.map prime_spectrum.as_ideal).prod ≤ I ∧ (Z.map prime_spectrum.as_ideal).prod ≠ ⊥) ⟨Z₀, hZ₀⟩, have hZM : multiset.prod (Z.map prime_spectrum.as_ideal) ≤ M := le_trans hZI hIM, have hZ0 : Z ≠ 0, { rintro rfl, simpa [hM.ne_top] using hZM }, obtain ⟨_, hPZ', hPM⟩ := (hM.is_prime.multiset_prod_le (mt multiset.map_eq_zero.mp hZ0)).mp hZM, -- Then in fact there is a `P ∈ Z` with `P ≤ M`. obtain ⟨P, hPZ, rfl⟩ := multiset.mem_map.mp hPZ', letI := classical.dec_eq (ideal A), have := multiset.map_erase prime_spectrum.as_ideal subtype.coe_injective P Z, obtain ⟨hP0, hZP0⟩ : P.as_ideal ≠ ⊥ ∧ ((Z.erase P).map prime_spectrum.as_ideal).prod ≠ ⊥, { rwa [ne.def, ← multiset.cons_erase hPZ', multiset.prod_cons, ideal.mul_eq_bot, not_or_distrib, ← this] at hprodZ }, -- By maximality of `P` and `M`, we have that `P ≤ M` implies `P = M`. have hPM' := (is_dedekind_domain.dimension_le_one _ hP0 P.is_prime).eq_of_le hM.ne_top hPM, tactic.unfreeze_local_instances, subst hPM', -- By minimality of `Z`, erasing `P` from `Z` is exactly what we need. refine ⟨Z.erase P, _, _⟩, { convert hZI, rw [this, multiset.cons_erase hPZ'] }, { refine λ h, h_eraseZ (Z.erase P) ⟨h, _⟩ (multiset.erase_lt.mpr hPZ), exact hZP0 } end namespace fractional_ideal lemma exists_not_mem_one_of_ne_bot [is_dedekind_domain A] (hNF : ¬ is_field A) {I : ideal A} (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) : ∃ x : K, x ∈ (I⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K) := begin -- WLOG, let `I` be maximal. suffices : ∀ {M : ideal A} (hM : M.is_maximal), ∃ x : K, x ∈ (M⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K), { obtain ⟨M, hM, hIM⟩ : ∃ (M : ideal A), is_maximal M ∧ I ≤ M := ideal.exists_le_maximal I hI1, resetI, have hM0 := (M.bot_lt_of_maximal hNF).ne', obtain ⟨x, hxM, hx1⟩ := this hM, refine ⟨x, inv_anti_mono _ _ ((coe_ideal_le_coe_ideal _).mpr hIM) hxM, hx1⟩; apply fractional_ideal.coe_ideal_ne_zero; assumption }, -- Let `a` be a nonzero element of `M` and `J` the ideal generated by `a`. intros M hM, resetI, obtain ⟨⟨a, haM⟩, ha0⟩ := submodule.nonzero_mem_of_bot_lt (M.bot_lt_of_maximal hNF), replace ha0 : a ≠ 0 := subtype.coe_injective.ne ha0, let J : ideal A := ideal.span {a}, have hJ0 : J ≠ ⊥ := mt ideal.span_singleton_eq_bot.mp ha0, have hJM : J ≤ M := ideal.span_le.mpr (set.singleton_subset_iff.mpr haM), have hM0 : ⊥ < M := M.bot_lt_of_maximal hNF, -- Then we can find a product of prime (hence maximal) ideals contained in `J`, -- such that removing element `M` from the product is not contained in `J`. obtain ⟨Z, hle, hnle⟩ := exists_multiset_prod_cons_le_and_prod_not_le hNF hJ0 hJM, -- Choose an element `b` of the product that is not in `J`. obtain ⟨b, hbZ, hbJ⟩ := set_like.not_le_iff_exists.mp hnle, have hnz_fa : algebra_map A K a ≠ 0 := mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) a) ha0, have hb0 : algebra_map A K b ≠ 0 := mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) b) (λ h, hbJ $ h.symm ▸ J.zero_mem), -- Then `b a⁻¹ : K` is in `M⁻¹` but not in `1`. refine ⟨algebra_map A K b * (algebra_map A K a)⁻¹, (mem_inv_iff _).mpr _, _⟩, { exact (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl _)).mpr hM0.ne' }, { rintro y₀ hy₀, obtain ⟨y, h_Iy, rfl⟩ := (fractional_ideal.mem_coe_ideal _).mp hy₀, rw [mul_comm, ← mul_assoc, ← ring_hom.map_mul], have h_yb : y * b ∈ J, { apply hle, rw multiset.prod_cons, exact submodule.smul_mem_smul h_Iy hbZ }, rw ideal.mem_span_singleton' at h_yb, rcases h_yb with ⟨c, hc⟩, rw [← hc, ring_hom.map_mul, mul_assoc, mul_inv_cancel hnz_fa, mul_one], apply fractional_ideal.coe_mem_one }, { refine mt (fractional_ideal.mem_one_iff _).mp _, rintros ⟨x', h₂_abs⟩, rw [← div_eq_mul_inv, eq_div_iff_mul_eq hnz_fa, ← ring_hom.map_mul] at h₂_abs, have := ideal.mem_span_singleton'.mpr ⟨x', is_fraction_ring.injective A K h₂_abs⟩, contradiction }, end lemma one_mem_inv_coe_ideal {I : ideal A} (hI : I ≠ ⊥) : (1 : K) ∈ (I : fractional_ideal A⁰ K)⁻¹ := begin rw mem_inv_iff (fractional_ideal.coe_ideal_ne_zero hI), intros y hy, rw one_mul, exact coe_ideal_le_one hy, assumption end lemma mul_inv_cancel_of_le_one [h : is_dedekind_domain A] {I : ideal A} (hI0 : I ≠ ⊥) (hI : ((I * I⁻¹)⁻¹ : fractional_ideal A⁰ K) ≤ 1) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- Handle a few trivial cases. by_cases hI1 : I = ⊤, { rw [hI1, coe_ideal_top, one_mul, fractional_ideal.one_inv] }, by_cases hNF : is_field A, { letI := hNF.to_field A, rcases hI1 (I.eq_bot_or_top.resolve_left hI0) }, -- We'll show a contradiction with `exists_not_mem_one_of_ne_bot`: -- `J⁻¹ = (I * I⁻¹)⁻¹` cannot have an element `x ∉ 1`, so it must equal `1`. obtain ⟨J, hJ⟩ : ∃ (J : ideal A), (J : fractional_ideal A⁰ K) = I * I⁻¹ := le_one_iff_exists_coe_ideal.mp mul_one_div_le_one, by_cases hJ0 : J = ⊥, { subst hJ0, refine absurd _ hI0, rw [eq_bot_iff, ← coe_ideal_le_coe_ideal K, hJ], exact coe_ideal_le_self_mul_inv K I, apply_instance }, by_cases hJ1 : J = ⊤, { rw [← hJ, hJ1, coe_ideal_top] }, obtain ⟨x, hx, hx1⟩ : ∃ (x : K), x ∈ (J : fractional_ideal A⁰ K)⁻¹ ∧ x ∉ (1 : fractional_ideal A⁰ K) := exists_not_mem_one_of_ne_bot hNF hJ0 hJ1, contrapose! hx1 with h_abs, rw hJ at hx, exact hI hx, end /-- Nonzero integral ideals in a Dedekind domain are invertible. We will use this to show that nonzero fractional ideals are invertible, and finally conclude that fractional ideals in a Dedekind domain form a group with zero. -/ lemma coe_ideal_mul_inv [h : is_dedekind_domain A] (I : ideal A) (hI0 : I ≠ ⊥) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- We'll show `1 ≤ J⁻¹ = (I * I⁻¹)⁻¹ ≤ 1`. apply mul_inv_cancel_of_le_one hI0, by_cases hJ0 : (I * I⁻¹ : fractional_ideal A⁰ K) = 0, { rw [hJ0, inv_zero'], exact fractional_ideal.zero_le _ }, intros x hx, -- In particular, we'll show all `x ∈ J⁻¹` are integral. suffices : x ∈ integral_closure A K, { rwa [is_integrally_closed.integral_closure_eq_bot, algebra.mem_bot, set.mem_range, ← fractional_ideal.mem_one_iff] at this; assumption }, -- For that, we'll find a subalgebra that is f.g. as a module and contains `x`. -- `A` is a noetherian ring, so we just need to find a subalgebra between `{x}` and `I⁻¹`. rw mem_integral_closure_iff_mem_fg, have x_mul_mem : ∀ b ∈ (I⁻¹ : fractional_ideal A⁰ K), x * b ∈ (I⁻¹ : fractional_ideal A⁰ K), { intros b hb, rw mem_inv_iff at ⊢ hx, swap, { exact fractional_ideal.coe_ideal_ne_zero hI0 }, swap, { exact hJ0 }, simp only [mul_assoc, mul_comm b] at ⊢ hx, intros y hy, exact hx _ (fractional_ideal.mul_mem_mul hy hb) }, -- It turns out the subalgebra consisting of all `p(x)` for `p : polynomial A` works. refine ⟨alg_hom.range (polynomial.aeval x : polynomial A →ₐ[A] K), is_noetherian_submodule.mp (fractional_ideal.is_noetherian I⁻¹) _ (λ y hy, _), ⟨polynomial.X, polynomial.aeval_X x⟩⟩, obtain ⟨p, rfl⟩ := (alg_hom.mem_range _).mp hy, rw polynomial.aeval_eq_sum_range, refine submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ _), clear hi, induction i with i ih, { rw pow_zero, exact one_mem_inv_coe_ideal hI0 }, { show x ^ i.succ ∈ (I⁻¹ : fractional_ideal A⁰ K), rw pow_succ, exact x_mul_mem _ ih }, end /-- Nonzero fractional ideals in a Dedekind domain are units. This is also available as `_root_.mul_inv_cancel`, using the `comm_group_with_zero` instance defined below. -/ protected theorem mul_inv_cancel [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hne : I ≠ 0) : I * I⁻¹ = 1 := begin obtain ⟨a, J, ha, hJ⟩ : ∃ (a : A) (aI : ideal A), a ≠ 0 ∧ I = span_singleton A⁰ (algebra_map _ _ a)⁻¹ * aI := exists_eq_span_singleton_mul I, suffices h₂ : I * (span_singleton A⁰ (algebra_map _ _ a) * J⁻¹) = 1, { rw mul_inv_cancel_iff, exact ⟨span_singleton A⁰ (algebra_map _ _ a) * J⁻¹, h₂⟩ }, subst hJ, rw [mul_assoc, mul_left_comm (J : fractional_ideal A⁰ K), coe_ideal_mul_inv, mul_one, fractional_ideal.span_singleton_mul_span_singleton, inv_mul_cancel, fractional_ideal.span_singleton_one], { exact mt ((algebra_map A K).injective_iff.mp (is_fraction_ring.injective A K) _) ha }, { exact fractional_ideal.coe_ideal_ne_zero_iff.mp (right_ne_zero_of_mul hne) } end lemma mul_right_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K} (hJ : J ≠ 0) : ∀ {I I'}, I * J ≤ I' * J ↔ I ≤ I' := begin intros I I', split, { intros h, convert mul_right_mono J⁻¹ h; rw [mul_assoc, fractional_ideal.mul_inv_cancel hJ, mul_one] }, { exact λ h, mul_right_mono J h } end lemma mul_left_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K} (hJ : J ≠ 0) {I I'} : J * I ≤ J * I' ↔ I ≤ I' := by convert fractional_ideal.mul_right_le_iff hJ using 1; simp only [mul_comm] lemma mul_right_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : strict_mono (* I) := strict_mono_of_le_iff_le (λ _ _, (mul_right_le_iff hI).symm) lemma mul_left_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : strict_mono ((*) I) := strict_mono_of_le_iff_le (λ _ _, (mul_left_le_iff hI).symm) /-- This is also available as `_root_.div_eq_mul_inv`, using the `comm_group_with_zero` instance defined below. -/ protected lemma div_eq_mul_inv [is_dedekind_domain A] (I J : fractional_ideal A⁰ K) : I / J = I * J⁻¹ := begin by_cases hJ : J = 0, { rw [hJ, div_zero, inv_zero', mul_zero] }, refine le_antisymm ((mul_right_le_iff hJ).mp _) ((le_div_iff_mul_le hJ).mpr _), { rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one, mul_le], intros x hx y hy, rw [mem_div_iff_of_nonzero hJ] at hx, exact hx y hy }, rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one], exact le_refl I end end fractional_ideal /-- `is_dedekind_domain` and `is_dedekind_domain_inv` are equivalent ways to express that an integral domain is a Dedekind domain. -/ theorem is_dedekind_domain_iff_is_dedekind_domain_inv : is_dedekind_domain A ↔ is_dedekind_domain_inv A := ⟨λ h I hI, by exactI fractional_ideal.mul_inv_cancel hI, λ h, h.is_dedekind_domain⟩ end inverse section is_dedekind_domain variables {R A} [is_dedekind_domain A] [algebra A K] [is_fraction_ring A K] open fractional_ideal noncomputable instance fractional_ideal.comm_group_with_zero : comm_group_with_zero (fractional_ideal A⁰ K) := { inv := λ I, I⁻¹, inv_zero := inv_zero' _, div := (/), div_eq_mul_inv := fractional_ideal.div_eq_mul_inv, exists_pair_ne := ⟨0, 1, (coe_to_fractional_ideal_injective (le_refl _)).ne (by simpa using @zero_ne_one (ideal A) _ _)⟩, mul_inv_cancel := λ I, fractional_ideal.mul_inv_cancel, .. fractional_ideal.comm_semiring } noncomputable instance ideal.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero (ideal A) := function.injective.comm_cancel_monoid_with_zero (coe_ideal_hom A⁰ (fraction_ring A)) coe_ideal_injective (ring_hom.map_zero _) (ring_hom.map_one _) (ring_hom.map_mul _) /-- For ideals in a Dedekind domain, to divide is to contain. -/ lemma ideal.dvd_iff_le {I J : ideal A} : (I ∣ J) ↔ J ≤ I := ⟨ideal.le_of_dvd, λ h, begin by_cases hI : I = ⊥, { have hJ : J = ⊥, { rwa [hI, ← eq_bot_iff] at h }, rw [hI, hJ] }, have hI' : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, have : (I : fractional_ideal A⁰ (fraction_ring A))⁻¹ * J ≤ 1 := le_trans (fractional_ideal.mul_left_mono (↑I)⁻¹ ((coe_ideal_le_coe_ideal _).mpr h)) (le_of_eq (inv_mul_cancel hI')), obtain ⟨H, hH⟩ := fractional_ideal.le_one_iff_exists_coe_ideal.mp this, use H, refine coe_to_fractional_ideal_injective (le_refl (non_zero_divisors A)) (show (J : fractional_ideal A⁰ (fraction_ring A)) = _, from _), rw [fractional_ideal.coe_ideal_mul, hH, ← mul_assoc, mul_inv_cancel hI', one_mul] end⟩ lemma ideal.dvd_not_unit_iff_lt {I J : ideal A} : dvd_not_unit I J ↔ J < I := ⟨λ ⟨hI, H, hunit, hmul⟩, lt_of_le_of_ne (ideal.dvd_iff_le.mp ⟨H, hmul⟩) (mt (λ h, have H = 1, from mul_left_cancel₀ hI (by rw [← hmul, h, mul_one]), show is_unit H, from this.symm ▸ is_unit_one) hunit), λ h, dvd_not_unit_of_dvd_of_not_dvd (ideal.dvd_iff_le.mpr (le_of_lt h)) (mt ideal.dvd_iff_le.mp (not_le_of_lt h))⟩ instance : wf_dvd_monoid (ideal A) := { well_founded_dvd_not_unit := have well_founded ((>) : ideal A → ideal A → Prop) := is_noetherian_iff_well_founded.mp (is_noetherian_ring_iff.mp is_dedekind_domain.is_noetherian_ring), by { convert this, ext, rw ideal.dvd_not_unit_iff_lt } } instance ideal.unique_factorization_monoid : unique_factorization_monoid (ideal A) := { irreducible_iff_prime := λ P, ⟨λ hirr, ⟨hirr.ne_zero, hirr.not_unit, λ I J, begin have : P.is_maximal, { refine ⟨⟨mt ideal.is_unit_iff.mpr hirr.not_unit, _⟩⟩, intros J hJ, obtain ⟨J_ne, H, hunit, P_eq⟩ := ideal.dvd_not_unit_iff_lt.mpr hJ, exact ideal.is_unit_iff.mp ((hirr.is_unit_or_is_unit P_eq).resolve_right hunit) }, rw [ideal.dvd_iff_le, ideal.dvd_iff_le, ideal.dvd_iff_le, set_like.le_def, set_like.le_def, set_like.le_def], contrapose!, rintros ⟨⟨x, x_mem, x_not_mem⟩, ⟨y, y_mem, y_not_mem⟩⟩, exact ⟨x * y, ideal.mul_mem_mul x_mem y_mem, mt this.is_prime.mem_or_mem (not_or x_not_mem y_not_mem)⟩, end⟩, prime.irreducible⟩, .. ideal.wf_dvd_monoid } noncomputable instance ideal.normalization_monoid : normalization_monoid (ideal A) := normalization_monoid_of_unique_units @[simp] lemma ideal.dvd_span_singleton {I : ideal A} {x : A} : I ∣ ideal.span {x} ↔ x ∈ I := ideal.dvd_iff_le.trans (ideal.span_le.trans set.singleton_subset_iff) lemma ideal.is_prime_of_prime {P : ideal A} (h : prime P) : is_prime P := begin refine ⟨_, λ x y hxy, _⟩, { unfreezingI { rintro rfl }, rw ← ideal.one_eq_top at h, exact h.not_unit is_unit_one }, { simp only [← ideal.dvd_span_singleton, ← ideal.span_singleton_mul_span_singleton] at ⊢ hxy, exact h.dvd_or_dvd hxy } end theorem ideal.prime_of_is_prime {P : ideal A} (hP : P ≠ ⊥) (h : is_prime P) : prime P := begin refine ⟨hP, mt ideal.is_unit_iff.mp h.ne_top, λ I J hIJ, _⟩, simpa only [ideal.dvd_iff_le] using (h.mul_le.mp (ideal.le_of_dvd hIJ)), end /-- In a Dedekind domain, the (nonzero) prime elements of the monoid with zero `ideal A` are exactly the prime ideals. -/ theorem ideal.prime_iff_is_prime {P : ideal A} (hP : P ≠ ⊥) : prime P ↔ is_prime P := ⟨ideal.is_prime_of_prime, ideal.prime_of_is_prime hP⟩ end is_dedekind_domain section is_integral_closure /-! ### `is_integral_closure` section We show that an integral closure of a Dedekind domain in a finite separable field extension is again a Dedekind domain. This implies the ring of integers of a number field is a Dedekind domain. -/ open algebra open_locale big_operators variables {A K} [algebra A K] [is_fraction_ring A K] variables {L : Type*} [field L] (C : Type*) [comm_ring C] variables [algebra K L] [finite_dimensional K L] [algebra A L] [is_scalar_tower A K L] variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L] lemma is_integral_closure.range_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : ((algebra.linear_map C L).restrict_scalars A).range ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, rintros _ ⟨x, rfl⟩, simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply], have hx : is_integral A (algebra_map C L x) := (is_integral_closure.is_integral A L x).algebra_map, suffices : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i, { obtain ⟨c, x_eq⟩ := this, rw x_eq, refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)), rw set.mem_range, exact ⟨i, rfl⟩ }, suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i), { obtain ⟨c, hc, hx⟩ := this, have hc' : ∀ i, is_localization.is_integer A (c i) := λ i, is_integrally_closed.is_integral_iff.mp (hc i), use λ i, classical.some (hc' i), refine hx.trans (finset.sum_congr rfl (λ i _, _)), conv_lhs { rw [← classical.some_spec (hc' i)] }, rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] }, refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩, rw bilin_form.dual_basis_repr_apply, exact is_integral_trace (is_integral_mul hx (hb_int i)) end lemma integral_closure_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : (integral_closure A L).to_submodule ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int), intros x hx, exact ⟨⟨x, hx⟩, rfl⟩ end variables (A) (K) include K /-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R` to `(y : R) • x ∈ integral_closure R L`. -/ lemma exists_integral_multiples (s : finset L) : ∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) := begin haveI := classical.dec_eq L, refine s.induction _ _, { use [1, one_ne_zero], rintros x ⟨⟩ }, { rintros x s hx ⟨y, hy, hs⟩, obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple ((is_fraction_ring.is_algebraic_iff A K).mpr (algebra.is_algebraic_of_finite x)) ((algebra_map A L).injective_iff.mp _), refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩, rcases finset.mem_insert.mp hx'' with (rfl | hx''), { rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'], exact is_integral_mul is_integral_algebra_map x'.2 }, { rw [mul_comm, mul_smul, algebra.smul_def], exact is_integral_mul is_integral_algebra_map (hs _ hx'') }, { rw is_scalar_tower.algebra_map_eq A K L, apply (algebra_map K L).injective.comp, exact is_fraction_ring.injective _ _ } } end variables (L) /-- If `L` is a finite extension of `K = Frac(A)`, then `L` has a basis over `A` consisting of integral elements. -/ lemma finite_dimensional.exists_is_basis_integral : ∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) := begin letI := classical.dec_eq L, letI : is_noetherian K L := is_noetherian.iff_fg.2 infer_instance, let s' := is_noetherian.finset_basis_index K L, let bs' := is_noetherian.finset_basis K L, obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'), have hy' : algebra_map A L y ≠ 0, { refine mt ((algebra_map A L).injective_iff.mp _ _) hy, rw is_scalar_tower.algebra_map_eq A K L, exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) }, refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x, inv_fun := λ x, (algebra_map A L y)⁻¹ * x, left_inv := _, right_inv := _, .. algebra.lmul _ _ (algebra_map A L y) }, _⟩, { intros x, simp only [inv_mul_cancel_left₀ hy'] }, { intros x, simp only [mul_inv_cancel_left₀ hy'] }, { rintros ⟨x', hx'⟩, simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his', simp only [basis.map_apply, linear_equiv.coe_mk], exact his' _ ⟨_, rfl⟩ } end variables (A K L) [is_separable K L] include L /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure `C` of `A` in `L` is Noetherian. -/ lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring C := begin haveI := classical.dec_eq L, obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L, rw is_noetherian_ring_iff, let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, letI := is_noetherian_span_of_finite A (set.finite_range b'), let f : C →ₗ[A] submodule.span A (set.range b') := (submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp ((algebra.linear_map C L).restrict_scalars A).range_restrict, refine is_noetherian_of_tower A (is_noetherian_of_ker_bot f _), rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict], exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L) end variables {A K} /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure of `A` in `L` is Noetherian. -/ lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring (integral_closure A L) := is_integral_closure.is_noetherian_ring A K L (integral_closure A L) variables (A K) [is_domain C] /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure `C` of `A` in `L` is a Dedekind domain. Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A` and `C := integral_closure A L`. -/ lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain C := begin haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C, exact ⟨is_integral_closure.is_noetherian_ring A K L C, h.dimension_le_one.is_integral_closure _ L _, (is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x (is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx), is_integral_closure.algebra_map_mk' _ _ _⟩)⟩ end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. Can't be an instance since `K` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`. -/ lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := is_integral_closure.is_dedekind_domain A K L (integral_closure A L) omit K variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L] variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L] /- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. See also the lemma `integral_closure.is_dedekind_domain` where you can choose the field of fractions yourself. -/ instance integral_closure.is_dedekind_domain_fraction_ring [is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := integral_closure.is_dedekind_domain A (fraction_ring A) L end is_integral_closure section is_dedekind_domain variables {T : Type*} [comm_ring T] [is_domain T] [is_dedekind_domain T] (I J : ideal T) open_locale classical open multiset unique_factorization_monoid ideal lemma prod_normalized_factors_eq_self {I : ideal T} (hI : I ≠ ⊥) : (normalized_factors I).prod = I := associated_iff_eq.1 (normalized_factors_prod hI) lemma normalized_factors_prod {α : multiset (ideal T)} (h : ∀ p ∈ α, prime p) : normalized_factors α.prod = α := by { simp_rw [← multiset.rel_eq, ← associated_eq_eq], exact prime_factors_unique (prime_of_normalized_factor) h (normalized_factors_prod (α.prod_ne_zero_of_prime h)) } lemma count_le_of_ideal_ge {I J : ideal T} (h : I ≤ J) (hI : I ≠ ⊥) (K : ideal T) : count K (normalized_factors J) ≤ count K (normalized_factors I) := le_iff_count.1 ((dvd_iff_normalized_factors_le_normalized_factors (ne_bot_of_le_ne_bot hI h) hI).1 (dvd_iff_le.2 h)) _ lemma sup_eq_prod_inf_factors (hI : I ≠ ⊥) (hJ : J ≠ ⊥) : I ⊔ J = (normalized_factors I ∩ normalized_factors J).prod := begin have H : normalized_factors (normalized_factors I ∩ normalized_factors J).prod = normalized_factors I ∩ normalized_factors J, { apply _root_.normalized_factors_prod, intros p hp, rw mem_inter at hp, exact prime_of_normalized_factor p hp.left }, have := (multiset.prod_ne_zero_of_prime (normalized_factors I ∩ normalized_factors J) (λ _ h, prime_of_normalized_factor _ (multiset.mem_inter.1 h).1)), apply le_antisymm, { rw [sup_le_iff, ← dvd_iff_le, ← dvd_iff_le], split, { rw [dvd_iff_normalized_factors_le_normalized_factors this hI, H], exact inf_le_left }, { rw [dvd_iff_normalized_factors_le_normalized_factors this hJ, H], exact inf_le_right } }, { rw [← dvd_iff_le, dvd_iff_normalized_factors_le_normalized_factors, _root_.normalized_factors_prod, le_iff_count], { intro a, rw multiset.count_inter, exact le_min (count_le_of_ideal_ge le_sup_left hI a) (count_le_of_ideal_ge le_sup_right hJ a) }, { intros p hp, rw mem_inter at hp, exact prime_of_normalized_factor p hp.left }, { exact ne_bot_of_le_ne_bot hI le_sup_left }, { exact this } }, end end is_dedekind_domain
8bf8b913287d21dc5d647962e92c9293595b0a04
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/ulift.lean
ad33defd3e921d6476b99c477ea4d0aeb033b641
[ "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
2,678
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 logic.equiv.basic /-! # Extra lemmas about `ulift` and `plift` In this file we provide `subsingleton`, `unique`, `decidable_eq`, and `is_empty` instances for `ulift α` and `plift α`. We also prove `ulift.forall`, `ulift.exists`, `plift.forall`, and `plift.exists`. -/ universes u v open function namespace plift variables {α : Sort u} {β : Sort v} instance [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance [nonempty α] : nonempty (plift α) := equiv.plift.nonempty instance [unique α] : unique (plift α) := equiv.plift.unique instance [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq instance [is_empty α] : is_empty (plift α) := equiv.plift.is_empty lemma up_injective : injective (@up α) := equiv.plift.symm.injective lemma up_surjective : surjective (@up α) := equiv.plift.symm.surjective lemma up_bijective : bijective (@up α) := equiv.plift.symm.bijective @[simp] lemma up_inj {x y : α} : up x = up y ↔ x = y := up_injective.eq_iff lemma down_surjective : surjective (@down α) := equiv.plift.surjective lemma down_bijective : bijective (@down α) := equiv.plift.bijective @[simp] lemma «forall» {p : plift α → Prop} : (∀ x, p x) ↔ ∀ x : α, p (plift.up x) := up_surjective.forall @[simp] lemma «exists» {p : plift α → Prop} : (∃ x, p x) ↔ ∃ x : α, p (plift.up x) := up_surjective.exists end plift namespace ulift variables {α : Type u} {β : Type v} instance [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance [nonempty α] : nonempty (ulift α) := equiv.ulift.nonempty instance [unique α] : unique (ulift α) := equiv.ulift.unique instance [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance [is_empty α] : is_empty (ulift α) := equiv.ulift.is_empty lemma up_injective : injective (@up α) := equiv.ulift.symm.injective lemma up_surjective : surjective (@up α) := equiv.ulift.symm.surjective lemma up_bijective : bijective (@up α) := equiv.ulift.symm.bijective @[simp] lemma up_inj {x y : α} : up x = up y ↔ x = y := up_injective.eq_iff lemma down_surjective : surjective (@down α) := equiv.ulift.surjective lemma down_bijective : bijective (@down α) := equiv.ulift.bijective @[simp] lemma «forall» {p : ulift α → Prop} : (∀ x, p x) ↔ ∀ x : α, p (ulift.up x) := up_surjective.forall @[simp] lemma «exists» {p : ulift α → Prop} : (∃ x, p x) ↔ ∃ x : α, p (ulift.up x) := up_surjective.exists end ulift
c4ca3bd6337fcb166c48a8e85e58a9d5308fcc92
5d95c8513fa8592ce314d1f40c23ad5eecfe1e34
/src/algebra/identities/common.lean
0fe8226d78b1d8d03832535d6472238030619987
[ "Apache-2.0" ]
permissive
solovay/lean-universal
6b792513ced2fe82218e7828400743375dd59e24
417ed5e1b030e547912cbfefe34df9d3d01c2b65
refs/heads/master
1,598,052,603,315
1,565,981,123,000
1,565,981,123,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,177
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import algebra.notations.basic import .basic namespace algebra variables (α : Type*) (β : Type*) def add_assoc [has_add α] [class.op_associative (has_add.add:α→α→α)] : ∀ (x y z : α), (x + y) + z = x + (y + z) := op_associative _ def add_comm [has_add α] [class.op_commutative (has_add.add:α→α→α)] : ∀ (x y : α), x + y = y + x := op_commutative _ def add_left_comm [has_add α] [class.op_left_commutative (has_add.add:α→α→α)] : ∀ (x y z : α), x + (y + z) = y + (x + z) := op_left_commutative _ def add_right_comm [has_add α] [class.op_right_commutative (has_add.add:α→α→α)] : ∀ (x y z : α), (x + y) + z = (x + z) + y := op_right_commutative _ def zero_add [has_add α] [has_zero α] [class.op_left_identity (has_add.add:α→α→α) (has_zero.zero α)] : ∀ (x : α), 0 + x = x := op_left_identity _ _ def add_zero [has_add α] [has_zero α] [class.op_right_identity (has_add.add:α→α→α) (has_zero.zero α)] : ∀ (x : α), x + 0 = x := op_right_identity _ _ def neg_add [has_add α] [has_neg α] [class.fn_op_homomorphism (has_neg.neg:α→α) (has_add.add:α→α→α) (has_add.add:α→α→α)] : ∀ (x y : α), -(x + y) = -x + -y := fn_op_homomorphism _ _ _ def neg_add_rev [has_add α] [has_neg α] [class.fn_op_antimorphism (has_neg.neg:α→α) (has_add.add:α→α→α) (has_add.add:α→α→α)] : ∀ (x y : α), -(x + y) = -y + -x := fn_op_antimorphism _ _ _ def neg_add_self [has_add α] [has_neg α] [has_zero α] [class.op_left_inverse (has_add.add:α→α→α) (has_neg.neg:α→α) (has_zero.zero α)] : ∀ (x : α), -x + x = 0 := op_left_inverse _ _ _ def add_neg_self [has_add α] [has_neg α] [has_zero α] [class.op_right_inverse (has_add.add:α→α→α) (has_neg.neg:α→α) (has_zero.zero α)] : ∀ (x : α), x + -x = 0 := op_right_inverse _ _ _ def neg_zero [has_neg α] [has_zero α] [class.fn_fixpoint (has_neg.neg:α→α) (has_zero.zero α)] : -(0:α) = 0 := fn_fixpoint _ _ def neg_neg [has_neg α] [class.fn_involutive (has_neg.neg:α→α)] : ∀ (x : α), - - x = x := fn_involutive _ def mul_assoc [has_mul α] [class.op_associative (has_mul.mul:α→α→α)] : ∀ (x y z : α), (x * y) * z = x * (y * z) := op_associative _ def mul_comm [has_mul α] [class.op_commutative (has_mul.mul:α→α→α)] : ∀ (x y : α), x * y = y * x := op_commutative _ def mul_left_comm [has_mul α] [class.op_left_commutative (has_mul.mul:α→α→α)] : ∀ (x y z : α), x * (y * z) = y * (x * z) := op_left_commutative _ def mul_right_comm [has_mul α] [class.op_right_commutative (has_mul.mul:α→α→α)] : ∀ (x y z : α), (x * y) * z = (x * z) * y := op_right_commutative _ def one_mul [has_mul α] [has_one α] [class.op_left_identity (has_mul.mul:α→α→α) (has_one.one α)] : ∀ (x : α), 1 * x = x := op_left_identity _ _ def mul_one [has_mul α] [has_one α] [class.op_right_identity (has_mul.mul:α→α→α) (has_one.one α)] : ∀ (x : α), x * 1 = x := op_right_identity _ _ def zero_mul [has_mul α] [has_zero α] [class.op_left_fixpoint (has_mul.mul:α→α→α) (has_zero.zero α)] : ∀ (x : α), 0 * x = 0 := op_left_fixpoint _ _ def mul_zero [has_mul α] [has_zero α] [class.op_right_fixpoint (has_mul.mul:α→α→α) (has_zero.zero α)] : ∀ (x : α), x * 0 = 0 := op_right_fixpoint _ _ def inv_mul [has_mul α] [has_inv α] [class.fn_op_homomorphism (has_inv.inv:α→α) (has_mul.mul:α→α→α) (has_mul.mul:α→α→α)] : ∀ (x y : α), (x * y)⁻¹ = x⁻¹ * y⁻¹ := fn_op_homomorphism _ _ _ def inv_mul_rev [has_mul α] [has_inv α] [class.fn_op_antimorphism (has_inv.inv:α→α) (has_mul.mul:α→α→α) (has_mul.mul:α→α→α)] : ∀ (x y : α), (x * y)⁻¹ = y⁻¹ * x⁻¹ := fn_op_antimorphism _ _ _ def inv_mul_self [has_mul α] [has_inv α] [has_one α] [class.op_left_inverse (has_mul.mul:α→α→α) (has_inv.inv:α→α) (has_one.one α)] : ∀ (x : α), x⁻¹ * x = 1 := op_left_inverse _ _ _ def mul_inv_self [has_mul α] [has_inv α] [has_one α] [class.op_right_inverse (has_mul.mul:α→α→α) (has_inv.inv:α→α) (has_one.one α)] : ∀ (x : α), x * x⁻¹ = 1 := op_right_inverse _ _ _ def inv_one [has_inv α] [has_one α] [class.fn_fixpoint (has_inv.inv:α→α) (has_one.one α)] : (1:α)⁻¹ = 1 := fn_fixpoint _ _ def inv_inv [has_inv α] [class.fn_involutive (has_inv.inv:α→α)] : ∀ (x : α), x⁻¹⁻¹ = x := fn_involutive _ def neg_mul [has_mul α] [has_neg α] [class.op_left_fn_homomorphism (has_mul.mul:α→α→α) (has_neg.neg:α→α) (has_neg.neg:α→α)] : ∀ (x y : α), -x * y = -(x * y) := op_left_fn_homomorphism _ _ _ def mul_neg [has_mul α] [has_neg α] [class.op_right_fn_homomorphism (has_mul.mul:α→α→α) (has_neg.neg:α→α) (has_neg.neg:α→α)] : ∀ (x y : α), x * -y = -(x * y) := op_right_fn_homomorphism _ _ _ def mul_lmul [has_lmul α β] [has_mul α] [class.op_left_compatible (has_lmul.lmul:α→β→β) (has_mul.mul:α→α→α)] : ∀ (x y : α) (z : β), (x * y) ∙ z = x ∙ (y ∙ z) := op_left_compatible _ _ def lmul_lmul [has_lmul α β] [has_lmul α α] [class.op_left_compatible (has_lmul.lmul:α→β→β) (has_lmul.lmul:α→α→α)] : ∀ (x y : α) (z : β), (x ∙ y) ∙ z = x ∙ (y ∙ z) := op_left_compatible _ _ def lmul_assoc [has_lmul α α] [class.op_associative (has_lmul.lmul:α→α→α)] : ∀ (x y z : α), (x ∙ y) ∙ z = x ∙ (y ∙ z) := op_associative _ def lmul_comm [has_lmul α α] [class.op_commutative (has_lmul.lmul:α→α→α)] : ∀ (x y : α), x ∙ y = y ∙ x := op_commutative _ def lmul_left_comm [has_lmul α β] [class.op_left_commutative (has_lmul.lmul:α→β→β)] : ∀ (x y : α) (z : β), x ∙ (y ∙ z) = y ∙ (x ∙ z) := op_left_commutative _ def lmul_right_comm [has_lmul α α] [class.op_right_commutative (has_lmul.lmul:α→α→α)] : ∀ (x y z : α), (x ∙ y) ∙ z = (x ∙ z) ∙ y := op_right_commutative _ def one_lmul [has_lmul α β] [has_one α] [class.op_left_identity (has_lmul.lmul:α→β→β) (has_one.one α)] : ∀ (x : β), (1:α) ∙ x = x := op_left_identity _ _ def lmul_one [has_lmul α α] [has_one α] [class.op_right_identity (has_lmul.lmul:α→α→α) (has_one.one α)] : ∀ (x : α), x ∙ 1 = x := op_right_identity _ _ def zero_lmul [has_lmul α α] [has_zero α] [class.op_left_fixpoint (has_lmul.lmul:α→α→α) (has_zero.zero α)] : ∀ (x : α), (0:α) ∙ x = 0 := op_left_fixpoint _ _ def lmul_zero [has_lmul α β] [has_zero β] [class.op_right_fixpoint (has_lmul.lmul:α→β→β) (has_zero.zero β)] : ∀ (x : α), x ∙ (0:β) = 0 := op_right_fixpoint _ _ def inv_lmul_self [has_lmul α α] [has_inv α] [has_one α] [class.op_left_inverse (has_lmul.lmul:α→α→α) (has_inv.inv:α→α) (has_one.one α)] : ∀ (x : α), x⁻¹ ∙ x = 1 := op_left_inverse _ _ _ def lmul_inv_self [has_lmul α α] [has_inv α] [has_one α] [class.op_right_inverse (has_lmul.lmul:α→α→α) (has_inv.inv:α→α) (has_one.one α)] : ∀ (x : α), x ∙ x⁻¹ = 1 := op_right_inverse _ _ _ def inv_lmul [has_lmul α α] [has_inv α] [class.fn_op_homomorphism (has_inv.inv:α→α) (has_lmul.lmul:α→α→α) (has_lmul.lmul:α→α→α)] : ∀ (x y : α), (x ∙ y)⁻¹ = x⁻¹ ∙ y⁻¹ := fn_op_homomorphism _ _ _ def inv_lmul_rev [has_lmul α α] [has_inv α] [class.fn_op_antimorphism (has_inv.inv:α→α) (has_lmul.lmul:α→α→α) (has_lmul.lmul:α→α→α)] : ∀ (x y : α), (x ∙ y)⁻¹ = y⁻¹ ∙ x⁻¹ := fn_op_antimorphism _ _ _ def neg_lmul [has_lmul α β] [has_neg α] [has_neg β] [class.op_left_fn_homomorphism (has_lmul.lmul:α→β→β) (has_neg.neg:α→α) (has_neg.neg:β→β)] : ∀ (x : α) (y : β), -x ∙ y = -(x ∙ y) := op_left_fn_homomorphism _ _ _ def lmul_neg [has_lmul α β] [has_neg β] [class.op_right_fn_homomorphism (has_lmul.lmul:α→β→β) (has_neg.neg:β→β) (has_neg.neg:β→β)] : ∀ (x : α) (y : β), x ∙ -y = -(x ∙ y) := op_right_fn_homomorphism _ _ _ end algebra
0fbb466d1e24f125744927cd454d4b0129909293
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/game_auto.lean
401493d1533d11999c3bffb27c949edd38916c9e
[]
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
6,332
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.pgame import Mathlib.PostPort universes u_1 u namespace Mathlib /-! # Combinatorial games. In this file we define the quotient of pre-games by the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`, and construct an instance `add_comm_group game`, as well as an instance `partial_order game` (although note carefully the warning that the `<` field in this instance is not the usual relation on combinatorial games). -/ protected instance pgame.setoid : setoid pgame := setoid.mk (fun (x y : pgame) => pgame.equiv x y) sorry /-- The type of combinatorial games. In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a combinatorial pre-game is built inductively from two families of combinatorial games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. A combinatorial game is then constructed by quotienting by the equivalence `x ≈ y ↔ x ≤ y ∧ y ≤ x`. -/ def game := quotient pgame.setoid namespace game /-- The relation `x ≤ y` on games. -/ def le : game → game → Prop := quotient.lift₂ (fun (x y : pgame) => x ≤ y) sorry protected instance has_le : HasLessEq game := { LessEq := le } theorem le_refl (x : game) : x ≤ x := quot.induction_on x fun (x : pgame) => pgame.le_refl x theorem le_trans (x : game) (y : game) (z : game) : x ≤ y → y ≤ z → x ≤ z := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => quot.induction_on z fun (z : pgame) => pgame.le_trans theorem le_antisymm (x : game) (y : game) : x ≤ y → y ≤ x → x = y := sorry /-- The relation `x < y` on games. -/ -- We don't yet make this into an instance, because it will conflict with the (incorrect) notion -- of `<` provided by `partial_order` later. def lt : game → game → Prop := quotient.lift₂ (fun (x y : pgame) => x < y) sorry theorem not_le {x : game} {y : game} : ¬x ≤ y ↔ lt y x := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => pgame.not_le protected instance has_zero : HasZero game := { zero := quotient.mk 0 } protected instance inhabited : Inhabited game := { default := 0 } protected instance has_one : HasOne game := { one := quotient.mk 1 } /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : game → game := Quot.lift (fun (x : pgame) => quotient.mk (-x)) sorry protected instance has_neg : Neg game := { neg := neg } /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add : game → game → game := quotient.lift₂ (fun (x y : pgame) => quotient.mk (x + y)) sorry protected instance has_add : Add game := { add := add } theorem add_assoc (x : game) (y : game) (z : game) : x + y + z = x + (y + z) := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => quot.induction_on z fun (z : pgame) => quot.sound pgame.add_assoc_equiv protected instance add_semigroup : add_semigroup game := add_semigroup.mk Add.add add_assoc theorem add_zero (x : game) : x + 0 = x := quot.induction_on x fun (x : pgame) => quot.sound (pgame.add_zero_equiv x) theorem zero_add (x : game) : 0 + x = x := quot.induction_on x fun (x : pgame) => quot.sound (pgame.zero_add_equiv x) protected instance add_monoid : add_monoid game := add_monoid.mk add_semigroup.add add_semigroup.add_assoc 0 zero_add add_zero theorem add_left_neg (x : game) : -x + x = 0 := quot.induction_on x fun (x : pgame) => quot.sound pgame.add_left_neg_equiv protected instance add_group : add_group game := add_group.mk add_monoid.add add_monoid.add_assoc add_monoid.zero add_monoid.zero_add add_monoid.add_zero Neg.neg (sub_neg_monoid.sub._default add_monoid.add add_monoid.add_assoc add_monoid.zero add_monoid.zero_add add_monoid.add_zero Neg.neg) add_left_neg theorem add_comm (x : game) (y : game) : x + y = y + x := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => quot.sound pgame.add_comm_equiv protected instance add_comm_semigroup : add_comm_semigroup game := add_comm_semigroup.mk add_semigroup.add add_semigroup.add_assoc add_comm protected instance add_comm_group : add_comm_group game := add_comm_group.mk add_comm_semigroup.add add_comm_semigroup.add_assoc add_group.zero add_group.zero_add add_group.add_zero add_group.neg add_group.sub add_group.add_left_neg add_comm_semigroup.add_comm theorem add_le_add_left (a : game) (b : game) : a ≤ b → ∀ (c : game), c + a ≤ c + b := sorry -- While it is very tempting to define a `partial_order` on games, and prove -- that games form an `ordered_add_comm_group`, it is a bit dangerous. -- The relations `≤` and `<` on games do not satisfy -- `lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)` -- (Consider `a = 0`, `b = star`.) -- (`lt_iff_le_not_le` is satisfied by surreal numbers, however.) -- Thus we can not use `<` when defining a `partial_order`. -- Because of this issue, we define the `partial_order` and `ordered_add_comm_group` instances, -- but do not actually mark them as instances, for safety. /-- The `<` operation provided by this partial order is not the usual `<` on games! -/ def game_partial_order : partial_order game := partial_order.mk LessEq (preorder.lt._default LessEq) le_refl le_trans le_antisymm /-- The `<` operation provided by this `ordered_add_comm_group` is not the usual `<` on games! -/ def ordered_add_comm_group_game : ordered_add_comm_group game := ordered_add_comm_group.mk add_comm_group.add add_comm_group.add_assoc add_comm_group.zero add_comm_group.zero_add add_comm_group.add_zero add_comm_group.neg add_comm_group.sub add_comm_group.add_left_neg add_comm_group.add_comm partial_order.le partial_order.lt partial_order.le_refl partial_order.le_trans partial_order.le_antisymm add_le_add_left end Mathlib
d6700e9bc6073a0adb153ac9904675b6ab1ff554
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/integral/divergence_theorem.lean
251b3b2f3d9486f14624239cc9981df93c6067f6
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
30,346
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.divergence_theorem import analysis.box_integral.integrability import measure_theory.integral.interval_integral import data.set.intervals.monotone /-! # Divergence theorem for Bochner integral In this file we prove the Divergence theorem for Bochner integral on a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`. More precisely, we prove the following theorem. Let `E` be a complete normed space with second countably topology. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is continuous on a rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, differentiable on its interior with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹`, and the divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriate signs. Moreover, the same is true if the function is not differentiable at countably many points of the interior of `[a, b]`. Once we prove the general theorem, we deduce corollaries for functions `ℝ → E` and pairs of functions `(ℝ × ℝ) → E`. ## Notations We use the following local notation to make the statement more readable. Note that the documentation website shows the actual terms, not those abbreviated using local notations. * `ℝⁿ`, `ℝⁿ⁺¹`, `Eⁿ⁺¹`: `fin n → ℝ`, `fin (n + 1) → ℝ`, `fin (n + 1) → E`; * `face i`: the `i`-th face of the box `[a, b]` as a closed segment in `ℝⁿ`, namely `[a ∘ fin.succ_above i, b ∘ fin.succ_above i]`; * `e i` : `i`-th basis vector `pi.single i 1`; * `front_face i`, `back_face i`: embeddings `ℝⁿ → ℝⁿ⁺¹` corresponding to the front face `{x | x i = b i}` and back face `{x | x i = a i}` of the box `[a, b]`, respectively. They are given by `fin.insert_nth i (b i)` and `fin.insert_nth i (a i)`. ## TODO * Add a version that assumes existence and integrability of partial derivatives. ## Tags divergence theorem, Bochner integral -/ open set finset topological_space function box_integral measure_theory filter open_locale big_operators classical topological_space interval universes u namespace measure_theory variables {E : Type u} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [second_countable_topology E] [complete_space E] section variables {n : ℕ} local notation `ℝⁿ` := fin n → ℝ local notation `ℝⁿ⁺¹` := fin (n + 1) → ℝ local notation `Eⁿ⁺¹` := fin (n + 1) → E local notation `e` i := pi.single i 1 section /-! ### Divergence theorem for functions on `ℝⁿ⁺¹ = fin (n + 1) → ℝ`. In this section we use the divergence theorem for a Henstock-Kurzweil-like integral `box_integral.has_integral_bot_divergence_of_forall_has_deriv_within_at` to prove the divergence theorem for Bochner integral. The divergence theorem for Bochner integral `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable` assumes that the function itself is continuous on a closed box, differentiable at all but countably many points of its interior, and the divergence is integrable on the box. This statement differs from `box_integral.has_integral_bot_divergence_of_forall_has_deriv_within_at` in several aspects. * We use Bochner integral instead of a Henstock-Kurzweil integral. This modification is done in `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable_aux₁`. As a side effect of this change, we need to assume that the divergence is integrable. * We don't assume differentiability on the boundary of the box. This modification is done in `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable_aux₂`. To prove it, we choose an increasing sequence of smaller boxes that cover the interior of the original box, then apply the previous lemma to these smaller boxes and take the limit of both sides of the equation. * We assume `a ≤ b` instead of `∀ i, a i < b i`. This is the last step of the proof, and it is done in the main theorem `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable`. -/ /-- An auxiliary lemma for `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable`. This is exactly `box_integral.has_integral_bot_divergence_of_forall_has_deriv_within_at` reformulated for the Bochner integral. -/ lemma integral_divergence_of_has_fderiv_within_at_off_countable_aux₁ (I : box (fin (n + 1))) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : countable s) (Hc : continuous_on f I.Icc) (Hd : ∀ x ∈ I.Icc \ s, has_fderiv_within_at f (f' x) I.Icc x) (Hi : integrable_on (λ x, ∑ i, f' x (e i) i) I.Icc) : ∫ x in I.Icc, ∑ i, f' x (e i) i = ∑ i : fin (n + 1), ((∫ x in (I.face i).Icc, f (i.insert_nth (I.upper i) x) i) - ∫ x in (I.face i).Icc, f (i.insert_nth (I.lower i) x) i) := begin simp only [← set_integral_congr_set_ae (box.coe_ae_eq_Icc _)], have A := ((Hi.mono_set box.coe_subset_Icc).has_box_integral ⊥ rfl), have B := has_integral_bot_divergence_of_forall_has_deriv_within_at I f f' (s ∩ I.Icc) (hs.mono (inter_subset_left _ _)) (λ x hx, Hc _ hx.2) (λ x hx, Hd _ ⟨hx.1, λ h, hx.2 ⟨h, hx.1⟩⟩), rw continuous_on_pi at Hc, refine (A.unique B).trans (sum_congr rfl $ λ i hi, _), refine congr_arg2 has_sub.sub _ _, { have := box.continuous_on_face_Icc (Hc i) (set.right_mem_Icc.2 (I.lower_le_upper i)), have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc, exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance }, { have := box.continuous_on_face_Icc (Hc i) (set.left_mem_Icc.2 (I.lower_le_upper i)), have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc, exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance } end /-- An auxiliary lemma for `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable`. Compared to the previous lemma, here we drop the assumption of differentiability on the boundary of the box. -/ lemma integral_divergence_of_has_fderiv_within_at_off_countable_aux₂ (I : box (fin (n + 1))) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : countable s) (Hc : continuous_on f I.Icc) (Hd : ∀ x ∈ I.Ioo \ s, has_fderiv_at f (f' x) x) (Hi : integrable_on (λ x, ∑ i, f' x (e i) i) I.Icc) : ∫ x in I.Icc, ∑ i, f' x (e i) i = ∑ i : fin (n + 1), ((∫ x in (I.face i).Icc, f (i.insert_nth (I.upper i) x) i) - ∫ x in (I.face i).Icc, f (i.insert_nth (I.lower i) x) i) := begin /- Choose a monotone sequence `J k` of subboxes that cover the interior of `I` and prove that these boxes satisfy the assumptions of the previous lemma. -/ rcases I.exists_seq_mono_tendsto with ⟨J, hJ_sub, hJl, hJu⟩, have hJ_sub' : ∀ k, (J k).Icc ⊆ I.Icc, from λ k, (hJ_sub k).trans I.Ioo_subset_Icc, have hJ_le : ∀ k, J k ≤ I, from λ k, box.le_iff_Icc.2 (hJ_sub' k), have HcJ : ∀ k, continuous_on f (J k).Icc, from λ k, Hc.mono (hJ_sub' k), have HdJ : ∀ k (x ∈ (J k).Icc \ s), has_fderiv_within_at f (f' x) (J k).Icc x, from λ k x hx, (Hd x ⟨hJ_sub k hx.1, hx.2⟩).has_fderiv_within_at, have HiJ : ∀ k, integrable_on (λ x, ∑ i, f' x (e i) i) (J k).Icc, from λ k, Hi.mono_set (hJ_sub' k), -- Apply the previous lemma to `J k`. have HJ_eq := λ k, integral_divergence_of_has_fderiv_within_at_off_countable_aux₁ (J k) f f' s hs (HcJ k) (HdJ k) (HiJ k), /- Note that the LHS of `HJ_eq k` tends to the LHS of the goal as `k → ∞`. -/ have hI_tendsto : tendsto (λ k, ∫ x in (J k).Icc, ∑ i, f' x (e i) i) at_top (𝓝 (∫ x in I.Icc, ∑ i, f' x (e i) i)), { simp only [integrable_on, ← measure.restrict_congr_set (box.Ioo_ae_eq_Icc _)] at Hi ⊢, rw ← box.Union_Ioo_of_tendsto J.monotone hJl hJu at Hi ⊢, exact tendsto_set_integral_of_monotone (λ k, (J k).measurable_set_Ioo) (box.Ioo.comp J).monotone Hi }, /- Thus it suffices to prove the same about the RHS. -/ refine tendsto_nhds_unique_of_eventually_eq hI_tendsto _ (eventually_of_forall HJ_eq), clear hI_tendsto, rw tendsto_pi_nhds at hJl hJu, /- We'll need to prove a similar statement about the integrals over the front sides and the integrals over the back sides. In order to avoid repeating ourselves, we formulate a lemma. -/ suffices : ∀ (i : fin (n + 1)) (c : ℕ → ℝ) d, (∀ k, c k ∈ Icc (I.lower i) (I.upper i)) → tendsto c at_top (𝓝 d) → tendsto (λ k, ∫ x in ((J k).face i).Icc, f (i.insert_nth (c k) x) i) at_top (𝓝 $ ∫ x in (I.face i).Icc, f (i.insert_nth d x) i), { rw box.Icc_eq_pi at hJ_sub', refine tendsto_finset_sum _ (λ i hi, (this _ _ _ _ (hJu _)).sub (this _ _ _ _ (hJl _))), exacts [λ k, hJ_sub' k (J k).upper_mem_Icc _ trivial, λ k, hJ_sub' k (J k).lower_mem_Icc _ trivial] }, intros i c d hc hcd, /- First we prove that the integrals of the restriction of `f` to `{x | x i = d}` over increasing boxes `((J k).face i).Icc` tend to the desired limit. The proof mostly repeats the one above. -/ have hd : d ∈ Icc (I.lower i) (I.upper i), from is_closed_Icc.mem_of_tendsto hcd (eventually_of_forall hc), have Hic : ∀ k, integrable_on (λ x, f (i.insert_nth (c k) x) i) (I.face i).Icc, from λ k, (box.continuous_on_face_Icc ((continuous_apply i).comp_continuous_on Hc) (hc k)).integrable_on_Icc, have Hid : integrable_on (λ x, f (i.insert_nth d x) i) (I.face i).Icc, from (box.continuous_on_face_Icc ((continuous_apply i).comp_continuous_on Hc) hd).integrable_on_Icc, have H : tendsto (λ k, ∫ x in ((J k).face i).Icc, f (i.insert_nth d x) i) at_top (𝓝 $ ∫ x in (I.face i).Icc, f (i.insert_nth d x) i), { have hIoo : (⋃ k, ((J k).face i).Ioo) = (I.face i).Ioo, from box.Union_Ioo_of_tendsto ((box.monotone_face i).comp J.monotone) (tendsto_pi_nhds.2 (λ _, hJl _)) (tendsto_pi_nhds.2 (λ _, hJu _)), simp only [integrable_on, ← measure.restrict_congr_set (box.Ioo_ae_eq_Icc _), ← hIoo] at Hid ⊢, exact tendsto_set_integral_of_monotone (λ k, ((J k).face i).measurable_set_Ioo) (box.Ioo.monotone.comp ((box.monotone_face i).comp J.monotone)) Hid }, /- Thus it suffices to show that the distance between the integrals of the restrictions of `f` to `{x | x i = c k}` and `{x | x i = d}` over `((J k).face i).Icc` tends to zero as `k → ∞`. Choose `ε > 0`. -/ refine H.congr_dist (metric.nhds_basis_closed_ball.tendsto_right_iff.2 (λ ε εpos, _)), have hvol_pos : ∀ J : box (fin n), 0 < ∏ j, (J.upper j - J.lower j), from λ J, (prod_pos $ λ j hj, sub_pos.2 $ J.lower_lt_upper _), /- Choose `δ > 0` such that for any `x y ∈ I.Icc` at distance at most `δ`, the distance between `f x` and `f y` is at most `ε / volume (I.face i).Icc`, then the distance between the integrals is at most `(ε / volume (I.face i).Icc) * volume ((J k).face i).Icc ≤ ε`. -/ rcases metric.uniform_continuous_on_iff_le.1 (I.is_compact_Icc.uniform_continuous_on_of_continuous Hc) (ε / ∏ j, ((I.face i).upper j - (I.face i).lower j)) (div_pos εpos (hvol_pos (I.face i))) with ⟨δ, δpos, hδ⟩, refine (hcd.eventually (metric.ball_mem_nhds _ δpos)).mono (λ k hk, _), have Hsub : ((J k).face i).Icc ⊆ (I.face i).Icc, from box.le_iff_Icc.1 (box.face_mono (hJ_le _) i), rw [mem_closed_ball_zero_iff, real.norm_eq_abs, abs_of_nonneg dist_nonneg, dist_eq_norm, ← integral_sub (Hid.mono_set Hsub) ((Hic _).mono_set Hsub)], calc ∥(∫ x in ((J k).face i).Icc, f (i.insert_nth d x) i - f (i.insert_nth (c k) x) i)∥ ≤ (ε / ∏ j, ((I.face i).upper j - (I.face i).lower j)) * (volume ((J k).face i).Icc).to_real : begin refine norm_set_integral_le_of_norm_le_const' (((J k).face i).measure_Icc_lt_top _) ((J k).face i).measurable_set_Icc (λ x hx, _), rw ← dist_eq_norm, calc dist (f (i.insert_nth d x) i) (f (i.insert_nth (c k) x) i) ≤ dist (f (i.insert_nth d x)) (f (i.insert_nth (c k) x)) : dist_le_pi_dist (f (i.insert_nth d x)) (f (i.insert_nth (c k) x)) i ... ≤ (ε / ∏ j, ((I.face i).upper j - (I.face i).lower j)) : hδ _ (I.maps_to_insert_nth_face_Icc hd $ Hsub hx) _ (I.maps_to_insert_nth_face_Icc (hc _) $ Hsub hx) _, rw [fin.dist_insert_nth_insert_nth, dist_self, dist_comm], exact max_le hk.le δpos.lt.le end ... ≤ ε : begin rw [box.Icc_def, real.volume_Icc_pi_to_real ((J k).face i).lower_le_upper, ← le_div_iff (hvol_pos _)], refine div_le_div_of_le_left εpos.le (hvol_pos _) (prod_le_prod (λ j hj, _) (λ j hj, _)), exacts [sub_nonneg.2 (box.lower_le_upper _ _), sub_le_sub ((hJ_sub' _ (J _).upper_mem_Icc).2 _) ((hJ_sub' _ (J _).lower_mem_Icc).1 _)] end end variables (a b : ℝⁿ⁺¹) local notation `face` i := set.Icc (a ∘ fin.succ_above i) (b ∘ fin.succ_above i) local notation `front_face` i:2000 := fin.insert_nth i (b i) local notation `back_face` i:2000 := fin.insert_nth i (a i) /-- **Divergence theorem** for Bochner integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is continuous on a rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, is differentiable on its interior with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriat signs. Moreover, the same is true if the function is not differentiable at countably many points of the interior of `[a, b]`. We represent both faces `x i = a i` and `x i = b i` as the box `face i = [a ∘ fin.succ_above i, b ∘ fin.succ_above i]` in `ℝⁿ`, where `fin.succ_above : fin n ↪o fin (n + 1)` is the order embedding with range `{i}ᶜ`. The restrictions of `f : ℝⁿ⁺¹ → Eⁿ⁺¹` to these faces are given by `f ∘ back_face i` and `f ∘ front_face i`, where `back_face i = fin.insert_nth i (a i)` and `front_face i = fin.insert_nth i (b i)` are embeddings `ℝⁿ → ℝⁿ⁺¹` that take `y : ℝⁿ` and insert `a i` (resp., `b i`) as `i`-th coordinate. -/ lemma integral_divergence_of_has_fderiv_within_at_off_countable (hle : a ≤ b) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : countable s) (Hc : continuous_on f (Icc a b)) (Hd : ∀ x ∈ set.pi univ (λ i, Ioo (a i) (b i)) \ s, has_fderiv_at f (f' x) x) (Hi : integrable_on (λ x, ∑ i, f' x (e i) i) (Icc a b)) : ∫ x in Icc a b, ∑ i, f' x (e i) i = ∑ i : fin (n + 1), ((∫ x in face i, f (front_face i x) i) - ∫ x in face i, f (back_face i x) i) := begin rcases em (∃ i, a i = b i) with ⟨i, hi⟩|hne, { /- First we sort out the trivial case `∃ i, a i = b i`. -/ simp only [volume_pi, ← set_integral_congr_set_ae measure.univ_pi_Ioc_ae_eq_Icc], have hi' : Ioc (a i) (b i) = ∅ := Ioc_eq_empty hi.not_lt, have : pi set.univ (λ j, Ioc (a j) (b j)) = ∅, from univ_pi_eq_empty hi', rw [this, integral_empty, sum_eq_zero], rintro j -, rcases eq_or_ne i j with rfl|hne, { simp [hi] }, { rcases fin.exists_succ_above_eq hne with ⟨i, rfl⟩, have : pi set.univ (λ k : fin n, Ioc (a $ j.succ_above k) (b $ j.succ_above k)) = ∅, from univ_pi_eq_empty hi', rw [this, integral_empty, integral_empty, sub_self] } }, { /- In the non-trivial case `∀ i, a i < b i`, we apply a lemma we proved above. -/ have hlt : ∀ i, a i < b i, from λ i, (hle i).lt_of_ne (λ hi, hne ⟨i, hi⟩), convert integral_divergence_of_has_fderiv_within_at_off_countable_aux₂ ⟨a, b, hlt⟩ f f' s hs Hc Hd Hi } end /-- **Divergence theorem** for a family of functions `f : fin (n + 1) → ℝⁿ⁺¹ → E`. See also `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable'` for a version formulated in terms of a vector-valued function `f : ℝⁿ⁺¹ → Eⁿ⁺¹`. -/ lemma integral_divergence_of_has_fderiv_within_at_off_countable' (hle : a ≤ b) (f : fin (n + 1) → ℝⁿ⁺¹ → E) (f' : fin (n + 1) → ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] E) (s : set ℝⁿ⁺¹) (hs : countable s) (Hc : ∀ i, continuous_on (f i) (Icc a b)) (Hd : ∀ (x ∈ pi set.univ (λ i, Ioo (a i) (b i)) \ s) i, has_fderiv_at (f i) (f' i x) x) (Hi : integrable_on (λ x, ∑ i, f' i x (e i)) (Icc a b)) : ∫ x in Icc a b, ∑ i, f' i x (e i) = ∑ i : fin (n + 1), ((∫ x in face i, f i (front_face i x)) - ∫ x in face i, f i (back_face i x)) := integral_divergence_of_has_fderiv_within_at_off_countable a b hle (λ x i, f i x) (λ x, continuous_linear_map.pi (λ i, f' i x)) s hs (continuous_on_pi.2 Hc) (λ x hx, has_fderiv_at_pi.2 (Hd x hx)) Hi end /-- An auxiliary lemma that is used to specialize the general divergence theorem to spaces that do not have the form `fin n → ℝ`. -/ lemma integral_divergence_of_has_fderiv_within_at_off_countable_of_equiv {F : Type*} [normed_group F] [normed_space ℝ F] [partial_order F] [measure_space F] [borel_space F] (eL : F ≃L[ℝ] ℝⁿ⁺¹) (he_ord : ∀ x y, eL x ≤ eL y ↔ x ≤ y) (he_vol : measure_preserving eL volume volume) (f : fin (n + 1) → F → E) (f' : fin (n + 1) → F → F →L[ℝ] E) (s : set F) (hs : countable s) (a b : F) (hle : a ≤ b) (Hc : ∀ i, continuous_on (f i) (Icc a b)) (Hd : ∀ (x ∈ interior (Icc a b) \ s) i, has_fderiv_at (f i) (f' i x) x) (DF : F → E) (hDF : ∀ x, DF x = ∑ i, f' i x (eL.symm $ e i)) (Hi : integrable_on DF (Icc a b)) : ∫ x in Icc a b, DF x = ∑ i : fin (n + 1), ((∫ x in Icc (eL a ∘ i.succ_above) (eL b ∘ i.succ_above), f i (eL.symm $ i.insert_nth (eL b i) x)) - (∫ x in Icc (eL a ∘ i.succ_above) (eL b ∘ i.succ_above), f i (eL.symm $ i.insert_nth (eL a i) x))) := have he_emb : measurable_embedding eL := eL.to_homeomorph.to_measurable_equiv.measurable_embedding, have hIcc : eL ⁻¹' (Icc (eL a) (eL b)) = Icc a b, by { ext1 x, simp only [set.mem_preimage, set.mem_Icc, he_ord] }, have hIcc' : Icc (eL a) (eL b) = eL.symm ⁻¹' (Icc a b), by rw [← hIcc, eL.symm_preimage_preimage], calc ∫ x in Icc a b, DF x = ∫ x in Icc a b, ∑ i, f' i x (eL.symm $ e i) : by simp only [hDF] ... = ∫ x in Icc (eL a) (eL b), ∑ i, f' i (eL.symm x) (eL.symm $ e i) : begin rw [← he_vol.set_integral_preimage_emb he_emb], simp only [hIcc, eL.symm_apply_apply] end ... = ∑ i : fin (n + 1), ((∫ x in Icc (eL a ∘ i.succ_above) (eL b ∘ i.succ_above), f i (eL.symm $ i.insert_nth (eL b i) x)) - (∫ x in Icc (eL a ∘ i.succ_above) (eL b ∘ i.succ_above), f i (eL.symm $ i.insert_nth (eL a i) x))) : begin convert integral_divergence_of_has_fderiv_within_at_off_countable' (eL a) (eL b) ((he_ord _ _).2 hle) (λ i x, f i (eL.symm x)) (λ i x, f' i (eL.symm x) ∘L (eL.symm : ℝⁿ⁺¹ →L[ℝ] F)) (eL.symm ⁻¹' s) (hs.preimage eL.symm.injective) _ _ _, { refine λ i, (Hc i).comp eL.symm.continuous_on _, rw hIcc' }, { refine λ x hx i, (Hd (eL.symm x) ⟨_, hx.2⟩ i).comp x eL.symm.has_fderiv_at, rw ← hIcc, refine preimage_interior_subset_interior_preimage eL.continuous _, simp only [set.mem_preimage, eL.apply_symm_apply, ← pi_univ_Icc, interior_pi_set (finite.of_fintype _), interior_Icc], exact hx.1 }, { rw [← he_vol.integrable_on_comp_preimage he_emb, hIcc], simp [← hDF, (∘), Hi] } end end open_locale interval open continuous_linear_map (smul_right) local notation `ℝ¹` := fin 1 → ℝ local notation `ℝ²` := fin 2 → ℝ local notation `E¹` := fin 1 → E local notation `E²` := fin 2 → E /-- **Fundamental theorem of calculus, part 2**. This version assumes that `f` is continuous on the interval and is differentiable off a countable set `s`. See also * `interval_integral.integral_eq_sub_of_has_deriv_right_of_le` for a version that only assumes right differentiability of `f`; * `measure_theory.integral_eq_of_has_deriv_within_at_off_countable` for a version that works both for `a ≤ b` and `b ≤ a` at the expense of using unordered intervals instead of `set.Icc`. -/ theorem integral_eq_of_has_deriv_within_at_off_countable_of_le (f f' : ℝ → E) {a b : ℝ} (hle : a ≤ b) {s : set ℝ} (hs : countable s) (Hc : continuous_on f (Icc a b)) (Hd : ∀ x ∈ Ioo a b \ s, has_deriv_at f (f' x) x) (Hi : interval_integrable f' volume a b) : ∫ x in a..b, f' x = f b - f a := begin set e : ℝ ≃L[ℝ] ℝ¹ := (continuous_linear_equiv.fun_unique (fin 1) ℝ ℝ).symm, have e_symm : ∀ x, e.symm x = x 0 := λ x, rfl, set F' : ℝ → ℝ →L[ℝ] E := λ x, smul_right (1 : ℝ →L[ℝ] ℝ) (f' x), have hF' : ∀ x y, F' x y = y • f' x := λ x y, rfl, calc ∫ x in a..b, f' x = ∫ x in Icc a b, f' x : by simp only [interval_integral.integral_of_le hle, set_integral_congr_set_ae Ioc_ae_eq_Icc] ... = ∑ i : fin 1, ((∫ x in Icc (e a ∘ i.succ_above) (e b ∘ i.succ_above), f (e.symm $ i.insert_nth (e b i) x)) - (∫ x in Icc (e a ∘ i.succ_above) (e b ∘ i.succ_above), f (e.symm $ i.insert_nth (e a i) x))) : begin simp only [← interior_Icc] at Hd, refine integral_divergence_of_has_fderiv_within_at_off_countable_of_equiv e _ _ (λ _, f) (λ _, F') s hs a b hle (λ i, Hc) (λ x hx i, Hd x hx) _ _ _, { exact λ x y, (order_iso.fun_unique (fin 1) ℝ).symm.le_iff_le }, { exact (volume_preserving_fun_unique (fin 1) ℝ).symm }, { intro x, rw [fin.sum_univ_one, hF', e_symm, pi.single_eq_same, one_smul] }, { rw [interval_integrable_iff_integrable_Ioc_of_le hle] at Hi, exact Hi.congr_set_ae Ioc_ae_eq_Icc.symm } end ... = f b - f a : begin simp only [fin.sum_univ_one, e_symm], have : ∀ (c : ℝ), const (fin 0) c = is_empty_elim := λ c, subsingleton.elim _ _, simp [this, volume_pi, measure.pi_of_empty (λ _ : fin 0, volume)] end end /-- **Fundamental theorem of calculus, part 2**. This version assumes that `f` is continuous on the interval and is differentiable off a countable set `s`. See also `measure_theory.interval_integral.integral_eq_sub_of_has_deriv_right` for a version that only assumes right differentiability of `f`. -/ theorem integral_eq_of_has_deriv_within_at_off_countable (f f' : ℝ → E) {a b : ℝ} {s : set ℝ} (hs : countable s) (Hc : continuous_on f [a, b]) (Hd : ∀ x ∈ Ioo (min a b) (max a b) \ s, has_deriv_at f (f' x) x) (Hi : interval_integrable f' volume a b) : ∫ x in a..b, f' x = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le hab, min_eq_left hab, max_eq_right hab] at *, exact integral_eq_of_has_deriv_within_at_off_countable_of_le f f' hab hs Hc Hd Hi }, { simp only [interval_of_ge hab, min_eq_right hab, max_eq_left hab] at *, rw [interval_integral.integral_symm, neg_eq_iff_neg_eq, neg_sub, eq_comm], exact integral_eq_of_has_deriv_within_at_off_countable_of_le f f' hab hs Hc Hd Hi.symm } end /-- **Divergence theorem** for functions on the plane along rectangles. It is formulated in terms of two functions `f g : ℝ × ℝ → E` and an integral over `Icc a b = [a.1, b.1] × [a.2, b.2]`, where `a b : ℝ × ℝ`, `a ≤ b`. When thinking of `f` and `g` as the two coordinates of a single function `F : ℝ × ℝ → E × E` and when `E = ℝ`, this is the usual statement that the integral of the divergence of `F` inside the rectangle equals the integral of the normal derivative of `F` along the boundary. See also `measure_theory.integral2_divergence_prod_of_has_fderiv_within_at_off_countable` for a version that does not assume `a ≤ b` and uses iterated interval integral instead of the integral over `Icc a b`. -/ lemma integral_divergence_prod_Icc_of_has_fderiv_within_at_off_countable_of_le (f g : ℝ × ℝ → E) (f' g' : ℝ × ℝ → ℝ × ℝ →L[ℝ] E) (a b : ℝ × ℝ) (hle : a ≤ b) (s : set (ℝ × ℝ)) (hs : countable s) (Hcf : continuous_on f (Icc a b)) (Hcg : continuous_on g (Icc a b)) (Hdf : ∀ x ∈ Ioo a.1 b.1 ×ˢ Ioo a.2 b.2 \ s, has_fderiv_at f (f' x) x) (Hdg : ∀ x ∈ Ioo a.1 b.1 ×ˢ Ioo a.2 b.2 \ s, has_fderiv_at g (g' x) x) (Hi : integrable_on (λ x, f' x (1, 0) + g' x (0, 1)) (Icc a b)) : ∫ x in Icc a b, f' x (1, 0) + g' x (0, 1) = (∫ x in a.1..b.1, g (x, b.2)) - (∫ x in a.1..b.1, g (x, a.2)) + (∫ y in a.2..b.2, f (b.1, y)) - ∫ y in a.2..b.2, f (a.1, y) := let e : (ℝ × ℝ) ≃L[ℝ] ℝ² := (continuous_linear_equiv.fin_two_arrow ℝ ℝ).symm in calc ∫ x in Icc a b, f' x (1, 0) + g' x (0, 1) = ∑ i : fin 2, ((∫ x in Icc (e a ∘ i.succ_above) (e b ∘ i.succ_above), ![f, g] i (e.symm $ i.insert_nth (e b i) x)) - (∫ x in Icc (e a ∘ i.succ_above) (e b ∘ i.succ_above), ![f, g] i (e.symm $ i.insert_nth (e a i) x))) : begin refine integral_divergence_of_has_fderiv_within_at_off_countable_of_equiv e _ _ ![f, g] ![f', g'] s hs a b hle _ (λ x hx, _) _ _ Hi, { exact λ x y, (order_iso.fin_two_arrow_iso ℝ).symm.le_iff_le }, { exact (volume_preserving_fin_two_arrow ℝ).symm }, { exact fin.forall_fin_two.2 ⟨Hcf, Hcg⟩ }, { rw [Icc_prod_eq, interior_prod_eq, interior_Icc, interior_Icc] at hx, exact fin.forall_fin_two.2 ⟨Hdf x hx, Hdg x hx⟩ }, { intro x, rw fin.sum_univ_two, simp } end ... = (∫ y in Icc a.2 b.2, f (b.1, y)) - (∫ y in Icc a.2 b.2, f (a.1, y)) + ((∫ x in Icc a.1 b.1, g (x, b.2)) - ∫ x in Icc a.1 b.1, g (x, a.2)) : begin have : ∀ (a b : ℝ¹) (f : ℝ¹ → E), ∫ x in Icc a b, f x = ∫ x in Icc (a 0) (b 0), f (λ _, x), { intros a b f, convert ((volume_preserving_fun_unique (fin 1) ℝ).symm.set_integral_preimage_emb (measurable_equiv.measurable_embedding _) _ _).symm, exact ((order_iso.fun_unique (fin 1) ℝ).symm.preimage_Icc a b).symm }, simp only [fin.sum_univ_two, this], refl end ... = (∫ x in a.1..b.1, g (x, b.2)) - (∫ x in a.1..b.1, g (x, a.2)) + (∫ y in a.2..b.2, f (b.1, y)) - ∫ y in a.2..b.2, f (a.1, y) : begin simp only [interval_integral.integral_of_le hle.1, interval_integral.integral_of_le hle.2, set_integral_congr_set_ae Ioc_ae_eq_Icc], abel end /-- **Divergence theorem** for functions on the plane. It is formulated in terms of two functions `f g : ℝ × ℝ → E` and iterated integral `∫ x in a₁..b₁, ∫ y in a₂..b₂, _`, where `a₁ a₂ b₁ b₂ : ℝ`. When thinking of `f` and `g` as the two coordinates of a single function `F : ℝ × ℝ → E × E` and when `E = ℝ`, this is the usual statement that the integral of the divergence of `F` inside the rectangle with vertices `(aᵢ, bⱼ)`, `i, j =1,2`, equals the integral of the normal derivative of `F` along the boundary. See also `measure_theory.integral_divergence_prod_Icc_of_has_fderiv_within_at_off_countable_of_le` for a version that uses an integral over `Icc a b`, where `a b : ℝ × ℝ`, `a ≤ b`. -/ lemma integral2_divergence_prod_of_has_fderiv_within_at_off_countable (f g : ℝ × ℝ → E) (f' g' : ℝ × ℝ → ℝ × ℝ →L[ℝ] E) (a₁ a₂ b₁ b₂ : ℝ) (s : set (ℝ × ℝ)) (hs : countable s) (Hcf : continuous_on f ([a₁, b₁] ×ˢ [a₂, b₂])) (Hcg : continuous_on g ([a₁, b₁] ×ˢ [a₂, b₂])) (Hdf : ∀ x ∈ Ioo (min a₁ b₁) (max a₁ b₁) ×ˢ Ioo (min a₂ b₂) (max a₂ b₂) \ s, has_fderiv_at f (f' x) x) (Hdg : ∀ x ∈ Ioo (min a₁ b₁) (max a₁ b₁) ×ˢ Ioo (min a₂ b₂) (max a₂ b₂) \ s, has_fderiv_at g (g' x) x) (Hi : integrable_on (λ x, f' x (1, 0) + g' x (0, 1)) ([a₁, b₁] ×ˢ [a₂, b₂])) : ∫ x in a₁..b₁, ∫ y in a₂..b₂, f' (x, y) (1, 0) + g' (x, y) (0, 1) = (∫ x in a₁..b₁, g (x, b₂)) - (∫ x in a₁..b₁, g (x, a₂)) + (∫ y in a₂..b₂, f (b₁, y)) - ∫ y in a₂..b₂, f (a₁, y) := begin wlog h₁ : a₁ ≤ b₁ := le_total a₁ b₁ using [a₁ b₁, b₁ a₁] tactic.skip, wlog h₂ : a₂ ≤ b₂ := le_total a₂ b₂ using [a₂ b₂, b₂ a₂] tactic.skip, { simp only [interval_of_le h₁, interval_of_le h₂, min_eq_left, max_eq_right, h₁, h₂] at Hcf Hcg Hdf Hdg Hi, calc ∫ x in a₁..b₁, ∫ y in a₂..b₂, f' (x, y) (1, 0) + g' (x, y) (0, 1) = ∫ x in Icc a₁ b₁, ∫ y in Icc a₂ b₂, f' (x, y) (1, 0) + g' (x, y) (0, 1) : by simp only [interval_integral.integral_of_le, h₁, h₂, set_integral_congr_set_ae Ioc_ae_eq_Icc] ... = ∫ x in Icc a₁ b₁ ×ˢ Icc a₂ b₂, f' x (1, 0) + g' x (0, 1) : (set_integral_prod _ Hi).symm ... = (∫ x in a₁..b₁, g (x, b₂)) - (∫ x in a₁..b₁, g (x, a₂)) + (∫ y in a₂..b₂, f (b₁, y)) - ∫ y in a₂..b₂, f (a₁, y) : begin rw Icc_prod_Icc at *, apply integral_divergence_prod_Icc_of_has_fderiv_within_at_off_countable_of_le f g f' g' (a₁, a₂) (b₁, b₂) ⟨h₁, h₂⟩ s; assumption end }, { rw [interval_swap b₂ a₂, min_comm b₂ a₂, max_comm b₂ a₂] at this, intros Hcf Hcg Hdf Hdg Hi, simp only [interval_integral.integral_symm b₂ a₂, interval_integral.integral_neg], refine (congr_arg has_neg.neg (this Hcf Hcg Hdf Hdg Hi)).trans _, abel }, { rw [interval_swap b₁ a₁, min_comm b₁ a₁, max_comm b₁ a₁] at this, intros Hcf Hcg Hdf Hdg Hi, simp only [interval_integral.integral_symm b₁ a₁], refine (congr_arg has_neg.neg (this Hcf Hcg Hdf Hdg Hi)).trans _, abel } end end measure_theory
91ecbcbf6e8e46d39544699d00cb9a4e69047b3e
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/instances/rat.lean
eec32ff7596fa6decb52ac7037d91c7e9a75cb21
[ "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,203
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.instances.int import topology.instances.nat import topology.instances.real /-! # Topology on the ratonal numbers The structure of a metric space on `ℚ` is introduced in this file, induced from `ℝ`. -/ noncomputable theory open metric set filter namespace rat instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem dist_eq (x y : ℚ) : dist x y = |x - y| := rfl @[norm_cast, simp] lemma dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl theorem uniform_continuous_coe_real : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_coe_real : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_coe_real : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_coe_real.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_coe_real : embedding (coe : ℚ → ℝ) := dense_embedding_coe_real.to_embedding theorem continuous_coe_real : continuous (coe : ℚ → ℝ) := uniform_continuous_coe_real.continuous end rat @[norm_cast, simp] theorem nat.dist_cast_rat (x y : ℕ) : dist (x : ℚ) y = dist x y := by rw [← nat.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast lemma nat.uniform_embedding_coe_rat : uniform_embedding (coe : ℕ → ℚ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using nat.pairwise_one_le_dist lemma nat.closed_embedding_coe_rat : closed_embedding (coe : ℕ → ℚ) := closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using nat.pairwise_one_le_dist @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast lemma int.uniform_embedding_coe_rat : uniform_embedding (coe : ℤ → ℚ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using int.pairwise_one_le_dist lemma int.closed_embedding_coe_rat : closed_embedding (coe : ℤ → ℚ) := closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using int.pairwise_one_le_dist instance : noncompact_space ℚ := int.closed_embedding_coe_rat.noncompact_space -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := rat.uniform_embedding_coe_real.to_uniform_inducing.uniform_continuous_iff.2 $ by simp only [(∘), rat.cast_add]; exact real.uniform_continuous_add.comp (rat.uniform_continuous_coe_real.prod_map rat.uniform_continuous_coe_real) theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := rat.embedding_coe_real.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((rat.continuous_coe_real.prod_map rat.continuous_coe_real)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage rat.uniform_embedding_coe_real (totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end
3ca7e96131e8d762ce9680ba22dade48c2ac42ae
dc06cc9775d64d571bf4778459ec6fde1f344116
/src/ring_theory/noetherian.lean
25d5afb41d71654c956486787a6b82a84b9a383e
[ "Apache-2.0" ]
permissive
mgubi/mathlib
8c1ea39035776ad52cf189a7af8cc0eee7dea373
7c09ed5eec8434176fbc493e0115555ccc4c8f99
refs/heads/master
1,642,222,572,514
1,563,782,424,000
1,563,782,424,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,991
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import data.equiv.algebra import linear_algebra.finsupp import ring_theory.ideal_operations import ring_theory.subring open set lattice namespace submodule variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] def fg (s : submodule α β) : Prop := ∃ t : finset β, submodule.span α ↑t = s theorem fg_def {s : submodule α β} : s.fg ↔ ∃ t : set β, finite t ∧ span α t = s := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_coe, mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_coe, mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_coe, mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ideal.quotient.mk_one] at hr1 hc1 ⊢, rw [ideal.quotient.mk_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_coe, mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule α β).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {s₁ s₂ : submodule α β} (hs₁ : s₁.fg) (hs₂ : s₂.fg) : (s₁ ⊔ s₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hs₁, ⟨t₂, ht₂⟩ := fg_def.1 hs₂ in fg_def.2 ⟨t₁ ∪ t₂, finite_union ht₁.1 ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {γ : Type*} [add_comm_group γ] [module α γ] variables {f : β →ₗ[α] γ} theorem fg_map {s : submodule α β} (hs : s.fg) : (s.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, finite_image _ ht.1, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule α β} {sc : submodule α γ} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc, finite_union (finite_image _ htb.1) (finite_image _ htc.1), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule α β} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq α, haveI := classical.dec_eq β, haveI := classical.dec_eq γ, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : γ → β, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total β β α id).to_fun ((finsupp.lmap_domain α α g : (γ →₀ α) → β →₀ α) l), _, x - finsupp.total β β α id ((finsupp.lmap_domain α α g : (γ →₀ α) → β →₀ α) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited γ := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule class is_noetherian (α β) [ring α] [add_comm_group β] [module α β] : Prop := (noetherian : ∀ (s : submodule α β), s.fg) section variables {α : Type*} {β : Type*} {γ : Type*} variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] open is_noetherian include α theorem is_noetherian_submodule {N : submodule α β} : is_noetherian α N ↔ ∀ s : submodule α β, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule α β} : is_noetherian α N ↔ ∀ s : submodule α β, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule α β} : is_noetherian α N ↔ ∀ s : submodule α β, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (β) theorem is_noetherian_of_surjective (f : β →ₗ[α] γ) (hf : f.range = ⊤) [is_noetherian α β] : is_noetherian α γ := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {β} theorem is_noetherian_of_linear_equiv (f : β ≃ₗ[α] γ) [is_noetherian α β] : is_noetherian α γ := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian α β] [is_noetherian α γ] : is_noetherian α (β × γ) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd α β γ) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd α β γ) ≤ linear_map.range (linear_map.inl α β γ), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {α ι : Type*} {β : ι → Type*} [ring α] [Π i, add_comm_group (β i)] [Π i, module α (β i)] [fintype ι] [∀ i, is_noetherian α (β i)] : is_noetherian α (Π i, β i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian α (Π i : (↑s : set ι), β i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext i, cases i, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot α).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (β a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show β i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show β i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext i, cases i with i his, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext i, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian theorem is_noetherian_iff_well_founded {α β} [ring α] [add_comm_group β] [module α β] : is_noetherian α β ↔ well_founded ((>) : submodule α β → submodule α β → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let M := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian M) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set β), { rw [← submodule.Union_coe_of_directed _ N _], { show t ⊆ M, rw ← h₂, apply submodule.subset_span }, { apply_instance }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : M ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ M ≤ N, ∃ s, finite s ∧ M ⊔ submodule.span α s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ M, h.induction M _, intros M IH MN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ M, { cases le_antisymm MN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬M ⊔ submodule.span α {x} ≤ M, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (M ⊔ submodule.span α {x}) ⟨@le_sup_left _ _ M _, this⟩ (sup_le MN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, finite_insert _ hs, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt {α β} [ring α] [add_comm_group β] [module α β] : ∀ [is_noetherian α β], well_founded ((>) : submodule α β → submodule α β → Prop) := is_noetherian_iff_well_founded.mp @[class] def is_noetherian_ring (α) [ring α] : Prop := is_noetherian α α instance is_noetherian_ring.to_is_noetherian {α : Type*} [ring α] : ∀ [is_noetherian_ring α], is_noetherian α α := id instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [finset.coe_to_finset', submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one R h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨s.attach.sum (λ i, f i • i.1), N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change s.attach.sum (λ i, (f i + g i) • _) = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change s.attach.sum (λ i, (c • f i) • _) = _, simp only [smul_eq_mul, mul_smul], exact finset.sum_hom _ } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x.1, subtype.eq _⟩, change s.attach.sum (λ i, l i.1 • i.1) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R → S) [is_ring_hom f] (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R → S) [is_ring_hom f] [is_noetherian_ring R] : is_noetherian_ring (set.range f) := @is_noetherian_ring_of_surjective R _ (set.range f) _ (λ x, ⟨f x, x, rfl⟩) (⟨subtype.eq (is_ring_hom.map_one f), λ _ _, subtype.eq (is_ring_hom.map_mul f), λ _ _, subtype.eq (is_ring_hom.map_add f)⟩) (λ ⟨x, y, hy⟩, ⟨y, subtype.eq hy⟩) _ theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃r S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.1 f.1.surjective namespace is_noetherian_ring variables {α : Type*} [integral_domain α] [is_noetherian_ring α] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : α, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x ) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set α)) well_founded_submodule_gt lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f:multiset α, (∀b∈f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) local attribute [instance] set.pointwise_mul_semiring theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, set.pointwise_mul_finite hfm hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M^n).fg := nat.rec_on n (⟨finset.singleton 1, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
5c71350bc6297278f0831570085f7bb631765ee7
54a6e18abbdb2dc60326019200c15aec35794b37
/lean/mbair.lean
a4cd0a453ccf70928554e3906c11b321e72eaf5a
[ "MIT" ]
permissive
ahelwer/formal-methods-experiments
33326ec3f90c6595e2e215cd59981bc79c262980
d8391d6901927f17dfcb8426fceafe46605dbae9
refs/heads/master
1,692,361,742,269
1,691,080,299,000
1,691,080,299,000
218,297,227
0
0
null
null
null
null
UTF-8
Lean
false
false
3,293
lean
inductive BinTree (α : Type) where | leaf : BinTree α | branch : BinTree α → α → BinTree α → BinTree α deriving Repr def example_tree := BinTree.branch (BinTree.branch (BinTree.branch BinTree.leaf 6 BinTree.leaf) 5 (BinTree.branch BinTree.leaf 4 BinTree.leaf) ) 3 (BinTree.branch (BinTree.branch BinTree.leaf 2 BinTree.leaf) 1 (BinTree.branch BinTree.leaf 0 BinTree.leaf) ) def BinTree.enumerate (t : BinTree α) : BinTree (Nat × α) := let rec rank_from : Nat → BinTree α → Nat × BinTree (Nat × α) | n, BinTree.leaf => (n, BinTree.leaf) | n, BinTree.branch l x r => let (n, l) := rank_from n l let (n, x) := (n + 1, (n, x)) let (n, r) := rank_from n r (n, BinTree.branch l x r) let (_, t') := rank_from 0 t t' #eval example_tree.enumerate def State (σ : Type) (α : Type) : Type := σ → (σ × α) def BinTree.enumerateState (t : BinTree α) : BinTree (Nat × α) := let rec enumerate_from : BinTree α → State Nat (BinTree (Nat × α)) | BinTree.leaf => fun s => (s, BinTree.leaf) | BinTree.branch l x r => fun s => let (s, l) := (enumerate_from l) s let (s, x) := (fun s => (s + 1, (s, x))) s let (s, r) := (enumerate_from r) s (s, BinTree.branch l x r) let (_, t) := enumerate_from t 0 t #eval example_tree.enumerateState def andThen (first : State σ α) (next : α → State σ β) : State σ β := fun s => let (s', v) := first s next v s' infixl:55 " ~~> " => andThen def BinTree.enumerateAndThen (t : BinTree α) : BinTree (Nat × α) := let rec enumerate_from : BinTree α → State Nat (BinTree (Nat × α)) | BinTree.leaf => fun s => (s, BinTree.leaf) | BinTree.branch l x r => andThen (enumerate_from l) (fun sl => andThen (fun s => (s + 1, (s, x))) (fun sx => andThen (enumerate_from r) (fun sr => fun s => (s, BinTree.branch sl sx sr) ) ) ) let (_, t) := enumerate_from t 0 t #eval example_tree.enumerateAndThen def ok (x : α) : State σ α := fun s => (s, x) def get : State σ σ := fun s => (s, s) def set (s : σ) : State σ Unit := fun _ => (s, ()) def BinTree.enumerateInfix (t : BinTree α) : BinTree (Nat × α) := let rec enumerate_from : BinTree α → State Nat (BinTree (Nat × α)) | BinTree.leaf => ok BinTree.leaf | BinTree.branch l x r => enumerate_from l ~~> fun sl => get ~~> fun n => set (n + 1) ~~> fun () => enumerate_from r ~~> fun sr => ok (BinTree.branch sl (n, x) sr) (enumerate_from t 0).snd #eval example_tree.enumerateInfix instance : Monad (State σ) where pure x := fun s => (s, x) bind first next := fun s => let (s', x) := first s next x s' def BinTree.mapM [Monad m] (f : α → m β) : BinTree α → m (BinTree β) | BinTree.leaf => pure BinTree.leaf | BinTree.branch l x r => mapM f l >>= fun ml => f x >>= fun mx => mapM f r >>= fun mr => pure (BinTree.branch ml mx mr) def enumerate (v : α) : State Nat (Nat × α) := get >>= fun n => set (n + 1) >>= fun () => pure (n, v) #eval example_tree.mapM enumerate 0
f408f78a0d688407fdc2ee9cd57bd31eb7c42e71
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/module/linear_map.lean
7dc2d0f66c5323b9e3ffccc147f9f4df36810c14
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,637
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen -/ import algebra.group.hom import algebra.module.basic import algebra.group_action_hom /-! # Linear maps and linear equivalences In this file we define * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`module`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `linear_equiv R M ₂`, `M ≃ₗ[R] M₂`: an invertible linear map ## Tags linear map, linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A map `f` between modules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between modules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] extends add_hom M M₂, M →[R] M₂ end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom /-- The `mul_action_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_mul_action_hom infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [module R M] [module R M₂] /-- The `distrib_mul_action_hom` underlying a `linear_map`. -/ def to_distrib_mul_action_hom (f : M →ₗ[R] M₂) : distrib_mul_action_hom R M M₂ := { map_zero' := zero_smul R (0 : M) ▸ zero_smul R (f.to_fun 0) ▸ f.map_smul' 0 0, ..f } instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := { to_fun := id, ..distrib_mul_action_hom.id R } lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [module R M] [module R M₂] variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.map_add', f.map_smul'⟩ variables {f g} theorem coe_injective : @injective (M →ₗ[R] M₂) (M → M₂) coe_fn := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₗ[R] M₂) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) = f := ext $ λ _, rfl variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := f.to_distrib_mul_action_hom.map_zero @[simp] lemma map_eq_zero_iff (h : function.injective f) {x : M} : f x = 0 ↔ x = 0 := ⟨λ w, by { apply h, simp [w], }, λ w, by { subst w, simp, }⟩ variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] := (map_smul : ∀ (f : M →ₗ[S] M₂) (c : R) (x : M), f (c • x) = c • f x) variables {M M₂} @[priority 100] instance is_scalar_tower.compatible_smul {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [module S M] [is_scalar_tower R S M] [has_scalar R M₂] [module S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ f c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (f x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) (c : R) (x : M) : f (c • x) = c • f x := compatible_smul.map_smul f c x /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ⇑f.to_add_monoid_hom = f := rfl section restrict_scalars variables (R) [semiring S] [module S M] [module S M₂] [compatible_smul M M₂ R S] /-- If `M` and `M₂` are both `R`-modules and `S`-modules and `R`-module structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ @[simps] def restrict_scalars (f : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul_of_tower } lemma restrict_scalars_injective : function.injective (restrict_scalars R : (M →ₗ[S] M₂) → (M →ₗ[R] M₂)) := λ f g h, ext (linear_map.congr_fun h : _) @[simp] lemma restrict_scalars_inj (f g : M →ₗ[S] M₂) : f.restrict_scalars R = g.restrict_scalars R ↔ f = g := (restrict_scalars_injective R).eq_iff end restrict_scalars variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `R`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₗ[R] M} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smul, g.map_smul, h] theorem ext_ring_iff {f g : R →ₗ[R] M} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end section variables {module_M : module R M} {module_M₂ : module R M₂} {module_M₃ : module R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := { to_fun := f ∘ g, .. f.to_distrib_mul_action_hom.comp g.to_distrib_mul_action_hom } lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[simp, norm_cast] lemma coe_comp : (f.comp g : M → M₃) = f ∘ g := rfl @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl end /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [module R M] [module R M₂] (f : M →ₗ[R] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact { to_fun := g, map_add' := λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, map_smul' := λ a b, by { rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂] } } end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {module_M : module R M} {module_M₂ : module R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance compatible_smul.int_module {S : Type*} [semiring S] [module S M] [module S M₂] : compatible_smul M M₂ ℤ S := ⟨λ f c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simp [add_smul, ih] }, case hn : n ih { simp [sub_smul, ih] } end⟩ instance compatible_smul.units {R S : Type*} [monoid R] [mul_action R M] [mul_action R M₂] [semiring S] [module S M] [module S M₂] [compatible_smul M M₂ R S] : compatible_smul M M₂ (units R) S := ⟨λ f c x, (compatible_smul.map_smul f (c : R) x : _)⟩ end add_comm_group end linear_map namespace module /-- `g : R →+* S` is `R`-linear when the module structure on `S` is `module.comp_hom S g` . -/ @[simps] def comp_hom.to_linear_map {R S : Type*} [semiring R] [semiring S] (g : R →+* S) : (by haveI := comp_hom S g; exact (R →ₗ[R] S)) := by exact { to_fun := (g : R → S), map_add' := g.map_add, map_smul' := g.map_mul } end module namespace distrib_mul_action_hom variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] /-- A `distrib_mul_action_hom` between two modules is a linear map. -/ def to_linear_map (f : M →+[R] M₂) : M →ₗ[R] M₂ := { ..f } instance : has_coe (M →+[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ @[simp] lemma to_linear_map_eq_coe (f : M →+[R] M₂) : f.to_linear_map = ↑f := rfl @[simp, norm_cast] lemma coe_to_linear_map (f : M →+[R] M₂) : ((f : M →ₗ[R] M₂) : M → M₂) = f := rfl lemma to_linear_map_injective {f g : M →+[R] M₂} (h : (f : M →ₗ[R] M₂) = (g : M →ₗ[R] M₂)) : f = g := by { ext m, exact linear_map.congr_fun h m, } end distrib_mul_action_hom namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := { to_fun := f, map_add' := H.1, map_smul' := H.2 } @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [module R M] [module R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `linear_map.endomorphism_semiring` and algebra structure `module.endomorphism_algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℕ`-linear map. -/ def add_monoid_hom.to_nat_linear_map [add_comm_monoid M] [add_comm_monoid M₂] (f : M →+ M₂) : M →ₗ[ℕ] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_nat_module_smul } lemma add_monoid_hom.to_nat_linear_map_injective [add_comm_monoid M] [add_comm_monoid M₂] : function.injective (@add_monoid_hom.to_nat_linear_map M M₂ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_int_module_smul } lemma add_monoid_hom.to_int_linear_map_injective [add_comm_group M] [add_comm_group M₂] : function.injective (@add_monoid_hom.to_int_linear_map M M₂ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } @[simp] lemma add_monoid_hom.coe_to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : ⇑f.to_int_linear_map = f := rfl /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } lemma add_monoid_hom.to_rat_linear_map_injective [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] : function.injective (@add_monoid_hom.to_rat_linear_map M M₂ _ _ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } @[simp] lemma add_monoid_hom.coe_to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : ⇑f.to_rat_linear_map = f := rfl /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] extends M →ₗ[R] M₂, M ≃+ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [module R M] [module R M₂] [module R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_mk {to_fun inv_fun map_add map_smul left_inv right_inv } : ⇑(⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) = to_fun := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₗ[R] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := to_equiv_injective.eq_iff lemma to_linear_map_injective : function.injective (coe : (M ≃ₗ[R] M₂) → (M →ₗ[R] M₂)) := λ e₁ e₂ H, to_equiv_injective $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₗ[R] M₂} : (e₁ : M →ₗ[R] M₂) = e₂ ↔ e₁ = e₂ := to_linear_map_injective.eq_iff end section variables {module_M : module R M} {module_M₂ : module R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma to_linear_map_eq_coe : e.to_linear_map = ↑e := rfl @[simp, norm_cast] theorem coe_coe : ⇑(e : M →ₗ[R] M₂) = e := rfl @[simp] lemma coe_to_equiv : ⇑e.to_equiv = e := rfl @[simp] lemma coe_to_linear_map : ⇑e.to_linear_map = e := rfl @[simp] lemma to_fun_eq_coe : e.to_fun = e := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := to_equiv_injective (equiv.ext h) protected lemma congr_arg : Π {x x' : M}, x = x' → e x = e x' | _ _ rfl := rfl protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := h ▸ rfl lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := ⟨λ h x, h ▸ rfl, ext⟩ end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [module R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [module R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- See Note [custom simps projection] -/ def simps.symm_apply [module R M] [module R M₂] (e : M ≃ₗ[R] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm : e.inv_fun = e.symm := rfl variables {module_M₃ : module R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl /-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/ lemma to_add_monoid_hom_commutes : e.to_linear_map.to_add_monoid_hom = e.to_add_equiv.to_add_monoid_hom := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.right_inv c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.left_inv b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := to_equiv_injective e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := to_equiv_injective e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma refl_symm [module R M] : (refl R M).symm = linear_equiv.refl R M := rfl @[simp] lemma trans_symm [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [module R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [module R M] [module R M₂] [module R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] lemma mk_coe (h₁ h₂ f h₃ h₄) : (linear_equiv.mk e h₁ h₂ f h₃ h₄ : M ≃ₗ[R] M₂) = e := ext $ λ _, rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } lemma symm_bijective [module R M] [module R M₂] : function.bijective (symm : (M ≃ₗ[R] M₂) → (M₂ ≃ₗ[R] M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (f h₁ h₂ h₃ h₄) : (linear_equiv.mk f h₁ h₂ ⇑e h₃ h₄ : M₂ ≃ₗ[R] M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f h₁ h₂ h₃ h₄) : (⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm = { to_fun := f, inv_fun := e, ..(⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm } := rfl @[simp] lemma coe_symm_mk [module R M] [module R M₂] {to_fun inv_fun map_add map_smul left_inv right_inv} : ⇑((⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂).symm) = inv_fun := rfl protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end /-- An involutive linear map is a linear equivalence. -/ def of_involutive [module R M] (f : M →ₗ[R] M) (hf : involutive f) : M ≃ₗ[R] M := { .. f, .. hf.to_equiv f } @[simp] lemma coe_of_involutive [module R M] (f : M →ₗ[R] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl section restrict_scalars variables (R) [module R M] [module R M₂] [semiring S] [module S M] [module S M₂] [linear_map.compatible_smul M M₂ R S] /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear equivalence from `M` to `M₂` is also an `R`-linear equivalence. See also `linear_map.restrict_scalars`. -/ @[simps] def restrict_scalars (f : M ≃ₗ[S] M₂) : M ≃ₗ[R] M₂ := { to_fun := f, inv_fun := f.symm, left_inv := f.left_inv, right_inv := f.right_inv, .. f.to_linear_map.restrict_scalars R } lemma restrict_scalars_injective : function.injective (restrict_scalars R : (M ≃ₗ[S] M₂) → (M ≃ₗ[R] M₂)) := λ f g h, ext (linear_equiv.congr_fun h : _) @[simp] lemma restrict_scalars_inj (f g : M ≃ₗ[S] M₂) : f.restrict_scalars R = g.restrict_scalars R ↔ f = g := (restrict_scalars_injective R).eq_iff end restrict_scalars end add_comm_monoid end linear_equiv namespace module /-- `g : R ≃+* S` is `R`-linear when the module structure on `S` is `module.comp_hom S g` . -/ @[simps] def comp_hom.to_linear_equiv {R S : Type*} [semiring R] [semiring S] (g : R ≃+* S) : (by haveI := comp_hom S (↑g : R →+* S); exact (R ≃ₗ[R] S)) := by exact { to_fun := (g : R → S), inv_fun := (g.symm : S → R), map_smul' := g.map_mul, ..g } end module
84612b66332db7d17e1b64ddda892c80899640e4
3863d2564418bccb1859e057bf5a4ef240e75fd7
/hott/types/pi.hlean
19dd307109aaea4e16e13d6ebd50de59ce49bc95
[ "Apache-2.0" ]
permissive
JacobGross/lean
118bbb067ff4d4af48a266face2c7eb9868fa91c
eb26087df940c54337cb807b4bc6d345d1fc1085
refs/heads/master
1,582,735,011,532
1,462,557,826,000
1,462,557,826,000
46,451,196
0
0
null
1,462,557,826,000
1,447,885,161,000
C++
UTF-8
Lean
false
false
12,431
hlean
/- Copyright (c) 2014-15 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 pi-types (dependent function spaces) -/ import types.sigma arity open eq equiv is_equiv funext sigma unit bool is_trunc prod namespace pi variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ~ g]. This equivalence, however, is just the combination of [apd10] and function extensionality [funext], and as such, [eq_of_homotopy] Now we show how these things compute. -/ definition apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h := apd10 (right_inv apd10 h) definition eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p definition eq_of_homotopy_idp (f : Πa, B a) : eq_of_homotopy (λx : A, refl (f x)) = refl f := !eq_of_homotopy_eta /- homotopy.symm is an equivalence -/ definition is_equiv_homotopy_symm : is_equiv (homotopy.symm : f ~ g → g ~ f) := begin fapply adjointify homotopy.symm homotopy.symm, { intro p, apply eq_of_homotopy, intro a, unfold homotopy.symm, apply inv_inv }, { intro p, apply eq_of_homotopy, intro a, unfold homotopy.symm, apply inv_inv } end /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ definition eq_equiv_homotopy (f g : Πx, B x) : (f = g) ≃ (f ~ g) := equiv.mk apd10 _ definition pi_eq_equiv (f g : Πx, B x) : (f = g) ≃ (f ~ g) := !eq_equiv_homotopy definition is_equiv_eq_of_homotopy (f g : Πx, B x) : is_equiv (eq_of_homotopy : f ~ g → f = g) := _ definition homotopy_equiv_eq (f g : Πx, B x) : (f ~ g) ≃ (f = g) := equiv.mk eq_of_homotopy _ /- Transport -/ definition pi_transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ~ (λb, !tr_inv_tr ▸ (p ▸D (f (p⁻¹ ▸ b)))) := by induction p; reflexivity /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ definition pi_transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) (b : A') : (transport _ p f) b = p ▸ (f b) := by induction p; reflexivity /- Pathovers -/ definition pi_pathover {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[apo011 C p q] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_left {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a), f b =[apo011 C p !pathover_tr] g (p ▸ b)) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_right {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[apo011 C p !tr_pathover] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_constant {C : A → A' → Type} {f : Π(b : A'), C a b} {g : Π(b : A'), C a' b} {p : a = a'} (r : Π(b : A'), f b =[p] g b) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, exact eq_of_pathover_idp (r b), end -- a version where C is uncurried, but where the conclusion of r is still a proper pathover -- instead of a heterogenous equality definition pi_pathover' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)), end definition pi_pathover_left' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a), f b =[dpair_eq_dpair p !pathover_tr] g (p ▸ b)) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b) end definition pi_pathover_right' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[dpair_eq_dpair p !tr_pathover] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b) end /- Maps on paths -/ /- The action of maps given by lambda. -/ definition ap_lambdaD {C : A' → Type} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply eq_of_homotopy_idp end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (transport B p b)) ≃ (transport (λa, Π(b : B a), C a b) p f = g) -/ definition heq_piD (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, !homotopy_equiv_eq) g definition heq_pi {C : A → Type} (p : a = a') (f : Π(b : B a), C a) (g : Π(b' : B a'), C a') : (Π(b : B a), p ▸ (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, !homotopy_equiv_eq) g section open sigma sigma.ops /- more implicit arguments: (Π(b : B a), transport C (sigma_eq p idp) (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (transport B p b)) -/ definition heq_pi_sigma {C : (Σa, B a) → Type} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃ (Π(b : B a), p ▸D (f b) = g (p ▸ b)) := eq.rec_on p (λg, !equiv.refl) g end /- Functorial action -/ variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') /- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/ definition pi_functor [unfold_full] : (Π(a:A), B a) → (Π(a':A'), B' a') := λg a', f1 a' (g (f0 a')) definition pi_functor_left [unfold_full] (B : A → Type) : (Π(a:A), B a) → (Π(a':A'), B (f0 a')) := pi_functor f0 (λa, id) definition pi_functor_right [unfold_full] {B' : A → Type} (f1 : Π(a:A), B a → B' a) : (Π(a:A), B a) → (Π(a:A), B' a) := pi_functor id f1 definition ap_pi_functor {g g' : Π(a:A), B a} (h : g ~ g') : ap (pi_functor f0 f1) (eq_of_homotopy h) = eq_of_homotopy (λa':A', (ap (f1 a') (h (f0 a')))) := begin apply (is_equiv_rect (@apd10 A B g g')), intro p, clear h, cases p, apply concat, exact (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)), apply symm, apply eq_of_homotopy_idp end /- Equivalences -/ definition is_equiv_pi_functor [instance] [constructor] [H0 : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) := begin apply (adjointify (pi_functor f0 f1) (pi_functor f0⁻¹ (λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))), begin intro h, apply eq_of_homotopy, intro a', esimp, rewrite [adj f0 a',-tr_compose,fn_tr_eq_tr_fn _ f1,right_inv (f1 _)], apply apdt end, begin intro h, apply eq_of_homotopy, intro a, esimp, rewrite [left_inv (f1 _)], apply apdt end end definition pi_equiv_pi_of_is_equiv [constructor] [H : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : (Πa, B a) ≃ (Πa', B' a') := equiv.mk (pi_functor f0 f1) _ definition pi_equiv_pi [constructor] (f0 : A' ≃ A) (f1 : Πa', (B (to_fun f0 a') ≃ B' a')) : (Πa, B a) ≃ (Πa', B' a') := pi_equiv_pi_of_is_equiv (to_fun f0) (λa', to_fun (f1 a')) definition pi_equiv_pi_right [constructor] {P Q : A → Type} (g : Πa, P a ≃ Q a) : (Πa, P a) ≃ (Πa, Q a) := pi_equiv_pi equiv.refl g /- Equivalence if one of the types is contractible -/ definition pi_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A] : (Πa, B a) ≃ B (center A) := begin fapply equiv.MK, { intro f, exact f (center A)}, { intro b a, exact (center_eq a) ▸ b}, { intro b, rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]}, { intro f, apply eq_of_homotopy, intro a, induction (center_eq a), rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]} end definition pi_equiv_of_is_contr_right [constructor] [H : Πa, is_contr (B a)] : (Πa, B a) ≃ unit := begin fapply equiv.MK, { intro f, exact star}, { intro u a, exact !center}, { intro u, induction u, reflexivity}, { intro f, apply eq_of_homotopy, intro a, apply is_prop.elim} end /- Interaction with other type constructors -/ -- most of these are in the file of the other type constructor definition pi_empty_left [constructor] (B : empty → Type) : (Πx, B x) ≃ unit := begin fapply equiv.MK, { intro f, exact star}, { intro x y, contradiction}, { intro x, induction x, reflexivity}, { intro f, apply eq_of_homotopy, intro y, contradiction}, end definition pi_unit_left [constructor] (B : unit → Type) : (Πx, B x) ≃ B star := !pi_equiv_of_is_contr_left definition pi_bool_left [constructor] (B : bool → Type) : (Πx, B x) ≃ B ff × B tt := begin fapply equiv.MK, { intro f, exact (f ff, f tt)}, { intro x b, induction x, induction b: assumption}, { intro x, induction x, reflexivity}, { intro f, apply eq_of_homotopy, intro b, induction b: reflexivity}, end /- Truncatedness: any dependent product of n-types is an n-type -/ theorem is_trunc_pi (B : A → Type) (n : trunc_index) [H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) := begin revert B H, eapply (trunc_index.rec_on n), {intro B H, fapply is_contr.mk, intro a, apply center, intro f, apply eq_of_homotopy, intro x, apply (center_eq (f x))}, {intro n IH B H, fapply is_trunc_succ_intro, intro f g, fapply is_trunc_equiv_closed, apply equiv.symm, apply eq_equiv_homotopy, apply IH, intro a, show is_trunc n (f a = g a), from is_trunc_eq n (f a) (g a)} end local attribute is_trunc_pi [instance] theorem is_trunc_pi_eq [instance] [priority 500] (n : trunc_index) (f g : Πa, B a) [H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) := begin apply is_trunc_equiv_closed_rev, apply eq_equiv_homotopy end theorem is_trunc_not [instance] (n : trunc_index) (A : Type) : is_trunc (n.+1) ¬A := by unfold not;exact _ theorem is_prop_pi_eq [instance] [priority 490] (a : A) : is_prop (Π(a' : A), a = a') := is_prop_of_imp_is_contr ( assume (f : Πa', a = a'), have is_contr A, from is_contr.mk a f, by exact _) /- force type clas resolution -/ theorem is_prop_neg (A : Type) : is_prop (¬A) := _ local attribute ne [reducible] theorem is_prop_ne [instance] {A : Type} (a b : A) : is_prop (a ≠ b) := _ /- Symmetry of Π -/ definition is_equiv_flip [instance] {P : A → A' → Type} : is_equiv (@function.flip A A' P) := begin fapply is_equiv.mk, exact (@function.flip _ _ (function.flip P)), repeat (intro f; apply idp) end definition pi_comm_equiv {P : A → A' → Type} : (Πa b, P a b) ≃ (Πb a, P a b) := equiv.mk (@function.flip _ _ P) _ end pi attribute pi.is_trunc_pi [instance] [priority 1520]
321bb11a24cb03b5329014c7a6c296fe9f86e1b5
59aed81a2ce7741e690907fc374be338f4f88b6f
/src/math-688/lectures/lec-2.lean
1f3a8bfcc86118c297da24446341a6dbdbd8f324
[]
no_license
agusakov/math-688-lean
c84d5e1423eb208a0281135f0214b91b30d0ef48
67dc27ebff55a74c6b5a1c469ba04e7981d2e550
refs/heads/main
1,679,699,340,788
1,616,602,782,000
1,616,602,782,000
332,894,454
0
0
null
null
null
null
UTF-8
Lean
false
false
5,961
lean
/- 30 Aug 2019 -/ -- degree -- incidence matrix -- adjacency matrix /- ## Definitions: * A sequence of nonnegative integers is called `graphic` if it is the degree sequence of a simple graph. how does one write dn where n is a subscript? Havel-Hakimi Theorem: Let d_1 ≥ d_2 ≥ ... ≥ d_n ≥ 0 be a (finite) sequence of nonnegative integers. The sequence is graphic iff the sequence d_2 - 1, ... , d_(t + 1) - 1, d_(t + 2), ... , d_n, where t = d_1, is graphic. Let 0 ≤ d_1 ≤ d_2 ≤ ... ≤ d_n be a (finite) sequence of nonnegative integers. The sequence is graphic iff the sequence d_2 - 1, ... , d_(t + 1) - 1, d_(t + 2), ... , d_n, where t = d_1 is graphic. -/ import data.list.sort import combinatorics.simple_graph.basic import data.multiset.sort universe u variables (V : Type u) [fintype V] -- what type should i use? -- `list.sorted` or `list.pairwise` -- i think i can just use nat since that includes zero -- oh god i need some kind of counter? or index -- copy over the sequence except erase largest element and -- subtract one from the n next largest elements def sub_one_n_times' (n : ℕ) (l : list ℕ) : list ℕ := (l.take n).map (nat.pred) ++ l.drop n -- this one works i think, but ordering does matter /-def list.pos_filter (l : list ℕ) : list ℕ := l.filter (λ n, 0 < n) -- this probably already exists, just don't feel like looking it up def n_pos_list_check (n : ℕ) (l : list ℕ) : Prop := n ≤ l.pos_filter.length-/ -- def nth_is_pos (n : ℕ) (l : list ℕ) [l.sorted (≤)] : Prop := 0 < (l.nth n) -- bad def sub_one_n_times (n : ℕ) (l : list ℕ) (h : l.sorted (≥)) : option (list ℕ) := if n ≤ (l.filter (λ n, 0 < n)).length then some (sub_one_n_times' n l) else none def havel_hakimi' (l : list ℕ) (h : l.sorted (≥)) : option (list ℕ) := if (l.filter (λ n, 0 < n)) = [] then some [] else sub_one_n_times l.head l.tail h.tail -- you can't get the empty list out of applying sub_one_n_times and removing the largest degree repeatedly, so when -- you get the empty list, you're done -- is there another way of doing it? is there something else i can return -- also need to re-sort def havel_hakimi_step (l : list ℕ) (h : l.sorted (≥)) : multiset ℕ := sub_one_n_times' l.head l.tail -- ideas for degree sequence -- multiset of vertices, take the image -- `multiset.sort` to get sorted list variables {V} def simple_graph.degree_multiset (G : simple_graph V) [decidable_rel G.adj] : multiset ℕ := finset.univ.val.map (λ v, G.degree v) def simple_graph.degree_sequence (G : simple_graph V) [decidable_rel G.adj] : list ℕ := G.degree_multiset.sort (≥) -- test out definition - good for algebraic graph theory? - look through lecture notes --variables (l : list ℕ) [l.sorted (≥)] -- in pseudocode, -- a multiset ℕ is graphic if it is the degree sequence of some graph `G` def graphic' (s : multiset ℕ) : Prop := ∃ (G : simple_graph V) [decidable_rel G.adj], by exactI s = G.degree_multiset -- a sorted list is graphic if blah blah def graphic (l : list ℕ) : Prop := ∃ (n : ℕ) (G : simple_graph $ fin n) [decidable_rel G.adj], by exactI l = G.degree_sequence -- theorem statement from wikipedia: /- Let `S = (d_{1},\dots ,d_{n})` be a finite list of nonnegative integers that is nonincreasing. List `S` is graphic if and only if the finite list `S' = (d_{2}-1,d_{3}-1,\dots ,d_{{d_{1}+1}}-1,d_{{d_{1}+2}},\dots ,d_{n})` has nonnegative integers and is graphic. -/ variables (S : list ℕ) (h : S.sorted (≥)) def simple_graph.degree' (G : simple_graph V) [decidable_rel G.adj] : V → ℕ := λ v, G.degree v theorem havel_hakimi_A : graphic S → (S.head ≤ (S.filter (λ n, 0 < n)).length) ∧ graphic ((havel_hakimi_step S h).sort (≥)) := begin intros h2, split, { -- this is just the fact that S.head is largest degree, so the vertex with that degree is adjacent -- to S.head many vertices, which then means that they have degree at least 1 rcases h2 with ⟨n, G, hdec, hds⟩, have h3 : S.head = (@simple_graph.degree_sequence (fin n) _ G hdec).head, exact congr_arg list.head hds, let d1 := (@simple_graph.degree_sequence (fin n) _ G hdec).head, -- let v1 := simple_graph.degree_multiset⁻¹ G d1, -- how to get to the preimage of the map in degree_multiset sorry }, { -- the proof here is that performing the algorithm step is allowed because you can do the edge swap sorry }, end lemma havel_hakimi_B : (S.head ≤ (S.filter (λ n, 0 < n)).length) ∧ graphic ((havel_hakimi_step S h).sort (≥)) → graphic S := begin intros h2, rcases h2 with ⟨hnneg, n, G, hdec, hds⟩, sorry, end theorem havel_hakimi : graphic S ↔ (S.head ≤ (S.filter (λ n, 0 < n)).length) ∧ graphic ((havel_hakimi_step S h).sort (≥)) := ⟨havel_hakimi_A S h, havel_hakimi_B S h⟩ variables (G : simple_graph V) [decidable_eq V] (v w x y : V) variables (h1 : G.adj v w) (h2 : G.adj x y) (hn1 : ¬ G.adj v x) (hn2 : ¬ G.adj w y) def new_graph : simple_graph V := { adj := λ a b, if (((a = v) ∧ (b = w)) ∨ ((a = v) ∧ (b = x)) ∨ (((a = w) ∧ (b = y)) ∨ ((a = x) ∧ (b = y)))) then ¬ G.adj a b else G.adj a b, -- there's gotta be a better way of doing this sym := λ a b, begin simp, intros h, sorry, end, loopless := sorry, } /-def new_graph : simple_graph V := { adj := λ a b, if ((a ≠ v) ∧ (a ≠ w)) ∨ ((b ≠ x) ∧ (b ≠ y)) then G.adj a b else ¬ G.adj a b, -- there's gotta be a better way of doing this sym := λ a b, begin simp, intros h, end, loopless := _ }-/ -- okay shit this is gonna be annoying -- going to need to show that the max degree is le the number of remaining vertices -- sequence D is graphic if ∃ (G : simple_graph V), D is deg seq for G -- for proof, need to define swapping edge algo -- BUT FIRST we need to define edge deletion lmao
a9b348437a721dfeb2060d4e9e3110abc8aaebd9
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/order/bounds.lean
6588039d2362acb71d84b7852909e49f6746077e
[ "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
24,983
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) /-! ### 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 /-! ### 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 /-- 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 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 } 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_le (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
8f4d11fe33855f91f362f7150899bdcb9d900dab
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/constructor_tactic.lean
92039e2009ae911a5ea059a61ac37dd5f7258fe9
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
3,139
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.tactic init.function namespace tactic /- Return target after instantiating metavars and whnf -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf meta def get_constructors_for (e : expr) : tactic (list name) := do env ← get_env, I ← return e.get_app_fn.const_name, when (¬env.is_inductive I) (fail "constructor tactic failed, target is not an inductive datatype"), return $ env.constructors_of I private meta def try_constructors (cfg : apply_cfg): list name → tactic unit | [] := fail "constructor tactic failed, none of the constructors is applicable" | (c::cs) := (mk_const c >>= λ e, apply_core e cfg >> return ()) <|> try_constructors cs meta def constructor (cfg : apply_cfg := {}): tactic unit := target' >>= get_constructors_for >>= try_constructors cfg meta def econstructor : tactic unit := constructor {new_goals := new_goals.non_dep_only} meta def fconstructor : tactic unit := constructor {new_goals := new_goals.all} meta def left : tactic unit := do tgt ← target', [c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors", mk_const c₁ >>= apply meta def right : tactic unit := do tgt ← target', [c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors", mk_const c₂ >>= apply meta def constructor_idx (idx : nat) : tactic unit := do cs ← target' >>= get_constructors_for, some c ← return $ cs.nth (idx - 1) | fail "constructor_idx tactic failed, target is an inductive datatype, but it does not have sufficient constructors", mk_const c >>= apply meta def split : tactic unit := do [c] ← target' >>= get_constructors_for | fail "split tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= apply open expr private meta def apply_num_metavars : expr → expr → nat → tactic expr | f ftype 0 := return f | f ftype (n+1) := do pi m bi d b ← whnf ftype, a ← mk_meta_var d, new_f ← return $ f a, new_ftype ← return $ b.instantiate_var a, apply_num_metavars new_f new_ftype n meta def existsi (e : expr) : tactic unit := do [c] ← target' >>= get_constructors_for | fail "existsi tactic failed, target is not an inductive datatype with only one constructor", fn ← mk_const c, fn_type ← infer_type fn, n ← get_arity fn, when (n < 2) (fail "existsi tactic failed, constructor must have at least two arguments"), t ← apply_num_metavars fn fn_type (n - 2), eapply (app t e), t_type ← infer_type t >>= whnf, e_type ← infer_type e, (guard t_type.is_pi <|> fail "existsi tactic failed, failed to infer type"), (unify t_type.binding_domain e_type <|> fail "existsi tactic failed, type mismatch between given term witness and expected type") end tactic
f40dcff7eca26c8ad4e1f0d9313e80a5d59aa2d4
5719a16e23dfc08cdea7a5bf035b81690f307965
/stage0/src/Init/Lean/Meta/AppBuilder.lean
898f8a6662f5a2cf09fb4b0126d2a467f078c2bc
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,949
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.Lean.Util.Recognizers import Init.Lean.Meta.SynthInstance namespace Lean namespace Meta /-- Given `e` s.t. `inferType e` is definitionally equal to `expectedType`, return term `@id expectedType e`. -/ def mkExpectedTypeHint (e : Expr) (expectedType : Expr) : MetaM Expr := do u ← getLevel expectedType; pure $ mkApp2 (mkConst `id [u]) expectedType e def mkEq (a b : Expr) : MetaM Expr := do aType ← inferType a; u ← getLevel aType; pure $ mkApp3 (mkConst `Eq [u]) aType a b def mkHEq (a b : Expr) : MetaM Expr := do aType ← inferType a; bType ← inferType b; u ← getLevel aType; pure $ mkApp4 (mkConst `HEq [u]) aType a bType b def mkEqRefl (a : Expr) : MetaM Expr := do aType ← inferType a; u ← getLevel aType; pure $ mkApp2 (mkConst `Eq.refl [u]) aType a def mkHEqRefl (a : Expr) : MetaM Expr := do aType ← inferType a; u ← getLevel aType; pure $ mkApp2 (mkConst `HEq.refl [u]) aType a private def infer (h : Expr) : MetaM Expr := do hType ← inferType h; whnfD hType def mkEqSymm (h : Expr) : MetaM Expr := if h.isAppOf `Eq.refl then pure h else do hType ← infer h; match hType.eq? with | some (α, a, b) => do u ← getLevel α; pure $ mkApp4 (mkConst `Eq.symm [u]) α a b h | none => throwEx $ Exception.appBuilder `Eq.symm "equality proof expected" #[h] def mkEqTrans (h₁ h₂ : Expr) : MetaM Expr := if h₁.isAppOf `Eq.refl then pure h₂ else if h₂.isAppOf `Eq.refl then pure h₁ else do hType₁ ← infer h₁; hType₂ ← infer h₂; match hType₁.eq?, hType₂.eq? with | some (α, a, b), some (_, _, c) => do u ← getLevel α; pure $ mkApp6 (mkConst `Eq.trans [u]) α a b c h₁ h₂ | _, _ => throwEx $ Exception.appBuilder `Eq.trans "equality proof expected" #[h₁, h₂] def mkHEqSymm (h : Expr) : MetaM Expr := if h.isAppOf `HEq.refl then pure h else do hType ← infer h; match hType.heq? with | some (α, a, β, b) => do u ← getLevel α; pure $ mkApp5 (mkConst `HEq.symm [u]) α β a b h | none => throwEx $ Exception.appBuilder `HEq.symm "heterogeneous equality proof expected" #[h] def mkHEqTrans (h₁ h₂ : Expr) : MetaM Expr := if h₁.isAppOf `HEq.refl then pure h₂ else if h₂.isAppOf `HEq.refl then pure h₁ else do hType₁ ← infer h₁; hType₂ ← infer h₂; match hType₁.heq?, hType₂.heq? with | some (α, a, β, b), some (_, _, γ, c) => do u ← getLevel α; pure $ mkApp8 (mkConst `HEq.trans [u]) α β γ a b c h₁ h₂ | _, _ => throwEx $ Exception.appBuilder `HEq.trans "heterogeneous equality proof expected" #[h₁, h₂] def mkEqOfHEq (h : Expr) : MetaM Expr := do hType ← infer h; match hType.heq? with | some (α, a, β, b) => do unlessM (isDefEq α β) $ throwEx $ Exception.appBuilder `eqOfHEq "heterogeneous equality types are not definitionally equal" #[α, β]; u ← getLevel α; pure $ mkApp4 (mkConst `eqOfHEq [u]) α a b h | _ => throwEx $ Exception.appBuilder `HEq.trans "heterogeneous equality proof expected" #[h] def mkCongrArg (f h : Expr) : MetaM Expr := do hType ← infer h; fType ← infer f; match fType.arrow?, hType.eq? with | some (α, β), some (_, a, b) => do u ← getLevel α; v ← getLevel β; pure $ mkApp6 (mkConst `congrArg [u, v]) α β a b f h | none, _ => throwEx $ Exception.appBuilder `congrArg "non-dependent function expected" #[f, h] | _, none => throwEx $ Exception.appBuilder `congrArg "equality proof expected" #[f, h] def mkCongrFun (h a : Expr) : MetaM Expr := do hType ← infer h; match hType.eq? with | some (ρ, f, g) => do ρ ← whnfD ρ; match ρ with | Expr.forallE n α β _ => do let β' := Lean.mkLambda n BinderInfo.default α β; u ← getLevel α; v ← getLevel (mkApp β' a); pure $ mkApp6 (mkConst `congrFun [u, v]) α β' f g h a | _ => throwEx $ Exception.appBuilder `congrFun "equality proof between functions expected" #[h, a] | _ => throwEx $ Exception.appBuilder `congrFun "equality proof expected" #[h, a] def mkCongr (h₁ h₂ : Expr) : MetaM Expr := do hType₁ ← infer h₁; hType₂ ← infer h₂; match hType₁.eq?, hType₂.eq? with | some (ρ, f, g), some (α, a, b) => do ρ ← whnfD ρ; match ρ.arrow? with | some (_, β) => do u ← getLevel α; v ← getLevel β; pure $ mkApp8 (mkConst `congr [u, v]) α β f g a b h₁ h₂ | _ => throwEx $ Exception.appBuilder `congr "non-dependent function expected" #[h₁, h₂] | _, _ => throwEx $ Exception.appBuilder `congr "equality proof expected" #[h₁, h₂] private def mkAppMFinal (methodName : Name) (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do instMVars.forM $ fun mvarId => do { mvarDecl ← getMVarDecl mvarId; mvarVal ← synthInstance mvarDecl.type; assignExprMVar mvarId mvarVal }; result ← instantiateMVars (mkAppN f args); whenM (hasAssignableMVar result) $ throwEx $ Exception.appBuilder methodName "result contains metavariables" #[result]; pure result private partial def mkAppMAux (f : Expr) (xs : Array Expr) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args; match c.binderInfo with | BinderInfo.implicit => do mvar ← mkFreshExprMVar d n; mkAppMAux i (args.push mvar) j instMVars b | BinderInfo.instImplicit => do mvar ← mkFreshExprMVar d n MetavarKind.synthetic; mkAppMAux i (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => if h : i < xs.size then do let x := xs.get ⟨i, h⟩; xType ← inferType x; condM (isDefEq d xType) (mkAppMAux (i+1) (args.push x) j instMVars b) (throwEx $ Exception.appTypeMismatch (mkAppN f args) x) else mkAppMFinal `mkAppM f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args; type ← whnfD type; if type.isForall then mkAppMAux i args args.size instMVars type else if i == xs.size then mkAppMFinal `mkAppM f args instMVars else throwEx $ Exception.appBuilder `mkAppM "too many explicit arguments provided" (#[f] ++ xs) private def mkFun (constName : Name) : MetaM (Expr × Expr) := do cinfo ← getConstInfo constName; us ← cinfo.lparams.mapM $ fun _ => mkFreshLevelMVar; let f := mkConst constName us; let fType := cinfo.instantiateTypeLevelParams us; pure (f, fType) def mkAppM (constName : Name) (xs : Array Expr) : MetaM Expr := traceCtx `Meta.appBuilder $ withNewMCtxDepth $ do (f, fType) ← mkFun constName; mkAppMAux f xs 0 #[] 0 #[] fType private partial def mkAppOptMAux (f : Expr) (xs : Array (Option Expr)) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args; if h : i < xs.size then do match xs.get ⟨i, h⟩ with | none => match c.binderInfo with | BinderInfo.instImplicit => do mvar ← mkFreshExprMVar d n MetavarKind.synthetic; mkAppOptMAux (i+1) (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => do mvar ← mkFreshExprMVar d n; mkAppOptMAux (i+1) (args.push mvar) j instMVars b | some x => do xType ← inferType x; condM (isDefEq d xType) (mkAppOptMAux (i+1) (args.push x) j instMVars b) (throwEx $ Exception.appTypeMismatch (mkAppN f args) x) else mkAppMFinal `mkAppOptM f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args; type ← whnfD type; if type.isForall then mkAppOptMAux i args args.size instMVars type else if i == xs.size then mkAppMFinal `mkAppOptM f args instMVars else do let xs : Array Expr := xs.foldl (fun r x? => match x? with | none => r | some x => r.push x) #[]; throwEx $ Exception.appBuilder `mkAppOptM "too many arguments provided" (#[f] ++ xs) /-- Similar to `mkAppM`, but it allows us to specify which arguments are provided explicitly using `Option` type. Example: Given `HasPure.pure {m : Type u → Type v} [HasPure m] {α : Type u} (a : α) : m α`, ``` mkAppOptM `HasPure.pure #[m, none, none, a] ``` returns a `HasPure.pure` application if the instance `HasPure m` can be synthesized, and the universes match. Note that, ``` mkAppM `HasPure.pure #[a] ``` fails because the only explicit argument `(a : α)` is not sufficient for inferring the remaining arguments, we would need the expected type. -/ def mkAppOptM (constName : Name) (xs : Array (Option Expr)) : MetaM Expr := traceCtx `Meta.appBuilder $ withNewMCtxDepth $ do (f, fType) ← mkFun constName; mkAppOptMAux f xs 0 #[] 0 #[] fType def mkEqNDRec (motive h1 h2 : Expr) : MetaM Expr := if h2.isAppOf `Eq.refl then pure h1 else do h2Type ← infer h2; match h2Type.eq? with | none => throwEx $ Exception.appBuilder `Eq.ndrec "equality proof expected" #[h2] | some (α, a, b) => do u2 ← getLevel α; motiveType ← infer motive; match motiveType with | Expr.forallE _ _ (Expr.sort u1 _) _ => pure $ mkAppN (mkConst `Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwEx $ Exception.appBuilder `Eq.ndrec "invalid motive" #[motive] def mkEqRec (motive h1 h2 : Expr) : MetaM Expr := if h2.isAppOf `Eq.refl then pure h1 else do h2Type ← infer h2; match h2Type.eq? with | none => throwEx $ Exception.appBuilder `Eq.rec "equality proof expected" #[h2] | some (α, a, b) => do u2 ← getLevel α; motiveType ← infer motive; match motiveType with | Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ => pure $ mkAppN (mkConst `Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwEx $ Exception.appBuilder `Eq.rec "invalid motive" #[motive] def mkEqMP (eqProof pr : Expr) : MetaM Expr := mkAppM `Eq.mp #[eqProof, pr] def mkEqMPR (eqProof pr : Expr) : MetaM Expr := mkAppM `Eq.mpr #[eqProof, pr] def mkNoConfusion (target : Expr) (h : Expr) : MetaM Expr := do type ← inferType h; type ← whnf type; match type.eq? with | none => throwEx $ Exception.appBuilder `noConfusion "equality expected" #[h] | some (α, a, b) => do α ← whnf α; env ← getEnv; let f := α.getAppFn; matchConst env f (fun _ => throwEx $ Exception.appBuilder `noConfusion "inductive type expected" #[α]) $ fun cinfo us => match cinfo with | ConstantInfo.inductInfo v => do u ← getLevel target; pure $ mkAppN (mkConst (mkNameStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h]) | _ => throwEx $ Exception.appBuilder `noConfusion "inductive type expected" #[α] def mkPure (m : Expr) (e : Expr) : MetaM Expr := do mkAppOptM `HasPure.pure #[m, none, none, e] end Meta end Lean
6c80eeffbc3b45f28afaa173245224ff22540ca6
7bf54883c04ff2856c37f76a79599ceb380c1996
/non-mathlib/quartic.lean
182dc7ba9048b78acf03da9c5d5623af7d3fcd2a
[]
no_license
anonymousLeanDocsHosting/lean-polynomials
4094466bf19acc0d1a47b4cabb60d8c21ddb2b00
361ef4cb7b68ef47d43b85cfa2d13f2ea0a47613
refs/heads/main
1,691,112,899,935
1,631,819,522,000
1,631,819,522,000
405,448,439
0
2
null
null
null
null
UTF-8
Lean
false
false
81,302
lean
import field_definition import field_results import numbers import roots import quadratic import cubic lemma not_char_four (f : Type) [myfld f] [fld_not_char_two f] : (four f) ≠ myfld.zero := begin unfold four, rw two_plus_two f, exact mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two, end def fourth_power (f : Type) [myfld f] (a : f) : f := a .* (a .* (a .* a)) lemma fourth_power_of_product (f : Type) [myfld f] (a b : f) : (fourth_power f (a .* b)) = (fourth_power f a) .* (fourth_power f b) := begin unfold fourth_power, repeat {rw <- myfld.mul_assoc}, repeat {rw myfld.mul_comm b (_ .* _) }, repeat {rw <- myfld.mul_assoc}, end lemma fourth_power_negate (f : Type) [myfld f] (a : f) : (fourth_power f (.- a)) = (fourth_power f a) := begin unfold fourth_power, repeat {rw mul_negate}, repeat {rw mul_negate_alt_simp}, repeat {rw double_negative}, end def fourth_root_a (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : f := (sqroot (sqroot a)) lemma fourth_root_to_power_a (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : fourth_power f (fourth_root_a f a) = a := begin unfold fourth_power, unfold fourth_root_a, rw fld_with_sqrt.sqrt_mul_sqrt (sqroot a), rw myfld.mul_assoc, rw fld_with_sqrt.sqrt_mul_sqrt (sqroot a), rw fld_with_sqrt.sqrt_mul_sqrt a, end def fourth_root_b (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : f := (.- (sqroot (sqroot a))) lemma fourth_root_to_power_b (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : fourth_power f (fourth_root_b f a) = a := begin unfold fourth_power, unfold fourth_root_b, repeat {rw mul_negate_alt_simp, rw mul_negate}, repeat {rw mul_negate_alt_simp}, repeat {rw double_negative}, rw fld_with_sqrt.sqrt_mul_sqrt (sqroot a), rw myfld.mul_assoc, rw fld_with_sqrt.sqrt_mul_sqrt (sqroot a), rw fld_with_sqrt.sqrt_mul_sqrt a, end def fourth_root_c (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : f := sqroot (.- (sqroot a)) lemma fourth_root_to_power_c (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : fourth_power f (fourth_root_c f a) = a := begin unfold fourth_power, unfold fourth_root_c, rw fld_with_sqrt.sqrt_mul_sqrt (.- (sqroot a)), rw myfld.mul_assoc, rw fld_with_sqrt.sqrt_mul_sqrt (.- (sqroot a)), rw mul_negate, rw mul_negate_alt_simp, rw fld_with_sqrt.sqrt_mul_sqrt a, rw double_negative, end def fourth_root_d (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : f := .- (sqroot (.- (sqroot a))) lemma fourth_root_to_power_d (f : Type) [myfld f] [fld_with_sqrt f] (a : f) : fourth_power f (fourth_root_d f a) = a := begin unfold fourth_power, unfold fourth_root_d, repeat {rw mul_negate_alt_simp, rw mul_negate}, repeat {rw mul_negate_alt_simp}, repeat {rw double_negative}, rw fld_with_sqrt.sqrt_mul_sqrt (.- (sqroot a)), rw myfld.mul_assoc, rw fld_with_sqrt.sqrt_mul_sqrt (.- (sqroot a)), rw mul_negate, rw mul_negate_alt_simp, rw fld_with_sqrt.sqrt_mul_sqrt a, rw double_negative, end /- We put the negations in this expression so that it represents the quartic who's solutions are a1 a2 a3 & a4, which is neat.-/ def factorized_quartic_expression (f : Type) [myfld f] (x a1 a2 a3 a4 : f) : f := ((x .+ (.- a1)) .* ((x .+ (.- a2)) .* ((x .+ (.- a3)) .* (x .+ (.- a4))))) def quartic_expression (f : Type) [myfld f] (x a b c d e : f) : f := (((fourth_power f x) .* a) .+ (((cubed f x) .* b) .+ (((square f x) .* c) .+ ((x .* d) .+ e)))) lemma multiply_out_quartic (f : Type) [myfld f] (x a1 a2 a3 a4 : f) : (factorized_quartic_expression f x a1 a2 a3 a4) = (quartic_expression f x myfld.one (.- (a1 .+ (a2 .+ (a3 .+ a4)))) ((a1 .* a2) .+ ((a1 .* a3) .+ ((a1 .* a4) .+ ((a2 .* a3) .+ ((a2 .* a4) .+ (a3 .* a4)))))) (.- ((a1 .* (a2 .* a3)) .+ ((a1 .* (a2 .* a4)) .+ ((a1 .* (a3 .* a4)) .+ (a2 .* (a3 .* a4)))))) (a1 .* (a2 .* (a3 .* a4)))) := begin have clear_term : ∀ (a b x : f), a = b -> (x .+ a) = (x .+ b), intros a b x h, rw h, unfold quartic_expression, unfold factorized_quartic_expression, unfold fourth_power, unfold cubed, unfold square, repeat {rw distrib_simp f _ _ _}, repeat {rw distrib_simp_alt f _ _ _}, repeat {rw distrib_simp f _ _ _}, repeat {rw distrib_simp_alt f _ _ _}, repeat {rw mul_negate_alt_simp f _ _}, repeat {rw mul_negate f _ _}, repeat {rw mul_negate_alt_simp f _ _}, repeat {rw mul_negate f _ _}, repeat {rw double_negative f _}, repeat {rw distrib_simp_alt f}, repeat {rw <- myfld.add_assoc}, repeat {rw myfld.mul_assoc}, repeat {rw add_negate f}, rw simp_mul_one, apply clear_term _ _ _, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (.- (((x .* x) .* x) .* a4)), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw <- myfld.mul_assoc (x .* x) a3 x, rw myfld.mul_comm a3 x, rw myfld.mul_assoc (x .* x) x a3, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (.- (((x .* x) .* x) .* a3)), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (((x .* x) .* a3) .* a4), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw myfld.mul_comm ((x .* x) .* x) a2, rw myfld.mul_comm x a2, repeat {rw myfld.mul_assoc}, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (.- (((a2 .* x) .* x) .* x)), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, repeat {rw myfld.add_assoc}, repeat {rw myfld.add_comm _ (((a1 .* a2) .* a3) .* a4) }, apply clear_term _ _ _, rw myfld.mul_comm (x .* x) a2, repeat {rw myfld.mul_assoc}, rw myfld.add_comm _ (((a2 .* x) .* x) .* a4), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw <- myfld.mul_assoc (a2 .* x) x a3, rw myfld.mul_comm x a3, rw myfld.mul_assoc (a2 .* x) a3 x, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (((a2 .* x) .* a3) .* x), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw myfld.add_comm _ (_ .+ _), rw myfld.mul_comm ((x .* x) .* x) a1, repeat {rw myfld.mul_assoc}, repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw myfld.mul_comm (x .* x) a1, rw myfld.mul_assoc a1 x x, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (((a1 .* x) .* x) .* a4), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw <- myfld.mul_assoc (a1 .* x) x a3, rw myfld.mul_comm x a3, rw myfld.mul_assoc (a1 .* x) a3 x, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (((a1 .* x) .* a3) .* x), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw myfld.mul_comm x a1, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (.- (((a1 .* x) .* a3) .* a4)), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, rw myfld.mul_comm ((a1 .* x) .* x) a2, rw myfld.mul_comm a1 a2, repeat {rw myfld.mul_assoc}, apply clear_term _ _ _, rw myfld.mul_comm (a1 .* x) a2, repeat {rw myfld.mul_assoc}, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (.- (((a2 .* a1) .* x) .* a4)), repeat {rw <- myfld.add_assoc}, apply clear_term _ _ _, repeat {rw myfld.mul_comm (_ .* _) x}, repeat {rw myfld.mul_assoc}, end lemma multiply_out_fourth_power (f : Type) [myfld f] (x y : f) : (fourth_power f (x .+ y)) = quartic_expression f x myfld.one ((four f) .* y) ((six f) .* (square f y)) ((four f) .* (cubed f y)) (fourth_power f y) := begin have reduce : (fourth_power f (x .+ y)) = factorized_quartic_expression f x (.- y) (.- y) (.- y) (.- y), unfold factorized_quartic_expression, unfold fourth_power, repeat {rw double_negative f y}, rw reduce, clear reduce, rw multiply_out_quartic, simp only [mul_negate, mul_negate_alt_simp, double_negative], repeat {rw <- add_negate f _ _}, repeat {rw double_negative f _}, have equate_coeff : ∀ (a1 a2 b1 b2 c1 c2 d1 d2 e1 e2 x : f), (a1 = a2) -> (b1 = b2) -> (c1 = c2) -> (d1 = d2) -> (e1 = e2) -> (quartic_expression f x a1 b1 c1 d1 e1) = (quartic_expression f x a2 b2 c2 d2 e2), intros a1 a2 b1 b2 c1 c2 d1 d2 e1 e2 x h1 h2 h3 h4 h5, rw h1, rw h2, rw h3, rw h4, rw h5, apply equate_coeff, refl, unfold four, unfold two, simp, unfold six, unfold two, unfold three, unfold square, simp, unfold four, unfold two, unfold cubed, simp, unfold fourth_power, end lemma sum_of_fourth_roots (f : Type) [myfld f] [fld_with_sqrt f] (x : f) : (fourth_root_a f x) .+ ((fourth_root_b f x) .+ ((fourth_root_c f x) .+ (fourth_root_d f x))) = myfld.zero := begin unfold fourth_root_a fourth_root_b fourth_root_c fourth_root_d, simp, end lemma no_other_fourth_roots (f : Type) [myfld f] [fld_with_sqrt f] (x root : f) : (root ≠ (fourth_root_a f x)) -> (root ≠ (fourth_root_b f x)) -> (root ≠ (fourth_root_c f x)) -> (root ≠ (fourth_root_d f x)) -> (fourth_power f root) ≠ x := begin intros ha hb hc hd is_root, have make_ne_zero : ∀ (a b : f), a ≠ b -> (a .+ (.- b)) ≠ myfld.zero, intros a b h1 h2, have h3 : (a .+ (.- b)) .+ b = myfld.zero .+ b, rw h2, clear h2, rw simp_zero at h3, rw <- myfld.add_assoc at h3, rw myfld.add_comm (.- b) b at h3, rw myfld.add_negate b at h3, rw zero_simp at h3, cc, have ha1 : root .+ (.- (fourth_root_a f x)) ≠ myfld.zero, exact make_ne_zero _ _ ha, clear ha, rename ha1 ha, have hb1 : root .+ (.- (fourth_root_b f x)) ≠ myfld.zero, exact make_ne_zero _ _ hb, clear hb, rename hb1 hb, have hc1 : root .+ (.- (fourth_root_c f x)) ≠ myfld.zero, exact make_ne_zero _ _ hc, clear hc, rename hc1 hc, have hd1 : root .+ (.- (fourth_root_d f x)) ≠ myfld.zero, exact make_ne_zero _ _ hd, clear hd, rename hd1 hd, clear make_ne_zero, have multiply_out : factorized_quartic_expression f root (fourth_root_a f x) (fourth_root_b f x) (fourth_root_c f x) (fourth_root_d f x) = (fourth_power f root) .+ (.- x) , rw multiply_out_quartic, rw sum_of_fourth_roots, rw negate_zero_zero, unfold fourth_root_a, unfold fourth_root_b, unfold fourth_root_c, unfold fourth_root_d, repeat {rw mul_negate}, repeat {rw mul_negate_alt_simp}, repeat {rw fld_with_sqrt.sqrt_mul_sqrt}, repeat {rw mul_negate}, repeat {rw mul_negate_alt_simp}, repeat {rw myfld.add_assoc _ (.- _) _}, rw myfld.add_comm (.- _) _, repeat {rw myfld.add_negate}, repeat {rw double_negative}, rw simp_zero, rw myfld.add_comm (.- _) (_ .* _), repeat {rw myfld.add_negate _}, rw simp_zero, rw myfld.add_negate _, rw simp_zero, rw myfld.add_negate _, rw negate_zero_zero, rw myfld.mul_assoc, rw fld_with_sqrt.sqrt_mul_sqrt, rw fld_with_sqrt.sqrt_mul_sqrt, unfold quartic_expression, simp, have h : (fourth_power f root) .+ (.- x) = myfld.zero, rw is_root, exact myfld.add_negate x, rw h at multiply_out, clear h, clear is_root, have h : factorized_quartic_expression f root (fourth_root_a f x) (fourth_root_b f x) (fourth_root_c f x) (fourth_root_d f x) ≠ myfld.zero, unfold factorized_quartic_expression, exact mul_nonzero f _ _ ha (mul_nonzero f _ _ hb (mul_nonzero f _ _ hc hd)), cc, end lemma remove_fourth_power_coefficient (f : Type) [myfld f] (a b c d e x : f) (a_ne_zero : a ≠ myfld.zero) : quartic_expression f x a b c d e = myfld.zero <-> quartic_expression f x myfld.one (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)) = myfld.zero := begin split, intros h, unfold quartic_expression, have tmp : myfld.one = (a .* (myfld.reciprocal a a_ne_zero)), symmetry, exact myfld.mul_reciprocal a a_ne_zero, rw tmp, clear tmp, repeat {rw myfld.mul_assoc _ _ (myfld.reciprocal a a_ne_zero) }, repeat {rw <- distrib_simp f _ _ (myfld.reciprocal a a_ne_zero) }, unfold quartic_expression at h, rw h, rw mul_zero, intros h, have h1 : (quartic_expression f x myfld.one (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero))) .* a = myfld.zero, rw h, exact mul_zero f _, clear h, rename h1 h, unfold quartic_expression at h, repeat {rw distrib_simp f _ _ a at h}, repeat {rw <- myfld.mul_assoc _ _ _ at h}, repeat {rw myfld.mul_comm (myfld.reciprocal a _) a at h}, repeat {rw myfld.mul_reciprocal a a_ne_zero at h}, repeat {rw simp_mul_one at h}, rw one_mul_simp at h, unfold quartic_expression, exact h, end def depressed_quartic_subst (f : Type) [myfld f] (c d e x : f) : f := ((fourth_power f x) .+ ((c .* (square f x)) .+ ((d .* x) .+ e))) open nat /- Various different powers of two are utilized in the definition of the solution to a quartic, so it's cleaner to have a consistent function to generate them.-/ def pow_of_two (f : Type) [myfld f] : nat -> f | 0 := myfld.one | (succ n) := (pow_of_two n) .* (two f) lemma pow_of_two_nonzero (f : Type) [myfld f] [fld_not_char_two f] (exp : nat) : (pow_of_two f exp ≠ myfld.zero) := begin induction exp, unfold pow_of_two, exact myfld.zero_distinct_one, unfold pow_of_two, exact mul_nonzero f (pow_of_two f exp_n) (two f) exp_ih fld_not_char_two.not_char_two, end def depressed_quartic_squ_coeff (f : Type) [myfld f] [fld_not_char_two f] (b c : f) : f := (c .+ (.- ((square f b) .* ((three f) .* (myfld.reciprocal (pow_of_two f 3) (pow_of_two_nonzero f 3)))))) def depressed_quartic_linear_coeff (f : Type) [myfld f] [fld_not_char_two f] (b c d : f) : f := ((((cubed f b) .* (myfld.reciprocal (pow_of_two f 3) (pow_of_two_nonzero f 3))) .+ (.- ((b .* c) .* (myfld.reciprocal (two f) fld_not_char_two.not_char_two)))) .+ d) def depressed_quartic_constant (f : Type) [myfld f] [fld_not_char_two f] (b c d e : f) : f := ((((.- ((fourth_power f b) .* ((three f) .* (myfld.reciprocal (pow_of_two f 8) (pow_of_two_nonzero f 8))))) .+ ((c .* (square f b)) .* (myfld.reciprocal (pow_of_two f 4) (pow_of_two_nonzero f 4)))) .+ (.- ((b .* d) .* (myfld.reciprocal (four f) (four_ne_zero f))))) .+ e) /- The first of a few tedious helper lemmae that we use to expediate the proof of reducing a quartic function to a depressed quartic.-/ /- lemma six_div_sixteen (f : Type) [myfld f] [fld_not_char_two f] : ((six f) .* (myfld.reciprocal (square f (four f)) (square_ne_zero f (four f) (four_ne_zero f)))) = ((three f) .* (myfld.reciprocal (pow_of_two f 3) (pow_of_two_nonzero f 3))) := begin unfold six, unfold four, unfold square, unfold pow_of_two, rw split_reciprocal, rw reciprocal_rewrite f ((two f) .+ (two f)) ((two f) .* (two f)) (two_plus_two f) _, rw [split_reciprocal f (two f) (two f) _] {occs := occurrences.pos [1]}, rw myfld.mul_comm (two f) (three f), repeat {rw <- myfld.mul_assoc}, rw myfld.mul_assoc (two f) (myfld.reciprocal (two f) _) _, rw myfld.mul_reciprocal (two f) _, rw one_mul_simp, repeat {rw split_reciprocal}, rw recip_one_one, rw one_mul_simp, repeat {rw myfld.mul_assoc}, end -/ lemma quartic_reduce_x_squ_helper (f : Type) [myfld f] [fld_not_char_two f] (b c : f) : ((.- ((three f) .* (b .* ((myfld.reciprocal (four f) (four_ne_zero f)) .* b)))) .+ (c .+ ((six f) .* ((myfld.reciprocal (square f (four f)) (square_ne_zero f (four f) (four_ne_zero f))) .* (square f b))))) = (depressed_quartic_squ_coeff f b c) := begin have clear_term : ∀ (a b x : f), a = b -> (x .+ a) = (x .+ b), intros a b x h, rw h, unfold depressed_quartic_squ_coeff, rw myfld.add_assoc _ c _, rw myfld.add_comm _ c, rw <- myfld.add_assoc c _ _, apply clear_term _ _ c, clear clear_term, have clear_term : ∀ (a b x : f), a = b -> (x .* a) = (x .* b), intros a b x h, rw h, unfold six, rw myfld.mul_comm (two f) (three f), rw <- myfld.mul_assoc (three f) _ _, rw mul_negate_alt f (three f) _, rw <- distrib_simp_alt f (three f) _ _, rw myfld.mul_assoc (square f b) (three f) _, rw myfld.mul_comm (square f b) (three f), rw <- myfld.mul_assoc (three f) _ _, rw mul_negate_alt f (three f) _, apply clear_term _ _ (three f), rw myfld.mul_comm (myfld.reciprocal _ _) b, rw myfld.mul_assoc b b _, rw mul_negate_alt f (b .* b) _, rw myfld.mul_assoc (two f) (myfld.reciprocal _ _) _, rw myfld.mul_comm _ (square f b), unfold square, rw <- distrib_simp_alt f (b .* b) _ _, rw mul_negate_alt f (b .* b) _, apply clear_term _ _ (b .* b), rw split_reciprocal f (four f) (four f) _, unfold four, rw reciprocal_rewrite f ((two f) .+ (two f)) ((two f) .* (two f)) (two_plus_two f) _, rw [split_reciprocal f (two f) (two f) _] {occs := occurrences.pos [2]}, repeat {rw myfld.mul_assoc}, rw myfld.mul_reciprocal (two f) _, rw one_mul_simp, rw [myfld.mul_one (myfld.reciprocal ((two f) .* (two f)) _) ] {occs := occurrences.pos [1]}, rw myfld.mul_comm (myfld.reciprocal _ _) (myfld.reciprocal _ _), rw mul_negate_alt f _ myfld.one, rw <- distrib_simp_alt f _ _ _, have tmp : myfld.one = (two f) .* (myfld.reciprocal (two f) (two_ne_zero f)) , rw myfld.mul_reciprocal (two f), rw tmp, clear tmp, rw [myfld.mul_one (myfld.reciprocal (two f) _) ] {occs := occurrences.pos [2]}, rw myfld.mul_comm (two f) (myfld.reciprocal _ _), rw mul_negate_alt, rw <- distrib_simp_alt, have tmp : .- (two f) = (.- myfld.one) .+ (.- myfld.one) , unfold two, simp, rw tmp, clear tmp, rw <- myfld.add_assoc _ (.- myfld.one) myfld.one, rw myfld.add_comm (.- myfld.one) myfld.one, rw myfld.add_negate myfld.one, rw zero_simp, unfold pow_of_two, simp, end lemma quartic_reduce_linear_helper (f : Type) [myfld f] [fld_not_char_two f] (b c d : f) : ((((.- ((two f) .* (b .* ((myfld.reciprocal (four f) (four_ne_zero f)) .* c)))) .+ d) .+ (.- ((four f) .* (cubed f ((myfld.reciprocal (four f) (four_ne_zero f)) .* b))))) .+ ((three f) .* (b .* ((myfld.reciprocal (four f) (four_ne_zero f)) .* (b .* ((myfld.reciprocal (four f) (four_ne_zero f)) .* b)))))) = depressed_quartic_linear_coeff f b c d := begin unfold depressed_quartic_linear_coeff, have clear_term : ∀ (a b x : f), a = b -> (x .+ a) = (x .+ b), intros a b x h, rw h, repeat {rw myfld.add_comm _ d}, repeat {rw <- myfld.add_assoc}, apply clear_term _ _ d, rw myfld.mul_comm (myfld.reciprocal _ _) c, rw myfld.mul_assoc b c _, rw myfld.mul_assoc _ (b .* c) _, rw myfld.mul_comm _ (b .* c), rw <- myfld.mul_assoc (b .* c) _ _, unfold four, rw reciprocal_rewrite f ((two f) .+ (two f)) ((two f) .* (two f)) (two_plus_two f) _, rw [split_reciprocal f (two f) (two f) _] {occs := occurrences.pos [1]}, rw myfld.mul_assoc (two f) (myfld.reciprocal _ _) (myfld.reciprocal _ _), rw myfld.mul_reciprocal (two f) _, rw one_mul_simp, rw only_one_reciprocal f (two f) _ fld_not_char_two.not_char_two, rw myfld.add_comm ((cubed f b) .* _) _, apply clear_term, clear clear_term, have cube_of_product : ∀ (x y : f), (cubed f (x .* y)) = (cubed f x) .* (cubed f y) , unfold cubed, intros x y, repeat {rw myfld.mul_assoc}, repeat {rw myfld.mul_comm (_ .* _) x}, repeat {rw myfld.mul_assoc}, rw cube_of_product, clear cube_of_product, rw only_one_reciprocal f ((two f) .* (two f)) _ (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two), repeat {rw myfld.mul_comm (_ .* _) b}, repeat {rw myfld.mul_comm (myfld.reciprocal _ _) b}, repeat {rw myfld.mul_assoc}, rw myfld.mul_comm (_ .* _) b, rw myfld.mul_assoc b (b .* b) _, repeat {rw <- myfld.mul_assoc (b .* (b .* b)) _ _}, rw myfld.mul_comm _ (cubed f b), unfold cubed, rw mul_negate_alt f (b .* (b .* b)) _, rw <- distrib_simp_alt f (b .* (b .* b)) _ _, have clear_term : ∀ (a b x : f), a = b -> (x .* a) = (x .* b), intros a b x h, rw h, apply clear_term, rw two_plus_two f, rw myfld.mul_assoc ((two f) .* (two f)) (myfld.reciprocal _ _) _, rw myfld.mul_reciprocal ((two f) .* (two f)) _, rw one_mul_simp, rw mul_negate_alt f (myfld.reciprocal _ _) (myfld.reciprocal _ _), rw myfld.mul_comm (three f) _, rw <- myfld.mul_assoc _ (three f) _, rw <- distrib_simp_alt, unfold pow_of_two, repeat {rw <- reciprocal_rewrite f _ _ (myfld.mul_assoc _ _ _) _}, rw reciprocal_rewrite f _ _ (one_mul_simp f _) _, rw reciprocal_rewrite f _ _ (myfld.mul_assoc _ _ _) _, rw split_reciprocal f ((two f) .* (two f)) (two f) _, rw only_one_reciprocal f ((two f) .* (two f)) _ (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two), apply clear_term, have tmp : ∀ (x : f), (.- x) = (.- (myfld.one)) .* x, intros x, simp, rw tmp, clear tmp, rw <- distrib_simp f _ _ _, unfold three, rw myfld.add_assoc (.- myfld.one) myfld.one _, rw myfld.add_comm (.- myfld.one) myfld.one, rw myfld.add_negate myfld.one, rw simp_zero, have tmp : (myfld.one .+ myfld.one) = (two f), unfold two, rw tmp, clear tmp, rw split_reciprocal f (two f) (two f) _, rw myfld.mul_assoc, rw myfld.mul_reciprocal, rw only_one_reciprocal f (two f) _ fld_not_char_two.not_char_two, rw one_mul_simp, apply mul_nonzero f, exact myfld.zero_distinct_one, apply mul_nonzero f, exact fld_not_char_two.not_char_two, exact (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two), end lemma quartic_reduce_constant_helper (f : Type) [myfld f] [fld_not_char_two f] (b c d e : f) : (fourth_power f (.- ((myfld.reciprocal (four f) (four_ne_zero f)) .* b))) .+ ((.- ((cubed f ((myfld.reciprocal (four f) (four_ne_zero f)) .* b)) .* b)) .+ (((myfld.reciprocal (square f (four f)) (square_ne_zero f (four f) (four_ne_zero f))) .* ((square f b) .* c)) .+ ((.- (b .* ((myfld.reciprocal (four f) (four_ne_zero f)) .* d))) .+ e))) = depressed_quartic_constant f b c d e := begin have clear_term : ∀ (a b x : f), a = b -> (x .+ a) = (x .+ b), intros a b x h, rw h, unfold depressed_quartic_constant, repeat {rw myfld.add_assoc}, repeat {rw myfld.add_comm _ e}, apply clear_term, rw myfld.mul_comm (myfld.reciprocal _ _) d, rw myfld.mul_assoc b d _, repeat {rw myfld.add_comm _ (.- ((b .* d) .* (myfld.reciprocal (four f) _))) }, apply clear_term, have tmp : (square f (four f)) = (pow_of_two f 4), unfold four, rw two_plus_two, unfold square, unfold pow_of_two, rw one_mul_simp, repeat {rw myfld.mul_assoc}, rw reciprocal_rewrite f _ _ tmp _, rw <- myfld.mul_assoc _ (square f b) c, rw myfld.mul_comm (square f b) c, rw myfld.mul_comm (myfld.reciprocal _ _) (c .* (square f b)), repeat {rw myfld.add_comm _ ((c .* (square f b)) .* (myfld.reciprocal (pow_of_two f 4) _)) }, apply clear_term, clear clear_term, clear tmp, rw cube_of_product, rw fourth_power_negate, rw fourth_power_of_product, rw <- myfld.mul_assoc _ (cubed f b) b, rw myfld.mul_comm _ ((cubed f b) .* b), have tmp : ((cubed f b) .* b) = fourth_power f b, unfold cubed, unfold fourth_power, repeat {rw myfld.mul_assoc}, rw tmp, clear tmp, rw mul_negate_alt f (fourth_power f b) _, rw myfld.mul_comm _ (fourth_power f b), rw <- distrib_simp_alt f (fourth_power f b) _, repeat {rw <- myfld.mul_assoc (fourth_power f b) _ _}, rw mul_negate_alt f (fourth_power f b) _, have clear_term : ∀ (a b x : f), a = b -> (x .* a) = (x .* b), intros a b x h, rw h, apply clear_term, have tmp : (pow_of_two f 8) = (((four f) .* (four f)) .* ((four f) .* (four f))), unfold four, rw two_plus_two, unfold pow_of_two, rw one_mul_simp, repeat {rw myfld.mul_assoc}, rw reciprocal_rewrite f _ _ tmp _, unfold cubed, rw mul_two_reciprocals f (four f) (four f) _, have squ_squ : ∀ (x : f), (fourth_power f x) = ((x .* x) .* (x .* x)), intros x, unfold fourth_power, repeat {rw myfld.mul_assoc}, rw squ_squ, clear squ_squ, rw mul_two_reciprocals f (four f) (four f) _ _, rw myfld.mul_comm (myfld.reciprocal (four f) _) (myfld.reciprocal ((four f) .* (four f)) _), rw myfld.mul_comm (three f) (myfld.reciprocal _ _), rw split_reciprocal f ((four f) .* (four f)) _ _, rw <- myfld.mul_assoc (myfld.reciprocal _ _) _ (three f), repeat {rw mul_negate_alt f (myfld.reciprocal ((four f) .* (four f)) _) _}, rw only_one_reciprocal f ((four f) .* (four f)) _ (mul_nonzero f (four f) (four f) (four_ne_zero f) (four_ne_zero f)), rw <- distrib_simp_alt, apply clear_term, clear tmp, have mul_both_sides : ∀ (x y z : f), (x ≠ myfld.zero) -> (x .* y) = (x .* z) -> y = z, intros x y z h1 h2, have h3 : (myfld.reciprocal x h1) .* (x .* y) = (myfld.reciprocal x h1) .* (x .* z) , rw h2, repeat {rw myfld.mul_assoc at h3}, rw myfld.mul_comm _ x at h3, rw myfld.mul_reciprocal x h1 at h3, repeat {rw one_mul_simp at h3}, exact h3, apply mul_both_sides ((four f) .* (four f)) _ _, exact mul_nonzero f (four f) (four f) (four_ne_zero f) (four_ne_zero f), rw distrib_simp_alt, rw myfld.mul_reciprocal, rw myfld.mul_assoc ((four f) .* (four f)) (myfld.reciprocal _ _) _, rw myfld.mul_reciprocal, rw one_mul_simp, rw mul_negate_alt_simp, rw <- myfld.mul_assoc (four f) (four f) (myfld.reciprocal (four f) _), rw myfld.mul_reciprocal, rw simp_mul_one, unfold four, unfold two, rw <- myfld.add_assoc myfld.one _ _, rw add_negate, rw myfld.add_assoc myfld.one (.- myfld.one) _, rw myfld.add_negate, rw simp_zero, unfold three, end /- Similarly to how the x^2 term can be removed from a cubic with a clever substitution, the x^3 term can be removed from a quartic.-/ lemma reduce_quartic_to_depressed (f : Type) [myfld f] [fld_not_char_two f] (b c d e x u : f) : (x = u .+ (.- (b .* (myfld.reciprocal (four f) (four_ne_zero f))))) -> (quartic_expression f x myfld.one b c d e) = (depressed_quartic_subst f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) u) := begin intro hu, rw hu, clear hu, unfold quartic_expression, rw multiply_out_fourth_power, rw multiply_out_cubed, rw multiply_out_squared, unfold quartic_expression, repeat {rw simp_mul_one}, repeat {rw one_mul_simp}, repeat {rw square_negate}, repeat {rw cube_negate}, repeat {rw distrib_simp}, repeat {rw distrib_simp_alt}, repeat {rw mul_negate}, repeat {rw mul_negate_alt_simp}, repeat {rw mul_negate}, repeat {rw mul_negate_alt_simp}, rw mul_negate, repeat {rw double_negative}, repeat {rw <- myfld.add_assoc}, repeat {rw <- myfld.mul_assoc}, have clear_term : ∀ (a b x : f), a = b -> (x .+ a) = (x .+ b), intros a b x h, rw h, unfold depressed_quartic_subst, /- We can clear the u^4 term from both sides.-/ apply clear_term, /- The u^3 term doesn't exist...-/ rw myfld.add_comm ((cubed f u) .* b) _, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ ((cubed f u) .* b), repeat {rw <- myfld.add_assoc}, rw myfld.mul_comm b (myfld.reciprocal (four f) _), rw myfld.mul_assoc (four f) (myfld.reciprocal (four f) _) b, rw myfld.mul_reciprocal (four f) _, rw one_mul_simp, rw myfld.add_assoc ((cubed f u) .* b) (.- ((cubed f u) .* b)), rw myfld.add_negate, rw simp_zero, /- u^2 term...-/ rw <- mul_two_squares f (myfld.reciprocal (four f) _) b, rw reciprocal_squared f (four f) _, rw myfld.mul_assoc (six f) (myfld.reciprocal _ _) _, rw myfld.add_comm ((square f u) .* c) _, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ ((square f u) .* c), repeat {rw <- myfld.add_assoc}, rw myfld.add_assoc ((square f u) .* c) ((square f u) .* _) _, rw <- distrib_simp_alt f (square f u) c _, rw myfld.mul_assoc (three f) (square f u) _, rw myfld.mul_comm (three f) (square f u), repeat {rw <- myfld.mul_assoc}, rw mul_negate_alt f (square f u) _, rw myfld.add_comm ((square f u) .* (.- _)) _, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ ((square f u) .* (.- _)), repeat {rw <- myfld.add_assoc}, rw myfld.add_assoc ((square f u) .* _) ((square f u) .* _) _, rw <- distrib_simp_alt f (square f u) _ _, rw quartic_reduce_x_squ_helper, rw myfld.mul_comm _ (square f u), apply clear_term, /- u term...-/ rw myfld.mul_comm u c, repeat {rw myfld.mul_assoc}, repeat {rw myfld.mul_comm _ u}, repeat {rw <- myfld.mul_assoc}, repeat {rw mul_negate_alt f u _}, rw myfld.add_assoc (fourth_power f _) (u .* _) _, rw myfld.add_comm (fourth_power f _) (u .* _), repeat {rw <- myfld.add_assoc}, rw myfld.add_comm (u .* d) _, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (u .* d), repeat {rw <- myfld.add_assoc}, rw myfld.add_comm (u .* (.- ((two f) .* _))) _, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (u .* (.- ((two f) .* _))), repeat {rw myfld.add_assoc}, repeat {rw <- distrib_simp_alt f u _ _}, rw quartic_reduce_linear_helper, repeat {rw <- myfld.add_assoc}, apply clear_term, /- constant term...-/ rw quartic_reduce_constant_helper, end /- This is the solution to a cubic described under "alternative methods" on Wikipedia.-/ lemma depressed_quartic_to_quadratic_product (f : Type) [myfld f] (c d e p q s x : f) (p_ne_zero : p ≠ myfld.zero) : (c .+ (square f p)) = (s .+ q) /\ (d .* (myfld.reciprocal p p_ne_zero) = s .+ (.- q)) /\ (e = s .* q) -> depressed_quartic_subst f c d e x = (quadratic_subst f x myfld.one p q) .* (quadratic_subst f x myfld.one (.- p) s) := begin intros h, cases h with h1 h2, cases h2 with h2 h3, unfold quadratic_subst, rw one_mul_simp, repeat {rw distrib_simp}, repeat {rw distrib_simp_alt}, repeat {rw myfld.mul_assoc}, repeat {rw mul_negate_alt_simp}, repeat {rw mul_negate}, repeat {rw myfld.mul_comm (x .* x) _}, repeat {rw myfld.mul_comm x p}, repeat {rw myfld.mul_comm x s}, rw myfld.mul_comm (p .* x) s, rw myfld.mul_comm (p .* x) p, repeat {rw myfld.mul_assoc _ _ x}, repeat {rw <- myfld.mul_assoc _ x x}, rw myfld.add_comm (.- ((p .* x) .* (x .* x))), repeat {rw <- myfld.add_assoc}, rw myfld.add_assoc (.- ((p .* x) .* _)) _ _, rw myfld.add_comm (.- ((p .* x) .* _)) _, rw myfld.add_negate _, rw simp_zero, have clear_term : ∀ (a b x : f), a = b -> (x .+ a) = (x .+ b), intros a b x h, rw h, unfold depressed_quartic_subst, unfold fourth_power, repeat {rw <- myfld.mul_assoc}, apply clear_term, rw h3, clear h3, repeat {rw myfld.add_assoc}, rw myfld.mul_comm s q, repeat {rw myfld.add_comm _ (q .* s) }, apply clear_term, rw myfld.add_comm _ (.- (q .* (p .* x))), rw myfld.add_comm _ (s .* (p .* x)), rw <- mul_negate f _ (p .* x), repeat {rw <- myfld.add_assoc}, rw myfld.add_assoc (_ .* (p .* x)) (_ .* (p .* x)) _, rw <- distrib_simp f _ _ (p .* x), rw myfld.mul_assoc _ p x, have h3 : (d .* (myfld.reciprocal p p_ne_zero)) .* p = (s .+ (.- q)) .* p, rw h2, clear h2, rw <- myfld.mul_assoc at h3, rw myfld.mul_comm (myfld.reciprocal _ _) p at h3, rw myfld.mul_reciprocal p _ at h3, clear p_ne_zero, rw simp_mul_one at h3, rw myfld.add_comm _ (d .* x), rw h3, clear h3, rw myfld.add_comm s (.- q), apply clear_term, clear clear_term, rw myfld.mul_assoc p p _, rw <- mul_negate f _ (x .* x), repeat {rw <- distrib_simp f _ _ (x .* x) }, have h2 : (c .+ (square f p)) .+ (.- (square f p)) = (s .+ q) .+ (.- (square f p)) , rw h1, clear h1, rw <- myfld.add_assoc at h2, rw myfld.add_negate at h2, rw zero_simp at h2, rw h2, clear h2, unfold square, rw myfld.add_comm (.- _) _, repeat {rw myfld.add_assoc}, end lemma simultaneous_solution_helper (f : Type) [myfld f] [fld_not_char_two f] (c d e p q s : f) (p_ne_zero : p ≠ myfld.zero) : cubic_subst f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) (square f p) = myfld.zero -> e = ((myfld.reciprocal ((two f) .* (two f)) (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two)) .* ((fourth_power f p) .+ (((two f) .* (c .* (square f p))) .+ (square f c)))) .+ ((myfld.reciprocal ((two f) .* (two f)) (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two)) .* (.- (square f (d .* (myfld.reciprocal p p_ne_zero))))) := begin intros h_tmp, unfold cubic_subst at h_tmp, rw one_mul at h_tmp, rw mul_both_sides f _ _ (square f p) (square_ne_zero f p p_ne_zero), rw mul_negate_alt_simp, repeat {rw distrib_simp f _ _ (square f p) }, rw <- mul_two_squares f d _, rw mul_negate, repeat {rw <- myfld.mul_assoc}, rw mul_two_squares f _ p, rw myfld.mul_comm _ p, rw myfld.mul_reciprocal p _, have squ_one : ∀ (x : f), x .* (square f myfld.one) = x, intros x, unfold square, rw simp_mul_one, rw simp_mul_one, rw squ_one, clear squ_one, rw myfld.mul_comm (_ .+ _) (square f p), rw distrib_simp_alt f (square f p), rw mul_both_sides f _ _ (four f) (four_ne_zero f), unfold four, rw two_plus_two, repeat {rw distrib_simp f _ _ ((two f) .* (two f)) }, repeat {rw myfld.mul_comm (myfld.reciprocal ((two f) .* (two f)) _) _}, rw mul_negate, repeat {rw <- myfld.mul_assoc _ (myfld.reciprocal (_ .* _) _) (_ .* _) }, repeat {rw myfld.mul_comm (myfld.reciprocal (_ .* _) _) (_ .* _) }, repeat {rw myfld.mul_reciprocal _ _}, repeat {rw simp_mul_one f _}, have sixth_power : ((square f p) .* (fourth_power f p)) = (cubed f (square f p)), unfold square, unfold cubed, unfold fourth_power, repeat {rw myfld.mul_assoc}, rw sixth_power, clear sixth_power, rw carry_term_across_alt, symmetry, rw myfld.mul_comm (square f p) _, rw distrib_simp, rw distrib_simp at h_tmp, unfold four at h_tmp, rw two_plus_two at h_tmp, repeat {rw myfld.add_assoc}, repeat {rw myfld.add_assoc at h_tmp}, rw myfld.add_comm _ (.- (square f d)), rw myfld.add_comm _ (.- (square f d)) at h_tmp, repeat {rw myfld.add_assoc}, repeat {rw myfld.add_assoc at h_tmp}, unfold square, unfold cubed, unfold square at h_tmp, unfold cubed at h_tmp, rw myfld.mul_comm ((two f) .* (two f)) e at h_tmp, rw <- myfld.mul_assoc _ (two f) (two f), rw <- myfld.mul_assoc e (p .* p) _, rw myfld.mul_comm (p .* p) ((two f) .* (two f)), repeat {rw myfld.mul_assoc}, repeat {rw myfld.mul_assoc at h_tmp}, rw mul_negate at h_tmp, rw mul_negate at h_tmp, exact h_tmp, end lemma simultaneous_solution (f : Type) [myfld f] [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e p q s : f) (p_ne_zero : p ≠ myfld.zero) (int_quantity_ne_zero : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) : p = sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero) -> s = ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f p) .+ (d .* (myfld.reciprocal p p_ne_zero))))) -> q = ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f p) .+ ((.- d) .* (myfld.reciprocal p p_ne_zero))))) -> (c .+ (square f p)) = (s .+ q) /\ (d .* (myfld.reciprocal p p_ne_zero) = s .+ (.- q)) /\ (e = s .* q) := begin intros hp hs hq, split, rw hs, rw hq, rw mul_negate, rw <- distrib_simp_alt, rw myfld.add_assoc _ _ (.- _), rw myfld.add_comm _ (.- _), rw myfld.add_assoc _ (.- _) _, rw myfld.add_assoc _ _ (d .* (myfld.reciprocal p p_ne_zero)), rw <- myfld.add_assoc _ _ (.- _), rw myfld.add_negate, rw zero_simp, rw two_x_div_two, split, rw hs, rw hq, rw mul_negate_alt, rw <- distrib_simp_alt, rw mul_negate, repeat {rw add_negate}, rw double_negative, rw myfld.add_assoc (.- _) (.- _) _, rw <- add_negate, rw myfld.add_assoc c _ _, rw myfld.add_comm (c .+ _) _, rw myfld.add_assoc _ (.- (c .+ (square f p))) _, rw <- myfld.add_assoc _ _ (.- (c .+ (square f p))), rw myfld.add_negate, rw zero_simp, rw two_x_div_two, rw hs, rw hq, clear hs, clear hq, rw mul_negate, rw myfld.mul_assoc _ (myfld.reciprocal _ _) _, rw myfld.mul_comm _ (myfld.reciprocal _ _), rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _) _, rw <- myfld.mul_assoc _ (_ .+ _) (_ .+ _), rw mul_two_reciprocals, repeat {rw myfld.add_assoc c _ _}, rw difference_of_squares, have tmp : (square f (c .+ (square f p))) = (fourth_power f p) .+ (((two f) .* (c .* (square f p))) .+ (square f c)) , unfold square, unfold two, repeat {rw distrib_simp}, repeat {rw distrib_simp_alt}, unfold fourth_power, rw one_mul_simp, repeat {rw myfld.mul_assoc}, repeat {rw myfld.add_assoc}, rw myfld.add_comm _ (((p .* p) .* p) .* p), rw myfld.add_comm (c .* c) _, rw <- myfld.add_assoc _ (c .* c) _, rw myfld.add_comm (c .* c) _, rw myfld.mul_comm (p .* p) c, repeat {rw myfld.mul_assoc}, repeat {rw myfld.add_assoc}, rw tmp, clear tmp, rw only_one_reciprocal f ((two f) .* (two f)) _ (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two), apply simultaneous_solution_helper f c d e p q s p_ne_zero, rw hp, repeat {rw sqrt_squared}, exact cubic_formula_a_correct f myfld.one _ _ _ (myfld.zero_distinct_one) int_quantity_ne_zero, end lemma depressed_quartic_to_quadratic_product_solved (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e x : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : (depressed_quartic_subst f c d e x) = ((quadratic_subst f x myfld.one (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ ((.- d) .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b))))))) .* (quadratic_subst f x myfld.one (.- (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ (d .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))))) := begin apply depressed_quartic_to_quadratic_product, apply simultaneous_solution, refl, refl, refl, end lemma depressed_quartic_to_linear_factorization (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e x : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : (depressed_quartic_subst f c d e x) = (x .+ .- (quadratic_formula f myfld.one (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ ((.- d) .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one)) .* (x .+ .- (quadratic_formula_alt f myfld.one (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ ((.- d) .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one)) .* (x .+ .- (quadratic_formula f myfld.one (.- (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ ((d) .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one)) .* (x .+ .- (quadratic_formula_alt f myfld.one (.- (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ ((d) .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one)) := begin rw depressed_quartic_to_quadratic_product_solved f c d e x int_quantity_ne_zero_a int_quantity_ne_zero_b, rw <- quadratic_factorize, rw <- quadratic_factorize, repeat {rw myfld.mul_assoc}, end /- We now need to devote a bit of space to some fairly trivial boilerplate to make the solution to a product of quadratics explicit.-/ lemma quadratic_product_solution (f : Type) [myfld f] [fld_not_char_two f] [fld_with_sqrt f] (b1 b2 c1 c2 x : f) : ((x = quadratic_formula f myfld.one b1 c1 myfld.zero_distinct_one) \/ (x = quadratic_formula_alt f myfld.one b1 c1 myfld.zero_distinct_one) \/ (x = quadratic_formula f myfld.one b2 c2 myfld.zero_distinct_one) \/ (x = quadratic_formula_alt f myfld.one b2 c2 myfld.zero_distinct_one)) -> (quadratic_subst f x myfld.one b1 c1) .* (quadratic_subst f x myfld.one b2 c2) = myfld.zero := begin intros h, cases h, have h1 : (quadratic_subst f x myfld.one b1 c1) = myfld.zero, rw h, exact quadratic_formula_works f myfld.one b1 c1 myfld.zero_distinct_one, rw h1, exact mul_zero f _, cases h, have h1 : (quadratic_subst f x myfld.one b1 c1) = myfld.zero, rw h, exact quadratic_formula_alt_works f myfld.one b1 c1 myfld.zero_distinct_one, rw h1, exact mul_zero f _, cases h, have h1 : (quadratic_subst f x myfld.one b2 c2) = myfld.zero, rw h, exact quadratic_formula_works f myfld.one b2 c2 myfld.zero_distinct_one, rw h1, exact zero_mul f _, have h1 : (quadratic_subst f x myfld.one b2 c2) = myfld.zero, rw h, exact quadratic_formula_alt_works f myfld.one b2 c2 myfld.zero_distinct_one, rw h1, exact zero_mul f _, end lemma quadratic_product_solution_unique (f : Type) [myfld f] [fld_not_char_two f] [fld_with_sqrt f] (b1 b2 c1 c2 x : f) : (x ≠ quadratic_formula f myfld.one b1 c1 myfld.zero_distinct_one) -> (x ≠ quadratic_formula_alt f myfld.one b1 c1 myfld.zero_distinct_one) -> (x ≠ quadratic_formula f myfld.one b2 c2 myfld.zero_distinct_one) -> (x ≠ quadratic_formula_alt f myfld.one b2 c2 myfld.zero_distinct_one) -> (quadratic_subst f x myfld.one b1 c1) .* (quadratic_subst f x myfld.one b2 c2) ≠ myfld.zero := begin intros h1 h2 h3 h4, have left_ne_zero : (quadratic_subst f x myfld.one b1 c1) ≠ myfld.zero, apply quadratic_solution_unique f myfld.one b1 c1 _ myfld.zero_distinct_one, split, cc, cc, have right_ne_zero : (quadratic_subst f x myfld.one b2 c2) ≠ myfld.zero, apply quadratic_solution_unique f myfld.one b2 c2 _ myfld.zero_distinct_one, split, cc, cc, exact mul_nonzero f _ _ left_ne_zero right_ne_zero, end def depressed_quartic_solution_a (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e: f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quadratic_formula f myfld.one (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ ((.- d) .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one) lemma depressed_quartic_solution_a_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : depressed_quartic_subst f c d e (depressed_quartic_solution_a f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) = myfld.zero := begin rw depressed_quartic_to_quadratic_product_solved, apply quadratic_product_solution, left, unfold depressed_quartic_solution_a, exact int_quantity_ne_zero_b, end def depressed_quartic_solution_b (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quadratic_formula_alt f myfld.one (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ ((.- d) .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one) lemma depressed_quartic_solution_b_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : depressed_quartic_subst f c d e (depressed_quartic_solution_b f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) = myfld.zero := begin rw depressed_quartic_to_quadratic_product_solved, apply quadratic_product_solution, right, left, unfold depressed_quartic_solution_b, exact int_quantity_ne_zero_b, end def depressed_quartic_solution_c (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quadratic_formula f myfld.one (.- (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ (d .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one) lemma depressed_quartic_solution_c_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : depressed_quartic_subst f c d e (depressed_quartic_solution_c f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) = myfld.zero := begin rw depressed_quartic_to_quadratic_product_solved, apply quadratic_product_solution, right, right, left, unfold depressed_quartic_solution_c, exact int_quantity_ne_zero_b, end def depressed_quartic_solution_d (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quadratic_formula_alt f myfld.one (.- (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) ((myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (c .+ ((square f (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a))) .+ (d .* (myfld.reciprocal (sqroot (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a)) (sqrt_ne_zero f (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) int_quantity_ne_zero_b)))))) myfld.zero_distinct_one) lemma depressed_quartic_solution_d_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : depressed_quartic_subst f c d e (depressed_quartic_solution_d f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) = myfld.zero := begin rw depressed_quartic_to_quadratic_product_solved, apply quadratic_product_solution, right, right, right, unfold depressed_quartic_solution_d, exact int_quantity_ne_zero_b, end lemma depressed_quartic_solution_uniqueness (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d e x : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f c) .+ (.- ((four f) .* e))))) .+ (.- (square f ((two f) .* c)))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* c) ((square f c) .+ (.- ((four f) .* e))) (.- (square f d)) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : (x ≠ (depressed_quartic_solution_a f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b)) -> (x ≠ (depressed_quartic_solution_b f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b)) -> (x ≠ (depressed_quartic_solution_c f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b)) -> (x ≠ (depressed_quartic_solution_d f c d e int_quantity_ne_zero_a int_quantity_ne_zero_b)) -> (depressed_quartic_subst f c d e x ≠ myfld.zero) := begin intros ha hb hc hd, rw depressed_quartic_to_quadratic_product_solved, apply quadratic_product_solution_unique, unfold depressed_quartic_solution_a at ha, exact ha, unfold depressed_quartic_solution_b at hb, exact hb, unfold depressed_quartic_solution_c at hc, exact hc, unfold depressed_quartic_solution_d at hd, exact hd, exact int_quantity_ne_zero_b, end /- This is the end of the actual interesting content in this file. The remainder is just an enormous amount of boilerplate to make it explicit that the four solutions to a depressed quartic imply four solutions to a full quartic. This should be obvious from all of the above to any thinking reader, but it still seemed incomplete to not make it explicit. -/ def quartic_formula_int_a (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := ((depressed_quartic_solution_a f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) .+ (.- (b .* (myfld.reciprocal (four f) (four_ne_zero f))))) lemma quartic_formula_int_a_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : (quartic_expression f (quartic_formula_int_a f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) myfld.one b c d e) = myfld.zero := begin rw reduce_quartic_to_depressed f b c d e (quartic_formula_int_a f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) (depressed_quartic_solution_a f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) _, apply depressed_quartic_solution_a_works, unfold quartic_formula_int_a, end def quartic_formula_a (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quartic_formula_int_a f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)) int_quantity_ne_zero_a int_quantity_ne_zero_b) lemma quartic_formula_a_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : quartic_expression f (quartic_formula_a f a b c d e a_ne_zero int_quantity_ne_zero_a int_quantity_ne_zero_b) a b c d e = myfld.zero := begin rw remove_fourth_power_coefficient, unfold quartic_formula_a, exact quartic_formula_int_a_works f _ _ _ _ int_quantity_ne_zero_a int_quantity_ne_zero_b, end def quartic_formula_int_b (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := ((depressed_quartic_solution_b f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) .+ (.- (b .* (myfld.reciprocal (four f) (four_ne_zero f))))) lemma quartic_formula_int_b_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : (quartic_expression f (quartic_formula_int_b f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) myfld.one b c d e) = myfld.zero := begin rw reduce_quartic_to_depressed f b c d e (quartic_formula_int_b f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) (depressed_quartic_solution_b f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) _, apply depressed_quartic_solution_b_works, unfold quartic_formula_int_b, end def quartic_formula_b (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quartic_formula_int_b f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)) int_quantity_ne_zero_a int_quantity_ne_zero_b) lemma quartic_formula_b_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : quartic_expression f (quartic_formula_b f a b c d e a_ne_zero int_quantity_ne_zero_a int_quantity_ne_zero_b) a b c d e = myfld.zero := begin rw remove_fourth_power_coefficient, unfold quartic_formula_b, exact quartic_formula_int_b_works f _ _ _ _ int_quantity_ne_zero_a int_quantity_ne_zero_b, end def quartic_formula_int_c (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := ((depressed_quartic_solution_c f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) .+ (.- (b .* (myfld.reciprocal (four f) (four_ne_zero f))))) lemma quartic_formula_int_c_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : (quartic_expression f (quartic_formula_int_c f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) myfld.one b c d e) = myfld.zero := begin rw reduce_quartic_to_depressed f b c d e (quartic_formula_int_c f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) (depressed_quartic_solution_c f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) _, apply depressed_quartic_solution_c_works, unfold quartic_formula_int_c, end def quartic_formula_c (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quartic_formula_int_c f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)) int_quantity_ne_zero_a int_quantity_ne_zero_b) lemma quartic_formula_c_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : quartic_expression f (quartic_formula_c f a b c d e a_ne_zero int_quantity_ne_zero_a int_quantity_ne_zero_b) a b c d e = myfld.zero := begin rw remove_fourth_power_coefficient, unfold quartic_formula_c, exact quartic_formula_int_c_works f _ _ _ _ int_quantity_ne_zero_a int_quantity_ne_zero_b, end def quartic_formula_int_d (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := ((depressed_quartic_solution_d f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) .+ (.- (b .* (myfld.reciprocal (four f) (four_ne_zero f))))) lemma quartic_formula_int_d_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (b c d e : f) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f b c))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f b c)) ((square f (depressed_quartic_squ_coeff f b c)) .+ (.- ((four f) .* (depressed_quartic_constant f b c d e)))) (.- (square f (depressed_quartic_linear_coeff f b c d))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : (quartic_expression f (quartic_formula_int_d f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) myfld.one b c d e) = myfld.zero := begin rw reduce_quartic_to_depressed f b c d e (quartic_formula_int_d f b c d e int_quantity_ne_zero_a int_quantity_ne_zero_b) (depressed_quartic_solution_d f (depressed_quartic_squ_coeff f b c) (depressed_quartic_linear_coeff f b c d) (depressed_quartic_constant f b c d e) int_quantity_ne_zero_a int_quantity_ne_zero_b) _, apply depressed_quartic_solution_d_works, unfold quartic_formula_int_d, end def quartic_formula_d (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : f := (quartic_formula_int_d f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)) int_quantity_ne_zero_a int_quantity_ne_zero_b) lemma quartic_formula_d_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d e : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero_a : (((three f) .* (myfld.one .* ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))))) .+ (.- (square f ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero))))))) ≠ myfld.zero) (int_quantity_ne_zero_b : (cubic_formula_a f myfld.one ((two f) .* (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) ((square f (depressed_quartic_squ_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((four f) .* (depressed_quartic_constant f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (e .* (myfld.reciprocal a a_ne_zero)))))) (.- (square f (depressed_quartic_linear_coeff f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero))))) myfld.zero_distinct_one int_quantity_ne_zero_a) ≠ myfld.zero) : quartic_expression f (quartic_formula_d f a b c d e a_ne_zero int_quantity_ne_zero_a int_quantity_ne_zero_b) a b c d e = myfld.zero := begin rw remove_fourth_power_coefficient, unfold quartic_formula_d, exact quartic_formula_int_d_works f _ _ _ _ int_quantity_ne_zero_a int_quantity_ne_zero_b, end
907a0f791d2df62358a25596434dd12815081519
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/homotopy/wedge.hlean
ba1e73490f7efb3ce2f382f9493ab10616aafd7d
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
3,656
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Ulrik Buchholtz The Wedge Sum of Two Pointed Types -/ import hit.pushout .connectedness types.unit open eq pushout pointed unit trunc_index definition wedge (A B : Type*) : Type := ppushout (pconst punit A) (pconst punit B) local attribute wedge [reducible] definition pwedge [constructor] (A B : Type*) : Type* := pointed.mk' (wedge A B) infixr ` ∨ ` := pwedge namespace wedge protected definition rec {A B : Type*} {P : wedge A B → Type} (Pinl : Π(x : A), P (inl x)) (Pinr : Π(x : B), P (inr x)) (Pglue : pathover P (Pinl pt) (glue ⋆) (Pinr pt)) (y : wedge A B) : P y := by induction y; apply Pinl; apply Pinr; induction x; exact Pglue protected definition elim {A B : Type*} {P : Type} (Pinl : A → P) (Pinr : B → P) (Pglue : Pinl pt = Pinr pt) (y : wedge A B) : P := by induction y with a b x; exact Pinl a; exact Pinr b; induction x; exact Pglue end wedge attribute wedge.rec wedge.elim [recursor 7] [unfold 7] namespace wedge -- TODO maybe find a cleaner proof protected definition unit (A : Type*) : A ≃* pwedge punit A := begin fapply pequiv_of_pmap, { fapply pmap.mk, intro a, apply pinr a, apply respect_pt }, { fapply is_equiv.adjointify, intro x, fapply pushout.elim_on x, exact λ x, Point A, exact id, intro u, reflexivity, intro x, fapply pushout.rec_on x, intro u, cases u, esimp, apply (glue unit.star)⁻¹, intro a, reflexivity, intro u, cases u, esimp, apply eq_pathover, refine _ ⬝hp !ap_id⁻¹, fapply eq_hconcat, apply ap_compose inr, krewrite elim_glue, fapply eq_hconcat, apply ap_idp, apply square_of_eq, apply con.left_inv, intro a, reflexivity}, end end wedge open trunc is_trunc is_conn function namespace wedge_extension section -- The wedge connectivity lemma (Lemma 8.6.2) parameters {A B : Type*} (n m : ℕ) [cA : is_conn n A] [cB : is_conn m B] (P : A → B → Type) [HP : Πa b, is_trunc (m + n) (P a b)] (f : Πa : A, P a pt) (g : Πb : B, P pt b) (p : f pt = g pt) include cA cB HP private definition Q (a : A) : Type := fiber (λs : (Πb : B, P a b), s (Point B)) (f a) private definition is_trunc_Q (a : A) : is_trunc (n.-1) (Q a) := begin refine @is_conn.elim_general (m.-1) _ _ _ (P a) _ (f a), rewrite [-succ_add_succ, of_nat_add_of_nat], intro b, apply HP end local attribute is_trunc_Q [instance] private definition Q_sec : Πa : A, Q a := is_conn.elim (n.-1) Q (fiber.mk g p⁻¹) protected definition ext : Π(a : A)(b : B), P a b := λa, fiber.point (Q_sec a) protected definition β_left (a : A) : ext a (Point B) = f a := fiber.point_eq (Q_sec a) private definition coh_aux : Σq : ext (Point A) = g, β_left (Point A) = ap (λs : (Πb : B, P (Point A) b), s (Point B)) q ⬝ p⁻¹ := equiv.to_fun (fiber.fiber_eq_equiv (Q_sec (Point A)) (fiber.mk g p⁻¹)) (is_conn.elim_β (n.-1) Q (fiber.mk g p⁻¹)) protected definition β_right (b : B) : ext (Point A) b = g b := apd10 (sigma.pr1 coh_aux) b private definition lem : β_left (Point A) = β_right (Point B) ⬝ p⁻¹ := begin unfold β_right, unfold β_left, krewrite (apd10_eq_ap_eval (sigma.pr1 coh_aux) (Point B)), exact sigma.pr2 coh_aux, end protected definition coh : (β_left (Point A))⁻¹ ⬝ β_right (Point B) = p := by rewrite [lem,con_inv,inv_inv,con.assoc,con.left_inv] end end wedge_extension
2106d1eea49aa722bd73c46e4946619121018f59
75bd9c50a345718d735a7533c007cf45f9da9a83
/src/data/mv_polynomial/variables.lean
2c8e7f6b4207b06489f4f1d4142caa53d067c58a
[ "Apache-2.0" ]
permissive
jtbarker/mathlib
a1a3b1ddc16179826260578410746756ef18032c
392d3e376b44265ef2dedbd92231d3177acc1fd0
refs/heads/master
1,671,246,411,096
1,600,801,712,000
1,600,801,712,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,265
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.basic import data.set.disjointed /-! # Degrees and variables of polynomials This file establishes many results about the degree and variable sets of a multivariate polynomial. The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$ that appears in a monomial in $P$. The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a monomial of $P$. ## Main declarations * `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `mv_polynomial.degree_of n p : ℕ` -- the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `mv_polynomial.total_degree p : ℕ` -- the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Notation As in other polynomial files we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} section degrees /-! ### `degrees` -/ /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees (p : mv_polynomial σ R) : multiset σ := p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset := finset.sup_le $ assume t h, begin have := finsupp.support_single_subset h, rw [finset.mem_singleton] at this, rw this end lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) : degrees (monomial s a) = s.to_multiset := le_antisymm (degrees_monomial s a) $ finset.le_sup $ by rw [monomial, finsupp.support_single_ne_zero ha, finset.mem_singleton] lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 := multiset.le_zero.1 $ degrees_monomial _ _ lemma degrees_X (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} := le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _ lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 := by { rw ← C_0, exact degrees_C 0 } lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1 lemma degrees_add (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin refine finset.sup_le (assume b hb, _), have := finsupp.support_add hb, rw finset.mem_union at this, cases this, { exact le_sup_left_of_le (finset.le_sup this) }, { exact le_sup_right_of_le (finset.le_sup this) }, end lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) := begin refine s.induction _ _, { simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ }, { assume i s his ih, rw [finset.sup_insert, finset.sum_insert his], exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) } end lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees := begin refine finset.sup_le (assume b hb, _), have := support_mul p q hb, simp only [finset.mem_bind, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.to_multiset_add], exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) end lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees := begin refine s.induction _ _, { simp only [finset.prod_empty, finset.sum_empty, degrees_one] }, { assume i s his ih, rw [finset.prod_insert his, finset.sum_insert his], exact le_trans (degrees_mul _ _) (add_le_add_left ih _) } end lemma degrees_pow (p : mv_polynomial σ R) : ∀(n : ℕ), (p^n).degrees ≤ n •ℕ p.degrees | 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end | (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) lemma mem_degrees {p : mv_polynomial σ R} {i : σ} : i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support := by simp only [degrees, finset.mem_sup, ← finsupp.mem_support_iff, coeff, finsupp.mem_to_multiset, exists_prop] lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) : p.degrees ≤ (p + q).degrees := begin apply finset.sup_le, intros d hd, rw multiset.disjoint_iff_ne at h, rw multiset.le_iff_count, intros i, rw [degrees, multiset.count_sup], simp only [finsupp.count_to_multiset], by_cases h0 : d = 0, { simp only [h0, zero_le, finsupp.zero_apply], }, { refine @finset.le_sup _ _ _ (p + q).support _ d _, rw [finsupp.mem_support_iff, ← coeff, coeff_add], suffices : q.coeff d = 0, { rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], }, rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0, obtain ⟨j, hj⟩ := h0, contrapose! h, rw finsupp.mem_support_iff at hd, refine ⟨j, _, j, _, rfl⟩, all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } } end lemma degrees_add_of_disjoint {p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) : (p + q).degrees = p.degrees ∪ q.degrees := begin apply le_antisymm, { apply degrees_add }, { apply multiset.union_le, { apply le_degrees_add h }, { rw add_comm, apply le_degrees_add h.symm } } end lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) : (map f p).degrees ⊆ p.degrees := begin dsimp only [degrees], apply multiset.subset_of_le, convert finset.sup_subset _ _, apply mv_polynomial.support_map_subset end lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R) {f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees := by simp only [degrees, mv_polynomial.support_map_of_injective _ hf] end degrees section vars /-! ### `vars` -/ /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ R) : finset σ := p.degrees.to_finset @[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support := by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C a : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_C, multiset.to_finset_zero] @[simp] lemma vars_X (h : 0 ≠ (1 : R)) : (X n : mv_polynomial σ R).vars = {n} := by rw [X, vars_monomial h.symm, finsupp.support_single_ne_zero (one_ne_zero : 1 ≠ 0)] lemma mem_vars (i : σ) : i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support := by simp only [vars, multiset.mem_to_finset, mem_degrees, coeff, finsupp.mem_support_iff, exists_prop] lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) : x v = 0 := begin rw [vars, multiset.mem_to_finset] at h, rw ←not_mem_support_iff, contrapose! h, unfold degrees, rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H), rw finset.sup_insert, simp only [multiset.mem_union, multiset.sup_eq_union], left, rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h, end lemma vars_add_subset (p q : mv_polynomial σ R) : (p + q).vars ⊆ p.vars ∪ q.vars := begin intros x hx, simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢, simpa using multiset.mem_of_le (degrees_add _ _) hx, end lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) : (p + q).vars = p.vars ∪ q.vars := begin apply finset.subset.antisymm (vars_add_subset p q), intros x hx, simp only [vars, multiset.disjoint_to_finset] at h hx ⊢, rw [degrees_add_of_disjoint h, multiset.to_finset_union], exact hx end section mul lemma vars_mul (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars := begin intro i, simp only [mem_vars, finset.mem_union], rintro ⟨d, hd, hi⟩, rw [finsupp.mem_support_iff, ← coeff, coeff_mul] at hd, contrapose! hd, cases hd, rw finset.sum_eq_zero, rintro ⟨d₁, d₂⟩ H, rw finsupp.mem_antidiagonal_support at H, subst H, obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support, { simpa only [finset.mem_union] using finsupp.support_add hi, }, { suffices : coeff d₁ φ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, { suffices : coeff d₂ ψ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, end @[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ := vars_C lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars := begin induction n with n ih, { simp }, { rw pow_succ, apply finset.subset.trans (vars_mul _ _), exact finset.union_subset (finset.subset.refl _) ih } end /-- The variables of the product of a family of polynomials are a subset of the union of the sets of variables of each polynomial. -/ lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ R) : (∏ i in s, f i).vars ⊆ s.bind (λ i, (f i).vars) := begin apply s.induction_on, { simp }, { intros a s hs hsub, simp only [hs, finset.bind_insert, finset.prod_insert, not_false_iff], apply finset.subset.trans (vars_mul _ _), exact finset.union_subset_union (finset.subset.refl _) hsub } end section integral_domain variables {A : Type*} [integral_domain A] lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars := begin ext1 i, simp only [mem_vars, exists_prop, finsupp.mem_support_iff], apply exists_congr, intro d, apply and_congr _ iff.rfl, rw [← coeff, ← coeff, coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and], end end integral_domain end mul section sum variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R) lemma vars_sum_subset : (∑ i in t, φ i).vars ⊆ finset.bind t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bind_insert, finset.sum_insert has], refine finset.subset.trans (vars_add_subset _ _) (finset.union_subset_union (finset.subset.refl _) _), assumption } end lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) : (∑ i in t, φ i).vars = finset.bind t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bind_insert, finset.sum_insert has, vars_add_of_disjoint, hsum], unfold pairwise on_fun at h, rw hsum, simp only [finset.disjoint_iff_ne] at h ⊢, intros v hv v2 hv2, rw finset.mem_bind at hv2, rcases hv2 with ⟨i, his, hi⟩, refine h a i _ _ hv _ hi, rintro rfl, contradiction } end end sum section map variables [comm_semiring S] (f : R →+* S) variable (p) lemma vars_map : (map f p).vars ⊆ p.vars := by simp [vars, degrees_map] variable {f} lemma vars_map_of_injective (hf : injective f) : (map f p).vars = p.vars := by simp [vars, degrees_map_of_injective _ hf] lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) : (monomial (finsupp.single i e) r).vars = {i} := by rw [vars_monomial hr, finsupp.support_single_ne_zero he] lemma vars_eq_support_bind_support : p.vars = p.support.bind finsupp.support := by { ext i, rw [mem_vars, finset.mem_bind] } end map end vars section degree_of /-! ### `degree_of` -/ /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := p.degrees.count n end degree_of section total_degree /-! ### `total_degree` -/ /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e) lemma total_degree_eq (p : mv_polynomial σ R) : p.total_degree = p.support.sup (λm, m.to_multiset.card) := begin rw [total_degree], congr, funext m, exact (finsupp.card_to_multiset _).symm end lemma total_degree_le_degrees_card (p : mv_polynomial σ R) : p.total_degree ≤ p.degrees.card := begin rw [total_degree_eq], exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs) end @[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 := nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn, have _ := finsupp.support_single_subset hn, begin rw [finset.mem_singleton] at this, subst this, exact le_refl _ end @[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : R) @[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 := total_degree_C (1 : R) @[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) : (X s : mv_polynomial σ R).total_degree = 1 := begin rw [total_degree, X, monomial, finsupp.support_single_ne_zero (one_ne_zero : (1 : R) ≠ 0)], simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq], end lemma total_degree_add (a b : mv_polynomial σ R) : (a + b).total_degree ≤ max a.total_degree b.total_degree := finset.sup_le $ assume n hn, have _ := finsupp.support_add hn, begin rw finset.mem_union at this, cases this, { exact le_max_left_of_le (finset.le_sup this) }, { exact le_max_right_of_le (finset.le_sup this) } end lemma total_degree_mul (a b : mv_polynomial σ R) : (a * b).total_degree ≤ a.total_degree + b.total_degree := finset.sup_le $ assume n hn, have _ := add_monoid_algebra.support_mul a b hn, begin simp only [finset.mem_bind, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.sum_add_index], { exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) }, { assume a, refl }, { assume a b₁ b₂, refl } end lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) : (a ^ n).total_degree ≤ n * a.total_degree := begin induction n with n ih, { simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] }, rw pow_succ, calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _ ... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _ ... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm] end lemma total_degree_list_prod : ∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum | [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl | (p :: ps) := begin rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons], exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _) end lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) : s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum := begin refine quotient.induction_on s (assume l, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum], exact total_degree_list_prod l end lemma total_degree_finset_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ) (h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) : ∃ i, d i < n := begin contrapose! h, calc n * fintype.card σ = ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ] ... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s) ... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl } ... ≤ f.total_degree : finset.le_sup hd, end lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ} (h : f.total_degree < ∑ i in d.support, d i) : coeff d f = 0 := begin classical, rw [total_degree, finset.sup_lt_iff] at h, { specialize h d, rw mem_support_iff at h, refine not_not.mp (mt h _), exact lt_irrefl _, }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end end total_degree section eval_vars /-! ### `vars` and `eval` -/ variables {S₁ : Type v} {S₂ : Type w} (f : σ → S₁) variables [comm_semiring S₁] [algebra R S₁] [comm_semiring S₂] lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S₂) {g : σ → S₂} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : eval₂_hom f g p = f (constant_coeff p) := begin conv_lhs { rw p.as_sum }, simp only [ring_hom.map_sum, eval₂_hom_monomial], by_cases h0 : constant_coeff p = 0, work_on_goal 0 { rw [h0, f.map_zero, finset.sum_eq_zero], intros d hd }, work_on_goal 1 { rw [finset.sum_eq_single (0 : σ →₀ ℕ)], { rw [finsupp.prod_zero_index, mul_one], refl }, intros d hd hd0, }, repeat { obtain ⟨i, hi⟩ : d.support.nonempty, { rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0, rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty], rintro rfl, contradiction }, rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)], rw [mem_vars], exact ⟨d, hd, hi⟩ }, { rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0, intro, contradiction } end lemma aeval_eq_constant_coeff_of_vars [algebra R S₂] {g : σ → S₂} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : aeval g p = algebra_map _ _ (constant_coeff p) := eval₂_hom_eq_constant_coeff_of_vars _ hp end eval_vars end comm_semiring end mv_polynomial
635f598f3faa23ef8ace3614cd9fb622bda0fc57
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/compiler/exportattr.lean
92b791dd252085b065b61949a361d30b85ba389e
[ "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
1,274
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.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 | (Name.mkString Name.anonymous s) := isValidCppId s | (Name.mkString p s) := isValidCppId s && isValidCppName p | _ := false def mkExportAttr : IO (ParametricAttribute Name) := registerParametricAttribute `export "name to be used by code generators" $ fun _ _ stx => match attrParamSyntaxToIdentifier stx with | some exportName => if isValidCppName exportName then Except.ok exportName else Except.error "invalid 'export' function name, is not a valid C++ identifier" | _ => Except.error "unexpected kind of argument" @[init mkExportAttr] constant exportAttr : ParametricAttribute Name := default _ @[export lean.get_export_name_for_core] def getExportNameFor (env : Environment) (n : Name) : Option Name := exportAttr.getParam env n def isExport (env : Environment) (n : Name) : Bool := (getExportNameFor env n).isSome end Lean
5dbee5ae8516079ba2ccdb4afed5f743646e596a
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/computability/turing_machine.lean
1d1fa76fa0a679293295f7fe4f90a5e22a1f78c2
[ "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
109,917
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.order import data.fintype.basic import data.pfun import tactic.apply_fun import logic.function.iterate /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `machine` is the set of all machines in the model. Usually this is approximately a function `Λ → stmt`, although different models have different ways of halting and other actions. * `step : cfg → option cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : input → cfg` sets up the initial state. The type `input` depends on the model; in most cases it is `list Γ`. * `eval : machine → input → roption output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to the final state to obtain the result. The type `output` depends on the model. * `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ open relation open nat (iterate) open function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace turing /-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default Γ`) to the end of `l₁`. -/ def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := ∃ n, l₂ = l₁ ++ list.repeat (default Γ) n @[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩ @[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩ theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l l₁ → blank_extends l l₂ → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i, simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h, simp only [← list.repeat_add, nat.add_sub_cancel' h, list.append_assoc], end /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : {l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l₁ l → blank_extends l₂ l → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j, refine list.append_right_cancel (e.symm.trans _), rw [list.append_assoc, ← list.repeat_add, nat.sub_add_cancel], apply_fun list.length at e, simp only [list.length_append, list.length_repeat] at e, rwa [← add_le_add_iff_left, e, add_le_add_iff_right] end /-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/ def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := blank_extends l₁ l₂ ∨ blank_extends l₂ l₁ @[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l := or.inl (blank_extends.refl _) @[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm @[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := begin rintro (h₁|h₁) (h₂|h₂), { exact or.inl (h₁.trans h₂) }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.above_of_le h₂ h) }, { exact or.inr (h₂.above_of_le h₁ h) } }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.below_of_le h₂ h) }, { exact or.inr (h₂.below_of_le h₁ h) } }, { exact or.inr (h₂.trans h₁) }, end /-- Given two `blank_rel` lists, there exists (constructively) a common join. -/ def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l₁ l ∧ blank_extends l₂ l} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end /-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/ def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l l₁ ∧ blank_extends l l₂} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩ else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) := ⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩ /-- Construct a setoid instance for `blank_rel`. -/ def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩ /-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ) instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩ instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩ /-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger precondition `blank_extends` instead of `blank_rel`. -/ @[elab_as_eliminator, reducible] protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α) (H : ∀ a b, blank_extends a b → f a = f b) : α := l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm] /-- The quotient map turning a `list` into a `list_blank`. -/ def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk' @[elab_as_eliminator] protected lemma list_blank.induction_on {Γ} [inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h /-- The head of a `list_blank` is well defined. -/ def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ := l.lift_on list.head begin rintro _ _ ⟨i, rfl⟩, cases a, {cases i; refl}, refl end @[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.head (list_blank.mk l) = l.head := rfl /-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/ def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk l.tail) begin rintro _ _ ⟨i, rfl⟩, refine quotient.sound' (or.inl _), cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩] end @[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl /-- We can cons an element onto a `list_blank`. -/ def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk (list.cons a l)) begin rintro _ _ ⟨i, rfl⟩, exact quotient.sound' (or.inl ⟨i, rfl⟩), end @[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl @[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).head = a := quotient.ind' $ by exact λ l, rfl @[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).tail = l := quotient.ind' $ by exact λ l, rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ @[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] : ∀ (l : list_blank Γ), l.tail.cons l.head = l := quotient.ind' begin refine (λ l, quotient.sound' (or.inr _)), cases l, {exact ⟨1, rfl⟩}, {refl}, end /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) : ∃ a l', l = list_blank.cons a l' := ⟨_, _, (list_blank.cons_head_tail _).symm⟩ /-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/ def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ := l.lift_on (λ l, list.inth l n) begin rintro l _ ⟨i, rfl⟩, simp only [list.inth], cases lt_or_le _ _ with h h, {rw list.nth_append h}, rw list.nth_len_le h, cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂}, rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat] end @[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) : (list_blank.mk l).nth n = l.inth n := rfl @[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H, begin wlog h : l₁.length ≤ l₂.length using l₁ l₂, swap, { exact (this $ λ i, (H i).symm).symm }, refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩), refine list.ext_le _ (λ i h h₂, eq.symm _), { simp only [nat.add_sub_of_le h, list.length_append, list.length_repeat] }, simp at H, cases lt_or_le i l₁.length with h' h', { simpa only [list.nth_le_append _ h', list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i }, { simpa only [list.nth_le_append_right h', list.nth_le_repeat, list.nth_le_nth h, list.nth_len_le h', option.iget] using H i }, end /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ | 0 L := L.tail.cons (f L.head) | (n+1) L := (L.tail.modify_nth n).cons L.head theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) : (L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i := begin induction n with n IH generalizing i L, { cases i; simp only [list_blank.nth_zero, if_true, list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true, list_blank.nth_succ, if_false, list_blank.tail_cons] }, { cases i, { rw if_neg (nat.succ_ne_zero _).symm, simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] }, { simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons], congr } } end /-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/ structure {u v} pointed_map (Γ : Type u) (Γ' : Type v) [inhabited Γ] [inhabited Γ'] : Type (max u v) := (f : Γ → Γ') (map_pt' : f (default _) = default _) instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') := ⟨⟨λ _, default _, rfl⟩⟩ instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') := ⟨_, pointed_map.f⟩ @[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl @[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _ @[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head := by cases l; [exact (pointed_map.map_pt f).symm, refl] /-- The `map` function on lists is well defined on `list_blank`s provided that the map is pointed. -/ def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.map f l)) begin rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩), simp only [pointed_map.map_pt, list.map_append, list.map_repeat], end @[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl @[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := begin refine (list_blank.cons_head_tail _).symm.trans _, simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons] end @[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := l.induction_on begin intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth], cases l.nth n, {exact f.2.symm}, {refl} end /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) : pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) (L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw list_blank.nth_map; refl theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) : (L.modify_nth f n).map F = (L.map F).modify_nth f' n := by induction n with n IH generalizing L; simp only [*, list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map] /-- Append a list on the left side of a list_blank. -/ @[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ | [] L := L | (a :: l) L := list_blank.cons a (list_blank.append l L) @[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := by induction l₁; simp only [*, list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk] theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc] /-- The `bind` function on lists is well defined on `list_blank`s provided that the default element is sent to a sequence of default elements. -/ def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list_blank Γ) (f : Γ → list Γ') (hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.bind l f)) begin rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩), rw [list.bind_append, mul_comm], congr, induction i with i IH, refl, simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind], end @[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list Γ) (f : Γ → list Γ') (hf) : (list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl @[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := l.induction_on $ by intro; simp only [list_blank.append_mk, list_blank.bind_mk, list_blank.cons_mk, list.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `list_blank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is consed onto the left side. -/ structure tape (Γ : Type*) [inhabited Γ] := (head : Γ) (left : list_blank Γ) (right : list_blank Γ) instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) := ⟨by constructor; apply default⟩ /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq, derive inhabited] inductive dir | left | right /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩ | dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.left).move dir.right = T := by cases T; simp [tape.move] @[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.right).move dir.left = T := by cases T; simp [tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).left = L := rfl @[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).head = R.head := rfl @[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right = R.tail := rfl @[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right₀ = R := list_blank.cons_head_tail _ @[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) : tape.mk' T.left T.right₀ = T := by cases T; simp only [tape.right₀, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) : ∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩ @[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] @[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := tape.mk' (list_blank.mk L) (list_blank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ := tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ | 0 := T.head | (n+1:ℕ) := T.right.nth n | -[1+ n] := T.left.nth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero, list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons] @[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) : (tape.mk' L R).nth n = R.nth n := by rw [← tape.right₀_nth, tape.mk'_right₀] @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm | ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm | ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _) | ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin rw add_sub_cancel, change (R.cons a).nth (n+1) = R.nth n, rw [list_blank.nth_succ, list_blank.tail_cons] end @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) : (T.move dir.right).nth i = T.nth (i+1) := by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel] @[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) : ((tape.move dir.right)^[i] T).head = T.nth i := by induction i generalizing T; [refl, simp only [*, tape.move_right_nth, int.coe_nat_succ, iterate_succ]] /-- Replace the current value of the head on the tape. -/ def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T} @[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T := by rintro ⟨⟩; refl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | ⟨a, L, R⟩ 0 := rfl | ⟨a, L, R⟩ (n+1:ℕ) := rfl | ⟨a, L, R⟩ -[1+ n] := rfl @[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) : (tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) := by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] /-- Apply a pointed map to a tape to change the alphabet. -/ def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 := by rintro ⟨⟩; refl @[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; refl @[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) : ((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) = ((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) := begin induction n with n IH generalizing L R, { simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply], rw [← tape.write_mk', list_blank.cons_head_tail] }, simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth, tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH] end theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T; cases d; simp only [tape.move, tape.map, list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map] theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) := by simp only [tape.mk', tape.map, list_blank.head_map, eq_self_iff_true, and_self, list_blank.tail_map] theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) := by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk] theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `roption.none`. -/ def eval {σ} (f : σ → option σ) : σ → roption σ := pfun.fix (λ s, roption.some $ (f s).elim (sum.inl s) sum.inr) /-- The reflexive transitive closure of a state transition function. `reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) /-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} : reaches f a b → reaches f a c → reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique ⟨λ _ _ _, option.mem_unique⟩ theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end /-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then `reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with equivalent states without taking a step. -/ def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_eliminator] def eval_induction {σ} {f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $ roption.mem_some_iff.2 $ by rw e; refl) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine eval_induction h (λ a h IH, _), cases e : f a with a', { rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ roption.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩; rw e at h; cases roption.mem_some_iff.1 h, cases IH a' h' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply roption.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply roption.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := roption.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ /-- A simpler version of `respects` when the state transition relation `tr` is a function. -/ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := roption.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (roption.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (roption.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ /-! ## The TM0 model A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions to state `q'`. The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move : dir → stmt | write : Γ → stmt instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment def machine := Λ → Γ → option (Λ × stmt) instance machine.inhabited : inhabited machine := by unfold machine; apply_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩ parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default Λ, tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : roption (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `equiv` without the laws. -/ def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S : set Λ} (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _) theorem machine.map_respects (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S} (ss : supports M S) (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto : (Γ → σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true open_locale classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end /-- The set of all statements in a turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → stmt) (l : list Γ) : roption (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M /-- The base machine state space is a pair of an `option stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption -- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here. -- But they are parameters so we cannot easily skip them for just this definition. def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) /-- Translate configurations from TM1 to TM0. -/ def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [roption.map_eq_map, roption.map_map, TM1.eval], congr' with ⟨⟩, refl end variables [fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, classical, let enc := H.set_value (default _) (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ /-- Read a vector of length `n` from the tape. -/ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v))) (stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q /-- To read a symbol from the tape, we use `read_aux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) /-- Write a list of bools on the tape. -/ def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def tr_normal : stmt₁ → stmt' | (stmt.move d q) := move d $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s) | stmt.halt := stmt.halt theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [iterate_succ', step_aux, IH, iterate_succ] end theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end parameter (enc0 : enc (default _) = vector.repeat ff n) section parameter {enc} include enc0 /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape' (L R : list_blank Γ) : tape bool := begin refine tape.mk' (L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩) (R.bind (λ x, (enc x).to_list) ⟨n, _⟩); simp only [enc0, vector.repeat, list.reverse_repeat, bool.default_bool, vector.to_list_mk] end /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀ theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R := by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀] end parameters (M : Λ → stmt₁) /-- The top level program. -/ def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q /-- The machine configuration translation. -/ def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ parameter {enc} include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (R.cons L.head)) := begin obtain ⟨a, L, rfl⟩ := L.exists_cons, simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons], suffices : ∀ {L' R' l₁ l₂} (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), tape.move dir.left^[l₁.length] (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'), { simpa only [list.length_reverse, vector.to_list_length] using this (list.reverse_reverse _).symm }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, iterate_succ_apply], convert IH e, simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons] end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (L.cons R.head) R.tail) := begin suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L, { refine (eq.symm _).trans (this n _), simp only [tr_tape'_move_left, list_blank.cons_head_tail, list_blank.head_cons, list_blank.tail_cons] }, intros, induction i with i IH, {refl}, rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH] end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) = step_aux q v (tr_tape' (list_blank.cons a L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) = step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'), { convert this [] _ _ ((enc b).2.trans (enc a).2.symm); rw list_blank.cons_bind; refl }, clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, dunfold write step_aux, convert IH _ _ e using 1, simp only [list_blank.head_cons, list_blank.tail_cons, list_blank.append, tape.move_right_mk', tape.write_mk'] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L R) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc0 L R) = step_aux (f (enc R.head)) v (tr_tape' enc0 (L.cons R.head) R.tail), { rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0], simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] }, obtain ⟨a, R, rfl⟩ := R.exists_cons, simp only [list_blank.head_cons, list_blank.tail_cons, tr_tape', list_blank.cons_bind, list_blank.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, transitivity step_aux (read_aux l₂.length (λ v, f (a ::ᵥ v))) v (tape.mk' ((L'.append l₁).cons a) (R'.append l₂)), { dsimp [read_aux, step_aux], simp, cases a; refl }, rw [← list_blank.append, IH], refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin obtain ⟨L, R, rfl⟩ := T.exists_mk', cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc0 L R)) (tr_cfg enc0 (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, iterate, step_aux_move, step_aux, list_blank.head_cons, tape.move_left_mk', list_blank.cons_head_tail, list_blank.tail_cons, tr_tape'_move_left enc0, tr_tape'_move_right enc0]; apply IH }, case TM1.stmt.write : f q IH { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, obtain ⟨a, R, rfl⟩ := R.exists_cons, rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons, step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons, list_blank.tail_cons, tape.write_mk'], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move, tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (Λ'.normal l) (writes (M l))) theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performes the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt /-- The program. -/ def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ -- unreachable | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) /-- The configuration translation. -/ def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `list_blank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push : ∀ k, (σ → Γ k) → stmt → stmt | peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto : (σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite size.) -/ structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ K} /-- The step function for the TM2 model. -/ @[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (update S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true open_locale classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in `S` jump only to other states in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, update (λ _, []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := bool × ∀ k, option (Γ k)`, where: * `bottom : bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n) (hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) : L.nth n k = S.reverse.nth n := begin rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map], cases S.reverse.nth n; refl end section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ @[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip -- the decidable_eq assumption, and this is a local definition anyway so it's not important. def Γ' := bool × ∀ k, option (Γ k) instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩ instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := prod.fintype _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' := list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩) theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L := begin simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _, generalize : list_blank.tail L = L', refine L'.induction_on _, intro l, simp, rw (_ : _ ∘ _ = id), {simp}, funext a, refl end theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) : (add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) := begin cases n; simp only [add_bottom, list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons], congr, symmetry, apply list_blank.map_modify_nth, intro, refl end theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n := by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff := by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt := by rw [add_bottom, list_blank.head_cons]; refl /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive st_act (k : K) | push : (σ → Γ k) → st_act | peek : (σ → option (Γ k) → σ) → st_act | pop : (σ → option (Γ k) → σ) → st_act instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩ section open st_act /-- The TM2 statement corresponding to a stack action. -/ @[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than -- it is worth to omit the typeclass assumption without breaking the parameters def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (peek f) := TM2.stmt.peek k f | (pop f) := TM2.stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (peek f) := f v l.head' | (pop f) := f v l.head' /-- The effect of a stack action on the stack. -/ def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (peek f) := l | (pop f) := l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret : stmt₂ → Λ' open Λ' instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q | (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q | (st_act.pop f) := branch (λ a _, a.1) ( load (λ a s, f s none) q ) ( move dir.left $ load (λ a s, f s (a.2 k)) $ write (λ a s, (a.1, update a.2 k none)) q ) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def tr_init (k) (L : list (Γ k)) : list Γ' := let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in (tt, L'.head.2) :: L'.tail theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl | (st_act.pop f) := rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl open_locale classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.load a q) := tr_stmts₁ q | Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' := update S k Sk' in ∃ (L' : list_blank (∀ k, option (Γ k))), (∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧ TM1.step_aux (tr_st_act q o) v ((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) = TM1.step_aux q v' ((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) := begin dsimp only, simp, cases o; simp only [st_write, st_var, tr_st_act, TM1.step_aux], case TM2to1.st_act.push : f { have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))), dsimp only at this, refine ⟨_, λ k', _, by rw [ tape.move_right_n_head, list.length, tape.mk'_nth_nat, this, add_bottom_modify_nth (λ a, update a k (some (f v))), nat.add_one, iterate_succ']⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [list.reverse_cons, function.update_same, list_blank.nth_mk, list.inth, list.map], { rw [list.nth_le_nth, list.nth_le_append_right]; simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos', list.length_append, lt_add_iff_pos_right, list.length] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth], cases decidable.lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } }, case TM2to1.st_act.peek : f { rw function.update_eq_self, use [L, hL], rw [tape.move_left_right], congr, cases e : S k, {refl}, rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e, list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl }, case TM2to1.st_act.pop : f { cases e : S k, { simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk', list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil], rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ }, { refine ⟨_, λ k', _, by rw [ list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)), add_bottom_modify_nth (λ a, update a k none), add_bottom_nth_snd, stk_nth_val _ (hL k), e, show (list.cons hd tl).reverse.nth tl.length = some hd, by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl, list.head', list.tail]⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [ function.update_same, list_blank.nth_mk, list.tail, list.inth], { rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons], cases decidable.lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } } }, end parameters (M : Λ → stmt₂) include M /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret q) := branch (λ a s, a.1) (tr_normal q) (move dir.left $ goto (λ _ _, ret q)) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) : (∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) : reaches₀ (TM1.step tr) ⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩ ⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, apply (IH (le_of_lt H)).tail, rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr, tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd, option.mem_def], rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse end theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) : reaches₀ (TM1.step tr) ⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ ⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, refine reaches₀.head _ IH, rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl, end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))}, (∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := begin simp only [tr_normal_run, step_run], have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _), obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o, have hret := tr_respects_aux₃ M _, have := hgo.tail' rfl, rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)), option.is_none, cond, hrun, TM1.step_aux] at this, obtain ⟨c, gc, rc⟩ := IH hT', refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩, rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst], exact rc, end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH _ hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := begin rw (_ : TM1.init _ = _), { refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩, refine list_blank.ext (λ i, _), rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘), list.nth_map, proj, pointed_map.mk_val], by_cases k' = k, { subst k', simp only [function.update_same], rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] }, { simp only [function.update_noteq h], rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth], cases L.reverse.nth i; refl } }, { rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl}, simp only [list.map_map, list.tail_cons, list.map], refl } end theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))), add_bottom L' = L₁ ∧ (∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧ S k = L₂ := begin obtain ⟨c₁, h₁, rfl⟩ := (roption.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (roption.mem_map_iff _).1 H₂, obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂, cases roption.mem_unique h₁ h₃, exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩ end /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l))) theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inl rfl), have hret := sub _ (or.inl $ or.inr rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
b8811789d02ee1cbaa81cced91ab3859dfb97a0c
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Meta.lean
2274788ece9b0fae631b71c465be5d3b351acdb9
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
745
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.Meta.Basic import Lean.Meta.LevelDefEq import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.ExprDefEq import Lean.Meta.DiscrTree import Lean.Meta.Reduce import Lean.Meta.Instances import Lean.Meta.AbstractMVars import Lean.Meta.SynthInstance import Lean.Meta.AppBuilder import Lean.Meta.Tactic import Lean.Meta.KAbstract import Lean.Meta.RecursorInfo import Lean.Meta.GeneralizeTelescope import Lean.Meta.Match import Lean.Meta.ReduceEval import Lean.Meta.Closure import Lean.Meta.AbstractNestedProofs import Lean.Meta.ForEachExpr
217a13465fb19a054e365fa4f95a7669e7382b22
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/repr.lean
646e5a0911df7476beae1068e35cd1a0c132595f
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
3,836
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.string.basic init.data.bool.basic init.data.subtype.basic import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div open sum subtype nat universes u v class has_repr (α : Type u) := (repr : α → string) def repr {α : Type u} [has_repr α] : α → string := has_repr.repr instance : has_repr bool := ⟨λ b, cond b "tt" "ff"⟩ instance {p : Prop} : has_repr (decidable p) := -- Remark: type class inference will not consider local instance `b` in the new elaborator ⟨λ b : decidable p, @ite p b _ "tt" "ff"⟩ protected def list.repr_aux {α : Type u} [has_repr α] : bool → list α → string | b [] := "" | tt (x::xs) := repr x ++ list.repr_aux ff xs | ff (x::xs) := ", " ++ repr x ++ list.repr_aux ff xs protected def list.repr {α : Type u} [has_repr α] : list α → string | [] := "[]" | (x::xs) := "[" ++ list.repr_aux tt (x::xs) ++ "]" instance {α : Type u} [has_repr α] : has_repr (list α) := ⟨list.repr⟩ instance : has_repr unit := ⟨λ u, "star"⟩ instance {α : Type u} [has_repr α] : has_repr (option α) := ⟨λ o, match o with | none := "none" | (some a) := "(some " ++ repr a ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_repr α] [has_repr β] : has_repr (α ⊕ β) := ⟨λ s, match s with | (inl a) := "(inl " ++ repr a ++ ")" | (inr b) := "(inr " ++ repr b ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_repr α] [has_repr β] : has_repr (α × β) := ⟨λ ⟨a, b⟩, "(" ++ repr a ++ ", " ++ repr b ++ ")"⟩ instance {α : Type u} {β : α → Type v} [has_repr α] [s : ∀ x, has_repr (β x)] : has_repr (sigma β) := ⟨λ ⟨a, b⟩, "⟨" ++ repr a ++ ", " ++ repr b ++ "⟩"⟩ instance {α : Type u} {p : α → Prop} [has_repr α] : has_repr (subtype p) := ⟨λ s, repr (val s)⟩ namespace nat def digit_char (n : ℕ) : char := if n = 0 then '0' else if n = 1 then '1' else if n = 2 then '2' else if n = 3 then '3' else if n = 4 then '4' else if n = 5 then '5' else if n = 6 then '6' else if n = 7 then '7' else if n = 8 then '8' else if n = 9 then '9' else if n = 0xa then 'a' else if n = 0xb then 'b' else if n = 0xc then 'c' else if n = 0xd then 'd' else if n = 0xe then 'e' else if n = 0xf then 'f' else '*' def digit_succ (base : ℕ) : list ℕ → list ℕ | [] := [1] | (d::ds) := if d+1 = base then 0 :: digit_succ ds else (d+1) :: ds def to_digits (base : ℕ) : ℕ → list ℕ | 0 := [0] | (n+1) := digit_succ base (to_digits n) protected def repr (n : ℕ) : string := ((to_digits 10 n).map digit_char).reverse.as_string end nat instance : has_repr nat := ⟨nat.repr⟩ def hex_digit_repr (n : nat) : string := string.singleton $ nat.digit_char n def char_to_hex (c : char) : string := let n := char.to_nat c, d2 := n / 16, d1 := n % 16 in hex_digit_repr d2 ++ hex_digit_repr d1 def char.quote_core (c : char) : string := if c = '\n' then "\\n" else if c = '\t' then "\\t" else if c = '\\' then "\\\\" else if c = '\"' then "\\\"" else if char.to_nat c <= 31 then "\\x" ++ char_to_hex c else string.singleton c instance : has_repr char := ⟨λ c, "'" ++ char.quote_core c ++ "'"⟩ def string.quote_aux : list char → string | [] := "" | (x::xs) := char.quote_core x ++ string.quote_aux xs def string.quote (s : string) : string := if s.is_empty = tt then "\"\"" else "\"" ++ string.quote_aux s.to_list ++ "\"" instance : has_repr string := ⟨string.quote⟩ instance (n : nat) : has_repr (fin n) := ⟨λ f, repr (fin.val f)⟩ instance : has_repr unsigned := ⟨λ n, repr (fin.val n)⟩ def char.repr (c : char) : string := repr c
1bc58cca820175c4fb7512559d94fb4231390197
d1e4f66050635dc90e91499961af6648c3059f3e
/extra/demorgans law.lean
87faa2decf91ab6db82ba9c36cfa7ae4de3a3d7e
[]
no_license
xivh/leanpractice
26612ef7dd3cc030c348ac97ab938b0767714bd0
a75115fc22da1e69dbe99d2bd9e90f153d2527a5
refs/heads/master
1,586,485,026,265
1,544,137,859,000
1,544,137,859,000
160,740,341
0
0
null
null
null
null
UTF-8
Lean
false
false
3,413
lean
open classical --one way DeMorgan's Law lemma DeMorganOne : ∀ P Q : Prop, ¬ (P ∧ Q) → ¬ P ∨ ¬ Q := begin assume P Q : Prop, assume npq : ¬ (P ∧ Q), change (P ∧ Q) → false at npq, have pnp : P ∨ ¬ P := em P, have qnq : Q ∨ ¬ Q := em Q, cases pnp with p np, cases qnq with q nq, have pq : P ∧ Q := and.intro p q, have f : false := npq pq, apply false.elim f, right, assumption, left, assumption, end --check to make sure it works variables (A B : Prop) #check DeMorganOne ¬ A ¬ B --defining ∨ when you only have ∧ example : ∀ P Q : Prop, P ∨ Q ↔ ¬(¬P ∧ ¬Q) := begin assume P Q : Prop, split, assume pq : P ∨ Q, assume npq : ¬ P ∧ ¬ Q, show false, from begin cases pq with p q, have np : ¬ P := and.elim_left npq, contradiction, have nq : ¬ Q := and.elim_right npq, contradiction, end, assume nnpnq, have DMO := DeMorganOne (¬ P) (¬ Q), have nnpnnq : ¬ ¬ P ∨ ¬ ¬ Q := DMO nnpnq, have pnp : P ∨ ¬ P := em P, have qnq : Q ∨ ¬ Q := em Q, cases nnpnnq with nnp nnq, change (P → false) → false at nnp, cases pnp with p np, left, assumption, change (P → false) at np, have f : false := nnp np, trivial, change (Q → false) → false at nnq, cases qnq with q nq, right, assumption, change (Q → false) at nq, have f : false := nnq nq, trivial, end --going the other way is easy (I will use more shortcuts) lemma DeMorganTwo : ∀ P Q : Prop, ¬ (P ∨ Q) → ¬ P ∧ ¬ Q := begin intros, change (P ∨ Q) → false at a, have pnp := em P, have qnq := em Q, cases pnp with p np, have pq := or.inl p, have f := a pq, trivial, cases qnq with q nq, have pq := or.inr q, have f := a pq, trivial, apply and.intro np nq, end -- defining ∧ from ∨ example : ∀ P Q : Prop, P ∧ Q ↔ ¬ (¬ P ∨ ¬ Q) := begin intros, split, intros, assume b, show false, from begin have p := and.elim_left a, have q := and.elim_right a, cases b with np nq, trivial, trivial, end, intros, have DMT := DeMorganTwo (¬ P) (¬ Q), have nnpnnq := DMT a, have pnp := em P, have qnq := em Q, cases nnpnnq with nnp nnq, change (¬ P) → false at nnp, change (¬ Q) → false at nnq, cases pnp with p np, cases qnq with q nq, apply and.intro p q, have f := nnq nq, trivial, have f := nnp np, trivial end --proving them again without relying on a proof of DML example : ∀ P Q : Prop, P ∨ Q ↔ ¬(¬P ∧ ¬Q) := begin intros, split, intros, assume npq, show false, from begin cases a, have np := and.elim_left npq, trivial, have nq := and.elim_right npq, trivial, end, assume nnpnq, have pnp : P ∨ ¬ P := em P, have qnq : Q ∨ ¬ Q := em Q, change (¬ P ∧ ¬ Q) → false at nnpnq, cases pnp, left, assumption, cases qnq, right, assumption, have f := nnpnq (and.intro pnp qnq), trivial, end example : ∀ P Q : Prop, P ∧ Q ↔ ¬ (¬ P ∨ ¬ Q) := begin intros, split, intros, assume b, show false, from begin have p := and.elim_left a, have q := and.elim_right a, cases b with np nq, trivial, trivial, end, intros, have pnp := em P, have qnq := em Q, change (¬ P ∨ ¬ Q) → false at a, cases pnp with p np, cases qnq with q nq, apply and.intro p q, have f := a (or.inr nq), trivial, have f := a (or.inl np), trivial, end
18680b38d82e04e8191bb951bdd7dd822a08b766
7282d49021d38dacd06c4ce45a48d09627687fe0
/src/builtin/heq.lean
9912bc3ee91fac2503d06210d2297886207ed648
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
2,314
lean
-- Heterogenous equality variable heq {A B : TypeU} : A → B → Bool infixl 50 == : heq axiom heq_eq {A : TypeU} (a b : A) : a == b ↔ a = b theorem to_eq {A : TypeU} {a b : A} (H : a == b) : a = b := (heq_eq a b) ◂ H theorem to_heq {A : TypeU} {a b : A} (H : a = b) : a == b := (symm (heq_eq a b)) ◂ H theorem hrefl {A : TypeU} (a : A) : a == a := to_heq (refl a) axiom hsymm {A B : TypeU} {a : A} {b : B} : a == b → b == a axiom htrans {A B C : TypeU} {a : A} {b : B} {c : C} : a == b → b == c → a == c axiom hcongr {A A' : TypeU} {B : A → TypeU} {B' : A' → TypeU} {f : ∀ x, B x} {f' : ∀ x, B' x} {a : A} {a' : A'} : f == f' → a == a' → f a == f' a' universe M ≥ 1 universe U ≥ M + 1 definition TypeM := (Type M) -- In the following definitions the type of A and A' cannot be TypeU -- because A = A' would be @eq (Type U+1) A A', and -- the type of eq is (∀T : (Type U), T → T → bool). -- So, we define M a universe smaller than U. axiom hfunext {A A' : TypeM} {B : A → TypeU} {B' : A' → TypeU} {f : ∀ x, B x} {f' : ∀ x, B' x} : A = A' → (∀ x x', x == x' → f x == f' x') → f == f' theorem hsfunext {A : TypeM} {B B' : A → TypeU} {f : ∀ x, B x} {f' : ∀ x, B' x} : (∀ x, f x == f' x) → f == f' := λ Hb, hfunext (refl A) (λ (x x' : A) (Hx : x == x'), let s1 : f x == f' x := Hb x, s2 : f' x == f' x' := hcongr (hrefl f') Hx in htrans s1 s2) axiom hallext {A A' : TypeM} {B : A → Bool} {B' : A' → Bool} : A = A' → (∀ x x', x == x' → B x = B' x') → (∀ x, B x) = (∀ x, B' x) -- The following axiom is not very useful, since the resultant -- equality is actually (@eq TypeM (∀ x, B x) (∀ x, B' x)). -- This is the case even if A, A', B and B' live in smaller universes (e.g., Type) -- To support this kind of axiom, it seems we have two options: -- 1) Universe level parameters like Agda -- 2) Axiom schema/template, where we create instances of hpiext for different universes. -- BTW, this is essentially what Coq does since the levels are implicit in Coq. -- axiom hpiext {A A' : TypeM} {B : A → TypeM} {B' : A' → TypeM} : -- A = A' → (∀ x x', x == x' → B x = B' x') → (∀ x, B x) = (∀ x, B' x)
5cde05dc745843e90c5c3f161cc8b47afd2d6711
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/data/list/default.lean
07e3d69e1562fa40f9cc79312ae4bf32bd8b262e
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
247
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.data.list.basic init.data.list.instances init.data.list.lemmas
1f68b9d7f21477f9bd6edbe77d6e7542a2ad61ba
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Std/Data.lean
0397c49f45fc3c09a2dbe094aa43e0ec815620d3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
478
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.BinomialHeap import Std.Data.DList import Std.Data.Stack import Std.Data.Queue import Std.Data.HashMap import Std.Data.HashSet import Std.Data.PersistentArray import Std.Data.PersistentHashMap import Std.Data.PersistentHashSet import Std.Data.AssocList import Std.Data.RBTree import Std.Data.RBMap
4c9977abd0ddd4da6170f49dfe558973fd6bc84b
b2e508d02500f1512e1618150413e6be69d9db10
/src/ring_theory/integral_closure.lean
d4185bd063a42660606e160fa6d60e02bc8dae11
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
13,497
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Integral closure of a subring. -/ import ring_theory.adjoin universes u v open polynomial submodule variables (R : Type u) {A : Type v} variables [comm_ring R] [comm_ring A] variables [decidable_eq R] [decidable_eq A] variables [algebra R A] 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 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, mem_coe], 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 (λ _, ⟨finset.singleton 1, le_antisymm (span_le.2 $ set.singleton_subset_iff.2 $ is_submonoid.one_mem _) (show ring.closure _ ⊆ _, by rw set.union_empty; exact set.subset.trans (ring.closure_subset (set.subset.refl _)) (λ y ⟨x, hx⟩, hx ▸ mul_one (algebra_map A x) ▸ algebra.smul_def x (1:A) ▸ (mem_coe _).2 (submodule.smul_mem _ x $ subset_span $ or.inl rfl)))⟩) (λ 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) (set.ne_empty_of_mem ⟨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 (M : subalgebra R A) (H : is_noetherian R (M : submodule R A)) (x : A) (hx : x ∈ M) : is_integral R x := begin letI : algebra R M := M.algebra, letI : comm_ring M := M.comm_ring R A, suffices : is_integral R (⟨x, hx⟩ : M), { 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 ← finset.sum_hom subtype.val, { refine finset.sum_congr rfl (λ n hn, _), change _ = _ * _, rw is_semiring_hom.map_pow subtype.val, refl, split; intros; refl }, refine { map_add := _, map_zero := _ }; intros; refl }, refine is_integral_of_noetherian' H ⟨x, hx⟩ end set_option class.instance_max_depth 100 theorem is_integral_of_mem_of_fg (M : subalgebra R A) (HM : (M : submodule R A).fg) (x : A) (hx : x ∈ M) : is_integral R x := begin cases HM with m hm, have hxm : x ∈ (M : submodule R A) := hx, rw [← hm, mem_span_iff_lc] at hxm, rcases hxm with ⟨lx, hlx1, hlx2⟩, have : ∀ (jk : (↑(m.product m) : set (A × A))), jk.1.1 * jk.1.2 ∈ (span R ↑m : submodule R A), { intros jk, let j : ↥(↑m : set A) := ⟨jk.1.1, (finset.mem_product.1 jk.2).1⟩, let k : ↥(↑m : set A) := ⟨jk.1.2, (finset.mem_product.1 jk.2).2⟩, have hj : j.1 ∈ (span R ↑m : submodule R A) := subset_span j.2, have hk : k.1 ∈ (span R ↑m : submodule R A) := subset_span k.2, revert hj hk, rw hm, exact @is_submonoid.mul_mem A _ M _ j.1 k.1 }, simp only [mem_span_iff_lc] at this, choose lm hlm1 hlm2, let S₀' : finset R := lx.frange ∪ finset.bind finset.univ (finsupp.frange ∘ lm), 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 : module S₀ (algebra.comap S₀ R A) := algebra.module, have : (span S₀ (insert 1 (↑m:set A) : set (algebra.comap S₀ R A)) : submodule S₀ (algebra.comap S₀ R A)) = (algebra.adjoin S₀ ((↑m : 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, simp only [mem_coe, mem_span_iff_lc] at ih1 ih2, have ih1' := ih1, have ih2' := ih2, rcases ih1' with ⟨l1, hl1, rfl⟩, rcases ih2' with ⟨l2, hl2, rfl⟩, simp only [lc.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 := _inst_6, 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 m m) : set (A × A)) := ⟨(r1, r2), finset.mem_product.2 ⟨hr1, hr2⟩⟩, specialize hlm2 jk, change _ = r1 * r2 at hlm2, rw [← hlm2, lc.total_apply], rw [finsupp.sum], refine sum_mem _ _, intros z hz, have : lm jk z ∈ S₀, { apply ring.subset_closure, apply finset.mem_union_right, apply finset.mem_bind.2, exact ⟨jk, finset.mem_univ _, finset.mem_image_of_mem _ hz⟩ }, change @has_scalar.smul S₀ (algebra.comap S₀ R A) _inst_6.to_has_scalar ⟨lm jk z, this⟩ z ∈ _, exact smul_mem _ _ (subset_span (set.mem_insert_of_mem _ (hlm1 _ hz))) }, haveI : is_noetherian_ring ↥S₀ :=(by convert is_noetherian_ring_closure _ (finset.finite_to_set _); apply_instance), apply is_integral_of_noetherian (algebra.adjoin S₀ ((↑m : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 m, by rw finset.coe_insert; convert this⟩), show x ∈ ((algebra.adjoin S₀ ((↑m : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)) : submodule S₀ (algebra.comap S₀ R A)), rw [← hlx2, lc.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 _ (finset.mem_image_of_mem _ hr)), change @has_scalar.smul S₀ (algebra.comap S₀ R A) _inst_6.to_has_scalar ⟨lx r, this⟩ r ∈ _, 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.union_singleton, insert] 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_zero R A ▸ is_integral_algebra_map theorem is_integral_one : is_integral R (1:A) := algebra.map_one R A ▸ 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.inr (or.inl rfl))) (ring.subset_closure (or.inl 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.inr (or.inl rfl))) (ring.subset_closure (or.inl 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 (or.inl 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 lattice.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 (or.inl 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
9b0a5866a4203d63c9d83a720f6ab94eae8287b8
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p1_categories/c3_wtypes/s1_base_change.lean
125e5f990ba91a2a70ab6e1ad08cd7a0a502ec28
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
6,096
lean
/- ----------------------------------------------------------------------- Base change, dependent sum, and dependent product. ----------------------------------------------------------------------- -/ import ..c2_limits namespace qp open stdaux universe variables ℓobj ℓhom /- ----------------------------------------------------------------------- Base change. ----------------------------------------------------------------------- -/ /-! #brief Action of base change on objects. -/ definition BaseChangeFun.obj {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) [f_HasPullbacksAlong : HasPullbacksAlong C f] (Y : OverObj C y) : OverObj C x := { obj := pullback C (f ↗→ Y^.hom ↗→↗) , hom := pullback.π C (f ↗→ Y^.hom ↗→↗) (@fin_of 1 0) } /-! #brief Action of base change on homs. -/ definition BaseChangeFun.hom {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) [f_HasPullbacksAlong : HasPullbacksAlong C f] (Y₁ Y₂ : OverObj C y) (h : OverHom C y Y₁ Y₂) : OverHom C x (BaseChangeFun.obj f Y₁) (BaseChangeFun.obj f Y₂) := { hom := pullback.hom C (x, x) [(Y₁^.obj, Y₂^.obj)] (f ↗→ Y₁^.hom ↗→↗) (f ↗→ Y₂^.hom ↗→↗) (C^.id x ↗ h^.hom ↗↗) , triangle := sorry } /-! #brief A base change functor. -/ definition BaseChangeFun {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) [f_HasPullbacksAlong : HasPullbacksAlong C f] : Fun (OverCat C y) (OverCat C x) := { obj := BaseChangeFun.obj f , hom := BaseChangeFun.hom f , hom_id := λ Y, OverHom.eq sorry , hom_circ := λ X Y Z G F, OverHom.eq sorry } /- ----------------------------------------------------------------------- Dependent sum. ----------------------------------------------------------------------- -/ /-! #brief The dependent sum functor. -/ definition DepSumFun {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) : Fun (OverCat C x) (OverCat C y) := { obj := λ X , { obj := X^.obj , hom := C^.circ f X^.hom } , hom := λ X Y F , { hom := F^.hom , triangle := begin rw -C^.circ_assoc, exact Cat.circ.congr_right F^.triangle end } , hom_id := λ X, rfl , hom_circ := λ X Y Z G F, rfl } /-! #brief A hom into a dependent sum object. -/ definition DepSumFun.into {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) (X : OverObj C y) (Y : OverObj C x) (Xx : C^.hom X^.obj x) (ωXx : X^.hom = f ∘∘ Xx) (h : (OverCat C x)^.hom { obj := X^.obj , hom := Xx } Y) : (OverCat C y)^.hom X ((DepSumFun f)^.obj Y) := { hom := h^.hom , triangle := by calc X^.hom = f ∘∘ Xx : ωXx ... = f ∘∘ (Y^.hom ∘∘ h^.hom) : Cat.circ.congr_right h^.triangle ... = f ∘∘ Y^.hom ∘∘ h^.hom : C^.circ_assoc } /-! #brief Dependent sum is adjoint to base change. -/ definition DepSum_BaseChange.Adj {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) [f_HasPullbacksAlong : HasPullbacksAlong C f] : Adj (DepSumFun f) (BaseChangeFun f) := { counit := { com := λ Y, { hom := pullback.π C (f ↗→ Y^.hom ↗→↗) (@fin_of 0 1) , triangle := sorry } , natural := sorry } , unit := { com := λ X, { hom := pullback.univ C (f ↗→ (f ∘∘ X^.hom) ↗→↗) (PullbackCone.mk (f ↗→ (f ∘∘ X^.hom) ↗→↗) X^.dom (f ∘∘ X^.hom) (X^.hom ↗← ⟨⟨ X^.obj ⟩⟩ ↗←↗) begin apply dlist.eq, { trivial }, apply dlist.eq, { rw [-C^.circ_assoc, C^.circ_id_right] }, trivial end) , triangle := sorry } , natural := sorry } , id_left := λ c , OverHom.eq begin dsimp [OverCat, OverHom.id, OverHom.comp, DepSumFun], exact sorry end , id_right := λ c , OverHom.eq begin exact sorry end } /- ----------------------------------------------------------------------- Dependent product. ----------------------------------------------------------------------- -/ /-! #brief A category with a dependent product. -/ class HasDepProd (C : Cat.{ℓobj ℓhom}) {x y : C^.obj} (f : C^.hom x y) [f_HasPullbacksAlong : HasPullbacksAlong C f] := (depprod : Fun (OverCat C x) (OverCat C y)) (adj : Adj (BaseChangeFun f) depprod) /-! #brief A category with all dependent products. -/ class HasAllDepProd (C : Cat.{ℓobj ℓhom}) [C_HasAllPullbacks : HasAllPullbacks C] := (has_depprod : ∀ {x y : C^.obj} (f : C^.hom x y) , HasDepProd C f) attribute [instance] HasAllDepProd.has_depprod /-! #brief A dependent product functor. -/ definition DepProdFun {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) [f_HasPullbacksAlong : HasPullbacksAlong C f] [C_HasDepProd : HasDepProd C f] : Fun (OverCat C x) (OverCat C y) := HasDepProd.depprod f_HasPullbacksAlong /-! #brief Base change is adjoint to dependent product. -/ definition BaseChange_DepProd.Adj {C : Cat.{ℓobj ℓhom}} {x y : C^.obj} (f : C^.hom x y) [f_HasPullbacksAlong : HasPullbacksAlong C f] [C_HasDepProd : HasDepProd C f] : Adj (BaseChangeFun f) (DepProdFun f) := HasDepProd.adj f_HasPullbacksAlong end qp
efcafd6814c259eeff8234e73e5169db17bd93d7
618003631150032a5676f229d13a079ac875ff77
/src/data/pnat/factors.lean
807d4937e691d1713fa0ea3533ba80472e5ef1cd
[ "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
13,915
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland -/ import data.pnat.basic import data.multiset import data.int.gcd import algebra.group /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : inhabited prime_multiset := by unfold prime_multiset; apply_instance instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_add_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≤ v → u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p :: 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset → multiset ℕ := λ v, v.map (λ p, (p : ℕ)) instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_inj : function.injective (coe : prime_multiset → multiset ℕ) := multiset.injective_map nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ) = (p : ℕ) :: 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } def to_pnat_multiset : prime_multiset → multiset ℕ+ := λ v, v.map (λ p, (p : ℕ+)) instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_inj : function.injective (coe : prime_multiset → multiset ℕ+) := multiset.injective_map nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ+) = (p : ℕ+) :: 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) := ⟨λ v, v.map (λ n, (n : ℕ))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) := by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod := begin let h : (v.prod : ℕ) = ((v.map coe).map coe).prod := (v.to_pnat_multiset.prod_hom coe).symm, rw [multiset.map_map] at h, have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) := by { change multiset.prod ((p : ℕ+) :: 0) = (p : ℕ+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } def of_nat_multiset (v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h) : multiset ℕ) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) := by rw[coe_prod, to_of_nat_multiset] def of_pnat_multiset (v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h theorem to_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h) : multiset ℕ+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h).prod : ℕ+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset := of_nat_multiset (l : multiset ℕ) h theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod := by { have := prod_of_nat_multiset (l : multiset ℕ) h, rw [multiset.coe_prod] at this, exact this } def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset := of_pnat_multiset (l : multiset ℕ+) h theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset ℕ+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset → multiset ℕ+)], rw [multiset.prod_add] } theorem prod_smul (d : ℕ) (u : prime_multiset) : (d •ℕ u).prod = u.prod ^ d := by { induction d with d ih, refl, rw [succ_nsmul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : ℕ+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : ℕ+) : ((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_inj, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with l, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes → ℕ), have : ∀ (p : ℕ), p ∈ l' → p.prime := λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : ℕ+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := rfl theorem factor_multiset_mul (n m : ℕ+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : ℕ+) (m : ℕ) : factor_multiset (n ^ m) = m •ℕ (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : ℕ+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : ℕ+} : factor_multiset m ≤ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd_intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_add_right (le_refl _) } end theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}: factor_multiset m ≤ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : ℕ+) : factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) := begin apply le_antisymm, { apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact inf_le_left, exact inf_le_right} end theorem factor_multiset_lcm (m n : ℕ+) : factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact le_sup_left, exact le_sup_right}, { apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_smul, prime_multiset.card_of_prime, mul_one] }, { have : ∀ (m : ℕ), m •ℕ (p::0) = multiset.repeat p m := λ m, by {induction m with m ih, { refl }, rw [succ_nsmul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u ⊓ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊓ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u ⊔ v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊔ v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
1d95af3ff23b61607ae3865dee02a80a3c0815a4
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/one2.lean
e7af7ca78892f62e854d6b8069fac9e4e5b65534
[ "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
401
lean
import data.num inductive one.{l} : Type.{l} := unit : one inductive pone : Type.{0} := unit : pone inductive two.{l} : Type.{max 1 l} := o : two, u : two inductive wrap.{l} : Type.{max 1 l} := mk : true → wrap inductive wrap2.{l} (A : Type.{l}) : Type.{max 1 l} := mk : A → wrap2 A set_option pp.universes true check @one.rec check @pone.rec check @two.rec check @wrap.rec check @wrap2.rec
447ecb3434577a7d21df56a203dcd8607f078e4b
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/WF.lean
1d1e1200af682bbf188e8625043fed9f88b1e731
[ "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
13,439
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic universes u v set_option codegen false inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop | intro (x : α) (h : ∀ y, r y x → Acc y) : Acc x @[elabAsEliminator, inline, reducible] def Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} (m : ∀ (x : α) (h : ∀ (y : α), r y x → Acc r y), (∀ (y : α) (a : r y x), C y) → C x) {a : α} (n : Acc r a) : C a := @Acc.rec α r (fun α _ => C α) m a n @[elabAsEliminator, inline, reducible] def Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} {a : α} (n : Acc r a) (m : ∀ (x : α) (h : ∀ (y : α), r y x → Acc r y), (∀ (y : α) (a : r y x), C y) → C x) : C a := @Acc.rec α r (fun α _ => C α) m a n namespace Acc variables {α : Sort u} {r : α → α → Prop} def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y := Acc.recOn h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂ end Acc inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop | intro (h : ∀ a, Acc r a) : WellFounded class HasWellFounded (α : Sort u) : Type u := (r : α → α → Prop) (wf : WellFounded r) namespace WellFounded def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) : ∀ a, Acc r a := fun a => WellFounded.recOn wf (fun p => p) a section variables {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r) theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := Acc.recOn (apply hwf a) (fun x₁ ac₁ ih => h x₁ ih) theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := recursion hwf a h variable {C : α → Sort v} variable (F : ∀ x, (∀ y, r y x → C y) → C x) def fixF (x : α) (a : Acc r x) : C x := Acc.recOn a (fun x₁ ac₁ ih => F x₁ ih) theorem fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := Acc.rec (fun x r ih => rfl) acx end variables {α : Sort u} {C : α → Sort v} {r : α → α → Prop} -- Well-founded fixpoint def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := fixF F x (apply hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fixEq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (fun y h => fix hwf F y) := fixFEq F x (apply hwf x) end WellFounded open WellFounded -- Empty relation is well-founded def emptyWf {α : Sort u} : WellFounded (@emptyRelation α) := WellFounded.intro (fun (a : α) => Acc.intro a (fun (b : α) (lt : False) => False.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace Subrelation variables {α : Sort u} {r q : α → α → Prop} def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := Acc.recOn ac $ fun x ax ih => Acc.intro x $ fun (y : α) (lt : q y x) => ih y (h₁ lt) def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q := ⟨fun a => accessible @h₁ (apply h₂ a)⟩ end Subrelation -- The inverse image of a well-founded relation is well-founded namespace InvImage variables {α : Sort u} {β : Sort v} {r : β → β → Prop} private def accAux (f : α → β) {b : β} (ac : Acc r b) : ∀ (x : α), f x = b → Acc (InvImage r f) x := Acc.ndrecOn ac $ fun x acx ih z e => Acc.intro z $ fun y lt => Eq.ndrecOn e (fun acx ih => ih (f y) lt y rfl) acx ih def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a := accAux f ac a rfl def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) := ⟨fun a => accessible f (apply h (f a))⟩ end InvImage -- The transitive closure of a well-founded relation is well-founded namespace TC variables {α : Sort u} {r : α → α → Prop} def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := Acc.ndrecOn ac $ fun x acx ih => Acc.intro x $ fun y rel => TC.ndrecOn rel (fun a b rab acx ih => ih a rab) (fun a b c rab rbc ih₁ ih₂ acx ih => Acc.inv (ih₂ acx ih) rab) acx ih def wf (h : WellFounded r) : WellFounded (TC r) := ⟨fun a => accessible (apply h a)⟩ end TC -- less-than is well-founded def Nat.ltWf : WellFounded Nat.lt := ⟨Nat.rec (Acc.intro 0 (fun n h => absurd h (Nat.notLtZero n))) (fun n ih => Acc.intro (Nat.succ n) $ fun m h => Or.elim (Nat.eqOrLtOfLe (Nat.leOfSuccLeSucc h)) (fun e => Eq.substr e ih) (Acc.inv ih))⟩ def measure {α : Sort u} : (α → Nat) → α → α → Prop := InvImage (fun a b => a < b) def measureWf {α : Sort u} (f : α → Nat) : WellFounded (measure f) := InvImage.wf f Nat.ltWf def sizeofMeasure (α : Sort u) [HasSizeof α] : α → α → Prop := measure sizeof def sizeofMeasureWf (α : Sort u) [HasSizeof α] : WellFounded (sizeofMeasure α) := measureWf sizeof instance hasWellFoundedOfHasSizeof (α : Sort u) [HasSizeof α] : HasWellFounded α := {r := sizeofMeasure α, wf := sizeofMeasureWf α} namespace Prod open WellFounded section variables {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive Lex : α × β → α × β → Prop | left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂) | right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂) -- relational product based on ra and rb inductive Rprod : α × β → α × β → Prop | intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : Rprod (a₁, b₁) (a₂, b₂) end section variables {α : Type u} {β : Type v} variables {ra : α → α → Prop} {rb : β → β → Prop} def lexAccessible {a} (aca : Acc ra a) (acb : ∀ b, Acc rb b): ∀ b, Acc (Lex ra rb) (a, b) := Acc.ndrecOn aca $ fun xa aca iha b => Acc.ndrecOn (acb b) $ fun xb acb ihb => Acc.intro (xa, xb) $ fun p lt => have aux : xa = xa → xb = xb → Acc (Lex ra rb) p from @Prod.Lex.recOn α β ra rb (fun p₁ p₂ _ => fst p₂ = xa → snd p₂ = xb → Acc (Lex ra rb) p₁) p (xa, xb) lt (fun (a₁ b₁ a₂ b₂ h) (Eq₂ : a₂ = xa) (Eq₃ : b₂ = xb) => iha a₁ (Eq.recOn Eq₂ h) b₁) (fun (a b₁ b₂ h) (Eq₂ : a = xa) (Eq₃ : b₂ = xb) => Eq.recOn Eq₂.symm (ihb b₁ (Eq.recOn Eq₃ h))); aux rfl rfl -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Lex ra rb) := ⟨fun p => casesOn p $ fun a b => lexAccessible (apply ha a) (WellFounded.apply hb) b⟩ -- relational product is a Subrelation of the Lex def rprodSubLex : ∀ a b, Rprod ra rb a b → Lex ra rb a b := @Prod.Rprod.rec _ _ ra rb (fun a b _ => Lex ra rb a b) (fun a₁ b₁ a₂ b₂ h₁ h₂ => Lex.left rb b₁ b₂ h₁) -- The relational product of well founded relations is well-founded def rprodWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Rprod ra rb) := Subrelation.wf (rprodSubLex) (lexWf ha hb) end instance HasWellFounded {α : Type u} {β : Type v} [s₁ : HasWellFounded α] [s₂ : HasWellFounded β] : HasWellFounded (α × β) := {r := Lex s₁.r s₂.r, wf := lexWf s₁.wf s₂.wf} end Prod namespace PSigma section variables {α : Sort u} {β : α → Sort v} variable (r : α → α → Prop) variable (s : ∀ a, β a → β a → Prop) -- Lexicographical order based on r and s inductive Lex : PSigma β → PSigma β → Prop | left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ | right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩ end section variables {α : Sort u} {β : α → Sort v} variables {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop} def lexAccessible {a} (aca : Acc r a) (acb : ∀ a, WellFounded (s a)) : ∀ (b : β a), Acc (Lex r s) ⟨a, b⟩ := Acc.ndrecOn aca $ fun (xa aca) (iha : ∀ y, r y xa → ∀ (b : β y), Acc (Lex r s) ⟨y, b⟩) (b : β xa) => Acc.ndrecOn (WellFounded.apply (acb xa) b) $ fun xb acb (ihb : ∀ (y : β xa), s xa y xb → Acc (Lex r s) ⟨xa, y⟩) => Acc.intro ⟨xa, xb⟩ $ fun (p) (lt : Lex r s p ⟨xa, xb⟩) => have aux : xa = xa → xb ≅ xb → Acc (Lex r s) p from @PSigma.Lex.recOn α β r s (fun p₁ p₂ _ => p₂.1 = xa → p₂.2 ≅ xb → Acc (Lex r s) p₁) p ⟨xa, xb⟩ lt (fun (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) (h : r a₁ a₂) (Eq₂ : a₂ = xa) (Eq₃ : b₂ ≅ xb) => have aux : (∀ (y : α), r y xa → ∀ (b : β y), Acc (Lex r s) ⟨y, b⟩) → r a₁ a₂ → ∀ (b₁ : β a₁), Acc (Lex r s) ⟨a₁, b₁⟩ from Eq.subst Eq₂ (fun iha h b₁ => iha a₁ h b₁); aux iha h b₁) (fun (a : α) (b₁ b₂ : β a) (h : s a b₁ b₂) (Eq₂ : a = xa) (Eq₃ : b₂ ≅ xb) => have aux : ∀ (xb : β xa), (∀ (y : β xa), s xa y xb → Acc (s xa) y) → (∀ (y : β xa), s xa y xb → Acc (Lex r s) ⟨xa, y⟩) → Lex r s p ⟨xa, xb⟩ → ∀ (b₁ : β a), s a b₁ b₂ → b₂ ≅ xb → Acc (Lex r s) ⟨a, b₁⟩ from Eq.subst Eq₂ $ fun xb acb ihb lt b₁ h Eq₃ => have newEq₃ : b₂ = xb from eqOfHEq Eq₃; have aux : (∀ (y : β a), s a y xb → Acc (Lex r s) ⟨a, y⟩) → ∀ (b₁ : β a), s a b₁ b₂ → Acc (Lex r s) ⟨a, b₁⟩ from Eq.subst newEq₃ (fun ihb b₁ h => ihb b₁ h); aux ihb b₁ h; aux xb acb ihb lt b₁ h Eq₃); aux rfl (HEq.refl xb) -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded r) (hb : ∀ x, WellFounded (s x)) : WellFounded (Lex r s) := WellFounded.intro $ fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b end section variables {α : Sort u} {β : Sort v} def lexNdep (r : α → α → Prop) (s : β → β → Prop) := Lex r (fun a => s) def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) := WellFounded.intro $ fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b end section variables {α : Sort u} {β : Sort v} -- Reverse lexicographical order based on r and s inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop | left : ∀ {a₁ a₂ : α} (b : β), r a₁ a₂ → RevLex ⟨a₁, b⟩ ⟨a₂, b⟩ | right : ∀ (a₁ : α) {b₁ : β} (a₂ : α) {b₂ : β}, s b₁ b₂ → RevLex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ end section open WellFounded variables {α : Sort u} {β : Sort v} variables {r : α → α → Prop} {s : β → β → Prop} def revLexAccessible {b} (acb : Acc s b) (aca : ∀ a, Acc r a): ∀ a, Acc (RevLex r s) ⟨a, b⟩ := Acc.recOn acb $ fun (xb acb) (ihb : ∀ y, s y xb → ∀ a, Acc (RevLex r s) ⟨a, y⟩) (a) => Acc.recOn (aca a) $ fun (xa aca) (iha : ∀ y, r y xa → Acc (RevLex r s) (mk y xb)) => Acc.intro ⟨xa, xb⟩ $ fun (p) (lt : RevLex r s p ⟨xa, xb⟩) => have aux : xa = xa → xb = xb → Acc (RevLex r s) p from @RevLex.recOn α β r s (fun p₁ p₂ _ => fst p₂ = xa → snd p₂ = xb → Acc (RevLex r s) p₁) p ⟨xa, xb⟩ lt (fun (a₁ a₂ b) (h : r a₁ a₂) (Eq₂ : a₂ = xa) (Eq₃ : b = xb) => show Acc (RevLex r s) ⟨a₁, b⟩ from have r₁ : r a₁ xa from Eq.recOn Eq₂ h; have aux : Acc (RevLex r s) ⟨a₁, xb⟩ from iha a₁ r₁; Eq.recOn (Eq.symm Eq₃) aux) (fun (a₁ b₁ a₂ b₂) (h : s b₁ b₂) (Eq₂ : a₂ = xa) (Eq₃ : b₂ = xb) => show Acc (RevLex r s) (mk a₁ b₁) from have s₁ : s b₁ xb from Eq.recOn Eq₃ h; ihb b₁ s₁ a₁); aux rfl rfl def revLexWf (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) := WellFounded.intro $ fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a end section def skipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop := RevLex emptyRelation s def skipLeftWf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (skipLeft α s) := revLexWf emptyWf hb def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : skipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := RevLex.right _ _ _ h end instance HasWellFounded {α : Type u} {β : α → Type v} [s₁ : HasWellFounded α] [s₂ : ∀ a, HasWellFounded (β a)] : HasWellFounded (PSigma β) := {r := Lex s₁.r (fun a => (s₂ a).r), wf := lexWf s₁.wf (fun a => (s₂ a).wf)} end PSigma
7e6c22bb5e92dc34004e6567827e5b4d71c23880
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/analysis/calculus/deriv.lean
49a86241bf94f8cb8155a29525e8d04a2658806c
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
72,900
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial.derivative /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - sum of finitely many functions - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space big_operators filter open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝[s] x) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp lemma has_deriv_within_at.has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := has_deriv_within_at_iff_has_fderiv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right, simp only [(∘)], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s \ {x}] x) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s] x) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[{x}ᶜ] x) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) : deriv_within f s x = deriv f x := by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl } section congr /-! ### Congruence properties of derivatives -/ theorem filter.eventually_eq.has_deriv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := h₀.has_fderiv_at_filter_iff hx (by simp [h₁]) lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa hL.has_deriv_at_filter_iff hx rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x := h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx) lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw hL.fderiv_within_eq hs hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x := by { unfold deriv, rwa filter.eventually_eq.fderiv_eq } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 := deriv_id x lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_add_const hxs] lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x := by simp only [deriv, fderiv_add_const] theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c + f y) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_const_add hxs] lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x := by simp only [deriv, fderiv_const_add] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply] lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_sub_const hxs] lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x := by simp only [deriv, fderiv_sub_const] theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c - f y) s x = -deriv_within f s x := by simp [deriv_within, fderiv_within_const_sub hxs] lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x := by simp only [← deriv_within_univ, deriv_within_const_sub unique_diff_within_at_univ] end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := by simpa using (hg.comp x hh).has_deriv_at_filter theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg $ hh.continuous_within_at.tendsto_nhds_within hst) hh /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g ∘ h) (h' • g') x := by simpa using (hg.comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of a scalar and vector functions -/ theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) {L : filter E} (hh₁ : has_deriv_at_filter h₁ h₁' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (h₁ ∘ f) (h₁' • f') x L := by { convert has_fderiv_at_filter.comp x hh₁ hf, ext x, simp [mul_comm] } theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (h₁ ∘ f) (h₁' • f') x := (hh₁.mono hf.continuous_at).comp_has_fderiv_at_filter x hf theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (hh₁.mono hf.continuous_within_at).comp_has_fderiv_at_filter x hf theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s t} (x) (hh₁ : has_deriv_within_at h₁ h₁' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : maps_to f s t) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (has_deriv_at_filter.mono hh₁ $ hf.continuous_within_at.tendsto_nhds_within hst).comp_has_fderiv_at_filter x hf /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_strict_deriv_at.comp (hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) : has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_deriv_at_filter (f^[n]) (f'^n) x L := begin have := hf.iterate hL hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_deriv_at (f^[n]) (f'^n) x := begin have := has_fderiv_at.iterate hf hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_deriv_within_at (f^[n]) (f'^n) s x := begin have := has_fderiv_within_at.iterate hf hx hs n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_deriv_at (f^[n]) (f'^n) x := begin have := hf.iterate hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) (λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono (mem_nhds_sets (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} : differentiable_within_at 𝕜 (λx, c x / d) s x := by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc] @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : differentiable_at 𝕜 (λ x, c x / d) x := by simp [div_eq_inv_mul, hc] lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} : differentiable_on 𝕜 (λx, c x / d) s := by simp [div_eq_inv_mul, differentiable_on.const_mul, hc] @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} : differentiable 𝕜 (λx, c x / d) := by simp [div_eq_inv_mul, differentiable.const_mul, hc] lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : deriv (λx, c x / d) x = (deriv c x) / d := by simp [div_eq_inv_mul, deriv_const_mul, hc] end division theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an nonzero derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) : has_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a) (hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) : ¬differentiable_within_at 𝕜 g s a := begin intro hg, have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha, simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _) end theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) : ¬differentiable_at 𝕜 g a := begin intro hg, have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm, simpa using has_deriv_at_unique this (has_deriv_at_id a) end end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_C_mul_X_pow], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, nat.sub_zero, nat.cast_one] }, { simp only [function.iterate_succ_apply', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_fpow m hx).has_deriv_at theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = (∏ i in finset.range k, (m - i) : ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [function.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], exact filter.eventually_eq.deriv_eq (eventually.mono (mem_nhds_sets is_open_ne hx) @ihk) } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in 𝓝[s \ {x}] x, (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in 𝓝[s] x, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently, refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
b2dc5477fb972073e53aa8e38a539b0cbb1fa372
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Init/Notation.lean
81d7c50bb544f5d5558e072917da57601782f0de
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
13,228
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 Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude import Init.Coe /-- Auxiliary type used to represent syntax categories. We mainly use them to attach doc strings to syntax categories. -/ structure Lean.Parser.Category namespace Lean.Parser.Category /-- `command` is the syntax category for things that appear at the top level of a lean file. For example, `def foo := 1` is a `command`, as is `namespace Foo` and `end Foo`. Commands generally have an effect on the state of adding something to the environment (like a new definition), as well as commands like `variable` which modify future commands within a scope. -/ def command : Category := {} /-- `term` is the builtin syntax category for terms. A term denotes an expression in lean's type theory, for example `2 + 2` is a term. The difference between `Term` and `Expr` is that the former is a kind of syntax, while the latter is the result of elaboration. For example `by simp` is also a `Term`, but it elaborates to different `Expr`s depending on the context. -/ def term : Category := {} /-- `tactic` is the builtin syntax category for tactics. These appear after `by` in proofs, and they are programs that take in the proof context (the hypotheses in scope plus the type of the term to synthesize) and construct a term of the expected type. For example, `simp` is a tactic, used in: ``` example : 2 + 2 = 4 := by simp ``` -/ def tactic : Category := {} /-- `doElem` is a builtin syntax category for elements that can appear in the `do` notation. For example, `let x ← e` is a `doElem`, and a `do` block consists of a list of `doElem`s. -/ def doElem : Category := {} /-- `level` is a builtin syntax category for universe levels. This is the `u` in `Sort u`: it can contain `max` and `imax`, addition with constants, and variables. -/ def level : Category := {} /-- `attr` is a builtin syntax category for attributes. Declarations can be annotated with attributes using the `@[...]` notation. -/ def attr : Category := {} /-- `stx` is a builtin syntax category for syntax. This is the abbreviated parser notation used inside `syntax` and `macro` declarations. -/ def stx : Category := {} /-- `prio` is a builtin syntax category for priorities. Priorities are used in many different attributes. Higher numbers denote higher priority, and for example typeclass search will try high priority instances before low priority. In addition to literals like `37`, you can also use `low`, `mid`, `high`, as well as add and subtract priorities. -/ def prio : Category := {} /-- `prec` is a builtin syntax category for precedences. A precedence is a value that expresses how tightly a piece of syntax binds: for example `1 + 2 * 3` is parsed as `1 + (2 * 3)` because `*` has a higher pr0ecedence than `+`. Higher numbers denote higher precedence. In addition to literals like `37`, there are some special named priorities: * `arg` for the precedence of function arguments * `max` for the highest precedence used in term parsers (not actually the maximum possible value) * `lead` for the precedence of terms not supposed to be used as arguments and you can also add and subtract precedences. -/ def prec : Category := {} end Lean.Parser.Category namespace Lean.Parser.Syntax /-! DSL for specifying parser precedences and priorities -/ syntax:65 (name := addPrec) prec " + " prec:66 : prec syntax:65 (name := subPrec) prec " - " prec:66 : prec syntax:65 (name := addPrio) prio " + " prio:66 : prio syntax:65 (name := subPrio) prio " - " prio:66 : prio end Lean.Parser.Syntax namespace Lean instance : CoeHead (TSyntax ks) Syntax where coe stx := stx.raw instance : Coe SyntaxNodeKind SyntaxNodeKinds where coe k := List.cons k List.nil end Lean /-- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) -/ macro "max" : prec => `(1024) /-- precedence used for application arguments (`do`, `by`, ...) -/ macro "arg" : prec => `(1023) /-- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...) -/ macro "lead" : prec => `(1022) macro "(" p:prec ")" : prec => return p /-- minimum precedence used in term parsers -/ macro "min" : prec => `(10) /-- `(min+1)` (we can only write `min+1` after `Meta.lean`) -/ macro "min1" : prec => `(11) /-- `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`. We use `max_prec` to workaround bootstrapping issues. -/ macro "max_prec" : term => `(1024) macro "default" : prio => `(1000) macro "low" : prio => `(100) macro "mid" : prio => `(1000) macro "high" : prio => `(10000) macro "(" p:prio ")" : prio => return p -- Basic notation for defining parsers -- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses syntax:arg stx:max "+" : stx syntax:arg stx:max "*" : stx syntax:arg stx:max "?" : stx syntax:2 stx:2 " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂)) /-- Comma-separated sequence. -/ macro:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /-- Comma-separated sequence with optional trailing comma. -/ macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro:arg "!" x:stx:max : stx => `(stx| notFollowedBy($x)) syntax (name := rawNatLit) "nat_lit " num : term infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:55 " ||| " => HOr.hOr infixl:58 " ^^^ " => HXor.hXor infixl:60 " &&& " => HAnd.hAnd infixl:65 " + " => HAdd.hAdd infixl:65 " - " => HSub.hSub infixl:70 " * " => HMul.hMul infixl:70 " / " => HDiv.hDiv infixl:70 " % " => HMod.hMod infixl:75 " <<< " => HShiftLeft.hShiftLeft infixl:75 " >>> " => HShiftRight.hShiftRight infixr:80 " ^ " => HPow.hPow infixl:65 " ++ " => HAppend.hAppend prefix:100 "-" => Neg.neg prefix:100 "~~~" => Complement.complement /-! Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators. It addresses issue #382. -/ macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y) macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y) macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y) macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y) macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y) macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y) macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y) macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y) macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y) macro_rules | `($x ++ $y) => `(binop% HAppend.hAppend $x $y) -- declare ASCII alternatives first so that the latter Unicode unexpander wins infix:50 " <= " => LE.le infix:50 " ≤ " => LE.le infix:50 " < " => LT.lt infix:50 " >= " => GE.ge infix:50 " ≥ " => GE.ge infix:50 " > " => GT.gt infix:50 " = " => Eq infix:50 " == " => BEq.beq /-! Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel% LE.le $x $y) macro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y) macro_rules | `($x < $y) => `(binrel% LT.lt $x $y) macro_rules | `($x > $y) => `(binrel% GT.gt $x $y) macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y) macro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y) macro_rules | `($x = $y) => `(binrel% Eq $x $y) macro_rules | `($x == $y) => `(binrel_no_prop% BEq.beq $x $y) infixr:35 " /\\ " => And infixr:35 " ∧ " => And infixr:30 " \\/ " => Or infixr:30 " ∨ " => Or notation:max "¬" p:40 => Not p infixl:35 " && " => and infixl:30 " || " => or notation:max "!" b:40 => not b infix:50 " ∈ " => Membership.mem notation:50 a:50 " ∉ " b:50 => ¬ (a ∈ b) infixr:67 " :: " => List.cons syntax:20 term:21 " <|> " term:20 : term syntax:60 term:61 " >> " term:60 : term infixl:55 " >>= " => Bind.bind notation:60 a:60 " <*> " b:61 => Seq.seq a fun _ : Unit => b notation:60 a:60 " <* " b:61 => SeqLeft.seqLeft a fun _ : Unit => b notation:60 a:60 " *> " b:61 => SeqRight.seqRight a fun _ : Unit => b infixr:100 " <$> " => Functor.map macro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y) macro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y) syntax (name := termDepIfThenElse) ppRealGroup(ppRealFill(ppIndent("if " ident " : " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(if $h : $c then $t else $e) => do let mvar ← Lean.withRef c `(?m) `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppRealGroup(ppRealFill(ppIndent("if " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(if $c then $t else $e) => do let mvar ← Lean.withRef c `(?m) `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite $mvar $t $e) macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat => $t | _ => $e) syntax (name := boolIfThenElse) ppRealGroup(ppRealFill(ppIndent("bif " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(bif $c then $t else $e) => `(cond $c $t $e) syntax:min term " <| " term:min : term macro_rules | `($f $args* <| $a) => `($f $args* $a) | `($f <| $a) => `($f $a) syntax:min term " |> " term:min1 : term macro_rules | `($a |> $f $args*) => `($f $args* $a) | `($a |> $f) => `($f $a) /-- Haskell-like pipe `<|` -/ -- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations. syntax:min term atomic(" $" ws) term:min : term macro_rules | `($f $args* $ $a) => `($f $args* $a) | `($f $ $a) => `($f $a) syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p)) /-- `without_expected_type t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `without_expected_type` is not effective in this case. -/ macro "without_expected_type " x:term : term => `(let aux := $x; aux) syntax "[" term,* "]" : term syntax "%[" term,* "|" term "]" : term -- auxiliary notation for creating big list literals namespace Lean macro_rules | `([ $elems,* ]) => do -- NOTE: we do not have `TSepArray.getElems` yet at this point let rec expandListLit (i : Nat) (skip : Bool) (result : TSyntax `term) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← ``(List.cons $(⟨elems.elemsAndSeps.get! i⟩) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← ``(List.nil)) else `(%[ $elems,* | List.nil ]) -- Declare `this` as a keyword that unhygienically binds to a scope-less `this` assumption (or other binding). -- The keyword prevents declaring a `this` binding except through metapgrogramming, as is done by `have`/`show`. /-- Special identifier introduced by "anonymous" `have : ...`, `suffices p ...` etc. -/ macro tk:"this" : term => return Syntax.ident tk.getHeadInfo "this".toSubstring `this [] /-- Category for carrying raw syntax trees between macros; any content is printed as is by the pretty printer. The only accepted parser for this category is an antiquotation. -/ declare_syntax_cat rawStx instance : Coe Syntax (TSyntax `rawStx) where coe stx := ⟨stx⟩ /-- `with_annotate_term stx e` annotates the lexical range of `stx : Syntax` with term info for `e`. -/ scoped syntax (name := withAnnotateTerm) "with_annotate_term " rawStx ppSpace term : term syntax (name := deprecated) "deprecated " (ident)? : attr /-- When `parent_dir` contains the current Lean file, `include_str "path" / "to" / "file"` becomes a string literal with the contents of the file at `"parent_dir" / "path" / "to" / "file"`. If this file cannot be read, elaboration fails. -/ syntax (name := includeStr) "include_str" term : term
13676ba01a394ba42cd9cebff5dff409d358a4a4
b29f946a2f0afd23ef86b9219116968babbb9f4f
/src/filter2.lean
6dbcb7fa3df44b89354fd23df9017982546f2c95
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M1P1-lean
58be7394fded719d95e45e6b10e1ecf2ed3c7c4c
3723468cc50f8bebd00a9811caf25224a578de17
refs/heads/master
1,587,063,867,779
1,572,727,164,000
1,572,727,164,000
165,845,802
14
4
Apache-2.0
1,549,730,698,000
1,547,554,675,000
Lean
UTF-8
Lean
false
false
2,398
lean
-- begin header import limits import order.filter import topology.basic import topology.instances.real --set_option pp.notation false --set_option trace.simplify.rewrite true -- end header /- Section Sequence tending to a limit -/ /- Here we show that a sequence $(a_n)_n$ tends to a limit $ℓ$ iff the cofinite filter on ℕ tends to the neighbourgood filter of $ℓ$ along the function $n ↦ a_n$. -/ /- Lemma Let $(a_n)$ be a sequence of reals and let $ℓ$ be a real. Then $a_n→ℓ$ if and only if `filter.tendsto a (filter.cofinite) (nhds l)`. -/ --set_option pp.all true lemma is_limit_iff_tendsto (a : ℕ → ℝ) (l : ℝ) : (∀ ε, ε > 0 → ∃ N : ℕ, ∀ n, N ≤ n → | a n - l| < ε) ↔ filter.tendsto a (filter.cofinite) (nhds l) := begin split, { -- a_n → l implies filter.tendsto intro Hl, intro X, intro HX, -- What we have to prove is that if that X is a nhd of l -- then `X ∈ (filter.map a filter.cofinite).sets` -- These next three lines show that WLOG X is B(l,ε) rw metric.mem_nhds_iff at HX, rcases HX with ⟨ε, Hε, Hlε⟩, change X ∈ filter.map a filter.cofinite, apply filter.mem_sets_of_superset _ Hlε, -- Now let's figure out what this filter.map stuff means -- [dsimp and unfold faffing] show a ⁻¹' metric.ball l ε ∈ filter.cofinite.sets, show a ⁻¹' metric.ball l ε ∈ filter.cofinite, -- Let's use the fact that a n → l rcases Hl ε Hε with ⟨N, HN⟩, let S := {n : ℕ | N ≤ n}, -- this is the definition of a_n → l have HS : S ⊆ a ⁻¹' metric.ball l ε, { intros n Hn, show a n ∈ _, rw metric.mem_ball, exact HN n Hn, }, suffices : S ∈ filter.cofinite.sets, exact filter.mem_sets_of_superset this HS, show set.finite (-S), show set.finite {n : ℕ | ¬ (N ≤ n)}, simp only [not_le], exact ⟨set.fintype_lt_nat _⟩ }, { -- filter.tendsto implies a_n → l intro h, intros ε hε, -- need N such that n ≥ N implies a_n → l, <<<<<<< HEAD:src/filter2.lean have : metric.ball l ε ∈ (nhds l), exact metric.mem_nhds_iff.2 ⟨ε, hε, by refl⟩, ======= unfold filter.tendsto at HF, unfold filter.map at HF, -- have X := HF _, --(metric.ball l ε), >>>>>>> af595e6d3ec06d523668e63274e1ad9f6149e10e:src/filter.lean sorry }, end
067aa178f11eea9c2b4fd4d8930cdaf488056713
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/ring.lean
93849ba91def5392baf4a2df2d84d7df5224e89a
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
17,308
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 Structures with multiplicative and additive components, including semirings, rings, and fields. The development is modeled after Isabelle's library. -/ import logic.eq logic.connectives data.unit data.sigma data.prod import algebra.binary algebra.group open eq eq.ops variable {A : Type} /- auxiliary classes -/ structure distrib [class] (A : Type) extends has_mul A, has_add A := (left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c)) (right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c)) theorem left_distrib [distrib A] (a b c : A) : a * (b + c) = a * b + a * c := !distrib.left_distrib theorem right_distrib [distrib A] (a b c : A) : (a + b) * c = a * c + b * c := !distrib.right_distrib structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A := (zero_mul : ∀a, mul zero a = zero) (mul_zero : ∀a, mul a zero = zero) theorem zero_mul [simp] [mul_zero_class A] (a : A) : 0 * a = 0 := !mul_zero_class.zero_mul theorem mul_zero [simp] [mul_zero_class A] (a : A) : a * 0 = 0 := !mul_zero_class.mul_zero structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A := (zero_ne_one : zero ≠ one) theorem zero_ne_one [s: zero_ne_one_class A] : 0 ≠ (1:A) := @zero_ne_one_class.zero_ne_one A s /- semiring -/ structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A, distrib A, mul_zero_class A section semiring variables [s : semiring A] (a b c : A) include s theorem one_add_one_eq_two : 1 + 1 = (2:A) := by unfold bit0 theorem ne_zero_of_mul_ne_zero_right {a b : A} (H : a * b ≠ 0) : a ≠ 0 := suppose a = 0, have a * b = 0, by rewrite [this, zero_mul], H this theorem ne_zero_of_mul_ne_zero_left {a b : A} (H : a * b ≠ 0) : b ≠ 0 := suppose b = 0, have a * b = 0, by rewrite [this, mul_zero], H this local attribute right_distrib [simp] theorem distrib_three_right (a b c d : A) : (a + b + c) * d = a * d + b * d + c * d := by simp end semiring /- comm semiring -/ structure comm_semiring [class] (A : Type) extends semiring A, comm_monoid A -- TODO: we could also define a cancelative comm_semiring, i.e. satisfying -- c ≠ 0 → c * a = c * b → a = b. section comm_semiring variables [s : comm_semiring A] (a b c : A) include s protected definition algebra.dvd (a b : A) : Prop := ∃c, b = a * c definition comm_semiring_has_dvd [instance] [priority algebra.prio] : has_dvd A := has_dvd.mk algebra.dvd theorem dvd.intro {a b c : A} (H : a * c = b) : a ∣ b := exists.intro _ H⁻¹ theorem dvd_of_mul_right_eq {a b c : A} (H : a * c = b) : a ∣ b := dvd.intro H theorem dvd.intro_left {a b c : A} (H : c * a = b) : a ∣ b := dvd.intro (by rewrite mul.comm at H; exact H) theorem dvd_of_mul_left_eq {a b c : A} (H : c * a = b) : a ∣ b := dvd.intro_left H theorem exists_eq_mul_right_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = a * c := H theorem dvd.elim {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = a * c → P) : P := exists.elim H₁ H₂ theorem exists_eq_mul_left_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = c * a := dvd.elim H (take c, assume H1 : b = a * c, exists.intro c (H1 ⬝ !mul.comm)) theorem dvd.elim_left {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd H₁) (take c, assume H₃ : b = c * a, H₂ c H₃) theorem dvd.refl [simp] : a ∣ a := dvd.intro !mul_one theorem dvd.trans {a b c : A} (H₁ : a ∣ b) (H₂ : b ∣ c) : a ∣ c := dvd.elim H₁ (take d, assume H₃ : b = a * d, dvd.elim H₂ (take e, assume H₄ : c = b * e, dvd.intro (show a * (d * e) = c, by rewrite [-mul.assoc, -H₃, H₄]))) theorem eq_zero_of_zero_dvd {a : A} (H : 0 ∣ a) : a = 0 := dvd.elim H (take c, assume H' : a = 0 * c, H' ⬝ !zero_mul) theorem dvd_zero [simp] : a ∣ 0 := dvd.intro !mul_zero theorem one_dvd [simp] : 1 ∣ a := dvd.intro !one_mul theorem dvd_mul_right [simp] : a ∣ a * b := dvd.intro rfl theorem dvd_mul_left [simp] : a ∣ b * a := by simp theorem dvd_mul_of_dvd_left {a b : A} (H : a ∣ b) (c : A) : a ∣ b * c := dvd.elim H (take d, suppose b = a * d, dvd.intro (show a * (d * c) = b * c, by simp)) theorem dvd_mul_of_dvd_right {a b : A} (H : a ∣ b) (c : A) : a ∣ c * b := !mul.comm ▸ (dvd_mul_of_dvd_left H _) theorem mul_dvd_mul {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d := dvd.elim dvd_ab (take e, suppose b = a * e, dvd.elim dvd_cd (take f, suppose d = c * f, dvd.intro (show a * c * (e * f) = b * d, by simp))) theorem dvd_of_mul_right_dvd {a b c : A} (H : a * b ∣ c) : a ∣ c := dvd.elim H (take d, assume Habdc : c = a * b * d, dvd.intro (!mul.assoc⁻¹ ⬝ Habdc⁻¹)) theorem dvd_of_mul_left_dvd {a b c : A} (H : a * b ∣ c) : b ∣ c := dvd_of_mul_right_dvd (mul.comm a b ▸ H) theorem dvd_add {a b c : A} (Hab : a ∣ b) (Hac : a ∣ c) : a ∣ b + c := dvd.elim Hab (take d, suppose b = a * d, dvd.elim Hac (take e, suppose c = a * e, dvd.intro (show a * (d + e) = b + c, by rewrite [left_distrib]; substvars))) end comm_semiring /- ring -/ structure ring [class] (A : Type) extends add_comm_group A, monoid A, distrib A theorem ring.mul_zero [simp] [ring A] (a : A) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rewrite left_distrib, show a * 0 = 0, from (add.left_cancel this)⁻¹ theorem ring.zero_mul [simp] [ring A] (a : A) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add.left_cancel this)⁻¹ definition ring.to_semiring [trans_instance] [s : ring A] : semiring A := ⦃ semiring, s, mul_zero := ring.mul_zero, zero_mul := ring.zero_mul ⦄ section variables [s : ring A] (a b c d e : A) include s theorem neg_mul_eq_neg_mul : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rewrite [-right_distrib, add.right_inv, zero_mul] end theorem neg_mul_eq_mul_neg : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rewrite [-left_distrib, add.right_inv, mul_zero] end theorem neg_mul_eq_neg_mul_symm [simp] : - a * b = - (a * b) := eq.symm !neg_mul_eq_neg_mul theorem mul_neg_eq_neg_mul_symm [simp] : a * - b = - (a * b) := eq.symm !neg_mul_eq_mul_neg theorem neg_mul_neg : -a * -b = a * b := by simp theorem neg_mul_comm : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul : -a = -1 * a := by simp theorem mul_sub_left_distrib : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib ... = a * b - a * c : by simp theorem mul_sub_right_distrib : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib ... = a * c - b * c : by simp -- TODO: can calc mode be improved to make this easier? -- TODO: there is also the other direction. It will be easier when we -- have the simplifier. 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 rewrite {b*e+_}add.comm ... ↔ a * e + c - b * e = d : iff.symm !sub_eq_iff_eq_add ... ↔ a * e - b * e + c = d : by rewrite sub_add_eq_add_sub ... ↔ (a - b) * e + c = d : by rewrite mul_sub_right_distrib theorem mul_add_eq_mul_add_of_sub_mul_add_eq : (a - b) * e + c = d → a * e + c = b * e + d := iff.mpr !mul_add_eq_mul_add_iff_sub_mul_add_eq theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := iff.mp !mul_add_eq_mul_add_iff_sub_mul_add_eq theorem mul_neg_one_eq_neg : a * (-1) = -a := have a + a * -1 = 0, from calc a + a * -1 = a * 1 + a * -1 : by simp ... = a * (1 + -1) : left_distrib ... = 0 : by simp, symm (neg_eq_of_add_eq_zero this) theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : A} (H : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := have a ≠ 0, from (suppose a = 0, have a * b = 0, by rewrite [this, zero_mul], absurd this H), have b ≠ 0, from (suppose b = 0, have a * b = 0, by rewrite [this, mul_zero], absurd this H), and.intro `a ≠ 0` `b ≠ 0` end structure comm_ring [class] (A : Type) extends ring A, comm_semigroup A definition comm_ring.to_comm_semiring [trans_instance] [s : comm_ring A] : comm_semiring A := ⦃ comm_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul ⦄ section variables [s : comm_ring A] (a b c d e : A) include s local attribute left_distrib right_distrib [simp] theorem mul_self_sub_mul_self_eq : a * a - b * b = (a + b) * (a - b) := by simp theorem mul_self_sub_one_eq : a * a - 1 = (a + 1) * (a - 1) := by simp theorem add_mul_self_eq : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp ... = a*a + 2*a*b + b*b : by rewrite one_add_one_eq_two theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) := iff.intro (suppose a ∣ -b, dvd.elim this (take c, suppose -b = a * c, dvd.intro (show a * -c = b, by rewrite [-neg_mul_eq_mul_neg, -this, neg_neg]))) (suppose a ∣ b, dvd.elim this (take c, suppose b = a * c, dvd.intro (show a * -c = -b, by rewrite [-neg_mul_eq_mul_neg, -this]))) theorem dvd_neg_of_dvd : (a ∣ b) → (a ∣ -b) := iff.mpr !dvd_neg_iff_dvd theorem dvd_of_dvd_neg : (a ∣ -b) → (a ∣ b) := iff.mp !dvd_neg_iff_dvd theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) := iff.intro (suppose -a ∣ b, dvd.elim this (take c, suppose b = -a * c, dvd.intro (show a * -c = b, by rewrite [-neg_mul_comm, this]))) (suppose a ∣ b, dvd.elim this (take c, suppose b = a * c, dvd.intro (show -a * -c = b, by rewrite [neg_mul_neg, this]))) theorem neg_dvd_of_dvd : (a ∣ b) → (-a ∣ b) := iff.mpr !neg_dvd_iff_dvd theorem dvd_of_neg_dvd : (-a ∣ b) → (a ∣ b) := iff.mp !neg_dvd_iff_dvd theorem dvd_sub (H₁ : (a ∣ b)) (H₂ : (a ∣ c)) : (a ∣ b - c) := dvd_add H₁ (!dvd_neg_of_dvd H₂) end /- integral domains -/ structure no_zero_divisors [class] (A : Type) extends has_mul A, has_zero A := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀a b, mul a b = zero → a = zero ∨ b = zero) theorem eq_zero_or_eq_zero_of_mul_eq_zero {A : Type} [no_zero_divisors A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := !no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero H theorem eq_zero_of_mul_self_eq_zero {A : Type} [no_zero_divisors A] {a : A} (H : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero H) (assume H', H') (assume H', H') structure integral_domain [class] (A : Type) extends comm_ring A, no_zero_divisors A, zero_ne_one_class A section variables [s : integral_domain A] (a b c d e : A) include s theorem mul_ne_zero {a b : A} (H1 : a ≠ 0) (H2 : b ≠ 0) : a * b ≠ 0 := suppose a * b = 0, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume H3, H1 H3) (assume H4, H2 H4) theorem eq_of_mul_eq_mul_right {a b c : A} (Ha : a ≠ 0) (H : b * a = c * a) : b = c := have b * a - c * a = 0, from iff.mp !eq_iff_sub_eq_zero H, have (b - c) * a = 0, by rewrite [mul_sub_right_distrib, this], have b - c = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha, iff.elim_right !eq_iff_sub_eq_zero this theorem eq_of_mul_eq_mul_left {a b c : A} (Ha : a ≠ 0) (H : a * b = a * c) : b = c := have a * b - a * c = 0, from iff.mp !eq_iff_sub_eq_zero H, have a * (b - c) = 0, by rewrite [mul_sub_left_distrib, this], have b - c = 0, from or_resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha, iff.elim_right !eq_iff_sub_eq_zero this -- TODO: do we want the iff versions? theorem eq_zero_of_mul_eq_self_right {a b : A} (H₁ : b ≠ 1) (H₂ : a * b = a) : a = 0 := have b - 1 ≠ 0, from suppose b - 1 = 0, H₁ (!zero_add ▸ eq_add_of_sub_eq this), have a * b - a = 0, by simp, have a * (b - 1) = 0, by rewrite [mul_sub_left_distrib, mul_one]; apply this, show a = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) `b - 1 ≠ 0` theorem eq_zero_of_mul_eq_self_left {a b : A} (H₁ : b ≠ 1) (H₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right H₁ (!mul.comm ▸ H₂) theorem mul_self_eq_mul_self_iff (a b : A) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (suppose a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul.comm, -mul_self_sub_mul_self_eq, this, sub_self], have a - b = 0 ∨ a + b = 0, from !eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (suppose a - b = 0, or.inl (eq_of_sub_eq_zero this)) (suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (suppose a = b ∨ a = -b, or.elim this (suppose a = b, by rewrite this) (suppose a = -b, by rewrite [this, neg_mul_neg])) theorem mul_self_eq_one_iff (a : A) : a * a = 1 ↔ a = 1 ∨ a = -1 := have a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rewrite mul_one at this; exact this -- TODO: c - b * c → c = 0 ∨ b = 1 and variants theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) := dvd.elim Hdvd (take d, suppose a * c = a * b * d, have b * d = c, from eq_of_mul_eq_mul_left Ha (mul.assoc a b d ▸ this⁻¹), dvd.intro this) theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) := dvd.elim Hdvd (take d, suppose c * a = b * a * d, have b * d * a = c * a, from by rewrite [mul.right_comm, -this], have b * d = c, from eq_of_mul_eq_mul_right Ha this, dvd.intro this) end namespace norm_num local attribute bit0 bit1 add1 [reducible] local attribute right_distrib left_distrib [simp] theorem mul_zero [mul_zero_class A] (a : A) : a * zero = zero := by simp theorem zero_mul [mul_zero_class A] (a : A) : zero * a = zero := by simp theorem mul_one [monoid A] (a : A) : a * one = a := by simp theorem mul_bit0 [distrib A] (a b : A) : a * (bit0 b) = bit0 (a * b) := by simp theorem mul_bit0_helper [distrib A] (a b t : A) (H : a * b = t) : a * (bit0 b) = bit0 t := by rewrite -H; simp theorem mul_bit1 [semiring A] (a b : A) : a * (bit1 b) = bit0 (a * b) + a := by simp theorem mul_bit1_helper [semiring A] (a b s t : A) (Hs : a * b = s) (Ht : bit0 s + a = t) : a * (bit1 b) = t := by simp theorem subst_into_prod [has_mul A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := by simp theorem mk_cong (op : A → A) (a b : A) (H : a = b) : op a = op b := by simp theorem neg_add_neg_eq_of_add_add_eq_zero [add_comm_group A] (a b c : A) (H : c + a + b = 0) : -a + -b = c := begin apply add_neg_eq_of_eq_add, apply neg_eq_of_add_eq_zero, simp end theorem neg_add_neg_helper [add_comm_group A] (a b c : A) (H : a + b = c) : -a + -b = -c := begin apply iff.mp !neg_eq_neg_iff_eq, simp end theorem neg_add_pos_eq_of_eq_add [add_comm_group A] (a b c : A) (H : b = c + a) : -a + b = c := begin apply neg_add_eq_of_eq_add, simp end theorem neg_add_pos_helper1 [add_comm_group A] (a b c : A) (H : b + c = a) : -a + b = -c := begin apply neg_add_eq_of_eq_add, apply eq_add_neg_of_add_eq H end theorem neg_add_pos_helper2 [add_comm_group A] (a b c : A) (H : a + c = b) : -a + b = c := begin apply neg_add_eq_of_eq_add, rewrite H end theorem pos_add_neg_helper [add_comm_group A] (a b c : A) (H : b + a = c) : a + b = c := by simp theorem sub_eq_add_neg_helper [add_comm_group A] (t₁ t₂ e w₁ w₂: A) (H₁ : t₁ = w₁) (H₂ : t₂ = w₂) (H : w₁ + -w₂ = e) : t₁ - t₂ = e := by simp theorem pos_add_pos_helper [add_comm_group A] (a b c h₁ h₂ : A) (H₁ : a = h₁) (H₂ : b = h₂) (H : h₁ + h₂ = c) : a + b = c := by simp theorem subst_into_subtr [add_group A] (l r t : A) (prt : l + -r = t) : l - r = t := by simp theorem neg_neg_helper [add_group A] (a b : A) (H : a = -b) : -a = b := by simp theorem neg_mul_neg_helper [ring A] (a b c : A) (H : a * b = c) : (-a) * (-b) = c := by simp theorem neg_mul_pos_helper [ring A] (a b c : A) (H : a * b = c) : (-a) * b = -c := by simp theorem pos_mul_neg_helper [ring A] (a b c : A) (H : a * b = c) : a * (-b) = -c := by simp end norm_num attribute [simp] zero_mul mul_zero at simplifier.unit attribute [simp] neg_mul_eq_neg_mul_symm mul_neg_eq_neg_mul_symm at simplifier.neg attribute [simp] left_distrib right_distrib at simplifier.distrib
56b74a5e74bce4c8eaab89d1680be5c988dd9e5f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/completion5.lean
5d9fffe661650bb0418d2d1af73b23c2edd4daee
[ "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
185
lean
structure C where f1 : Nat f2 : Bool b1 : String def f (c : C) : IO Unit := visit c where visit (c : C) : IO Unit := let x := c. --^ textDocument/completion
14fe58cd0c41f3b73a3ca1d1dae6000ac197231c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/nat/basic.lean
1fbdfe539943d7e8416dbadbc80df530ac04dce4
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,411
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.logic universes u namespace Mathlib namespace nat notation:1024 "ℕ" => Mathlib.nat inductive less_than_or_equal (a : ℕ) : ℕ → Prop where | refl : less_than_or_equal a a | step : ∀ {b : ℕ}, less_than_or_equal a b → less_than_or_equal a (Nat.succ b) protected instance has_le : HasLessEq ℕ := { LessEq := less_than_or_equal } protected def le (n : ℕ) (m : ℕ) := less_than_or_equal n m protected def lt (n : ℕ) (m : ℕ) := less_than_or_equal (Nat.succ n) m protected instance has_lt : HasLess ℕ := { Less := nat.lt } def pred : ℕ → ℕ := Nat.pred protected def sub : ℕ → ℕ → ℕ := Nat.sub protected def mul : ℕ → ℕ → ℕ := Nat.mul protected instance has_sub : Sub ℕ := { sub := Nat.sub } protected instance has_mul : Mul ℕ := { mul := Nat.mul } -- defeq to the instance provided by comm_semiring protected instance has_dvd : has_dvd ℕ := has_dvd.mk fun (a b : ℕ) => ∃ (c : ℕ), b = a * c protected instance decidable_eq : DecidableEq ℕ := sorry def repeat {α : Type u} (f : ℕ → α → α) : ℕ → α → α := sorry protected instance inhabited : Inhabited ℕ := { default := 0 } @[simp] theorem nat_zero_eq_zero : 0 = 0 := rfl /- properties of inequality -/ protected def le_refl (a : ℕ) : a ≤ a := less_than_or_equal.refl theorem le_succ (n : ℕ) : n ≤ Nat.succ n := less_than_or_equal.step (nat.le_refl n) theorem succ_le_succ {n : ℕ} {m : ℕ} : n ≤ m → Nat.succ n ≤ Nat.succ m := fun (h : n ≤ m) => less_than_or_equal._oldrec (nat.le_refl (Nat.succ n)) (fun (a : ℕ) (b : less_than_or_equal n a) => less_than_or_equal.step) h theorem zero_le (n : ℕ) : 0 ≤ n := sorry theorem zero_lt_succ (n : ℕ) : 0 < Nat.succ n := succ_le_succ (zero_le n) def succ_pos (n : ℕ) : 0 < Nat.succ n := zero_lt_succ theorem not_succ_le_zero (n : ℕ) : Nat.succ n ≤ 0 → False := sorry theorem not_lt_zero (a : ℕ) : ¬a < 0 := not_succ_le_zero a theorem pred_le_pred {n : ℕ} {m : ℕ} : n ≤ m → Nat.pred n ≤ Nat.pred m := sorry theorem le_of_succ_le_succ {n : ℕ} {m : ℕ} : Nat.succ n ≤ Nat.succ m → n ≤ m := pred_le_pred protected instance decidable_le (a : ℕ) (b : ℕ) : Decidable (a ≤ b) := sorry protected instance decidable_lt (a : ℕ) (b : ℕ) : Decidable (a < b) := nat.decidable_le (Nat.succ a) b protected theorem eq_or_lt_of_le {a : ℕ} {b : ℕ} (h : a ≤ b) : a = b ∨ a < b := less_than_or_equal.cases_on h (Or.inl rfl) fun (n : ℕ) (h : less_than_or_equal a n) => Or.inr (succ_le_succ h) theorem lt_succ_of_le {a : ℕ} {b : ℕ} : a ≤ b → a < Nat.succ b := succ_le_succ @[simp] theorem succ_sub_succ_eq_sub (a : ℕ) (b : ℕ) : Nat.succ a - Nat.succ b = a - b := nat.rec_on b ((fun (this : Nat.succ a - 1 = a - 0) => this) (Eq.refl (Nat.succ a - 1))) fun (b : ℕ) => congr_arg Nat.pred theorem not_succ_le_self (n : ℕ) : ¬Nat.succ n ≤ n := Nat.rec (not_succ_le_zero 0) (fun (a : ℕ) (b : ¬Nat.succ a ≤ a) (c : Nat.succ (Nat.succ a) ≤ Nat.succ a) => b (le_of_succ_le_succ c)) n protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self n protected theorem le_trans {n : ℕ} {m : ℕ} {k : ℕ} (h1 : n ≤ m) : m ≤ k → n ≤ k := less_than_or_equal._oldrec h1 fun (p : ℕ) (h2 : less_than_or_equal m p) => less_than_or_equal.step theorem pred_le (n : ℕ) : Nat.pred n ≤ n := nat.cases_on n (idRhs (less_than_or_equal (Nat.pred 0) (Nat.pred 0)) less_than_or_equal.refl) fun (n : ℕ) => idRhs (less_than_or_equal (Nat.pred (Nat.succ n)) (Nat.succ n)) (less_than_or_equal.step less_than_or_equal.refl) theorem pred_lt {n : ℕ} : n ≠ 0 → Nat.pred n < n := sorry theorem sub_le (a : ℕ) (b : ℕ) : a - b ≤ a := nat.rec_on b (nat.le_refl (a - 0)) fun (b₁ : ℕ) => nat.le_trans (pred_le (a - b₁)) theorem sub_lt {a : ℕ} {b : ℕ} : 0 < a → 0 < b → a - b < a := sorry protected theorem lt_of_lt_of_le {n : ℕ} {m : ℕ} {k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans /- Basic nat.add lemmas -/ protected theorem zero_add (n : ℕ) : 0 + n = n := sorry theorem succ_add (n : ℕ) (m : ℕ) : Nat.succ n + m = Nat.succ (n + m) := sorry theorem add_succ (n : ℕ) (m : ℕ) : n + Nat.succ m = Nat.succ (n + m) := rfl protected theorem add_zero (n : ℕ) : n + 0 = n := rfl theorem add_one (n : ℕ) : n + 1 = Nat.succ n := rfl theorem succ_eq_add_one (n : ℕ) : Nat.succ n = n + 1 := rfl /- Basic lemmas for comparing numerals -/ protected theorem bit0_succ_eq (n : ℕ) : bit0 (Nat.succ n) = Nat.succ (Nat.succ (bit0 n)) := (fun (this : Nat.succ (Nat.succ n + n) = Nat.succ (Nat.succ (n + n))) => this) (congr_arg Nat.succ (succ_add n n)) protected theorem zero_lt_bit0 {n : ℕ} : n ≠ 0 → 0 < bit0 n := sorry protected theorem zero_lt_bit1 (n : ℕ) : 0 < bit1 n := zero_lt_succ (bit0 n) protected theorem bit0_ne_zero {n : ℕ} : n ≠ 0 → bit0 n ≠ 0 := sorry protected theorem bit1_ne_zero (n : ℕ) : bit1 n ≠ 0 := (fun (this : Nat.succ (n + n) ≠ 0) => this) fun (h : Nat.succ (n + n) = 0) => nat.no_confusion h
cdd8fe572f2ba0ca58069707970ff8ad41fc12fc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/matrix/pequiv.lean
43cd965d4ce0f20b8fb88df41121f8659a5c5f53
[ "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
6,108
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 data.matrix.basic import data.pequiv /-! # partial equivalences for matrices Using partial equivalences to represent matrices. This file introduces the function `pequiv.to_matrix`, which returns a matrix containing ones and zeros. For any partial equivalence `f`, `f.to_matrix i j = 1 ↔ f i = some j`. The following important properties of this function are proved `to_matrix_trans : (f.trans g).to_matrix = f.to_matrix ⬝ g.to_matrix` `to_matrix_symm : f.symm.to_matrix = f.to_matrixᵀ` `to_matrix_refl : (pequiv.refl n).to_matrix = 1` `to_matrix_bot : ⊥.to_matrix = 0` This theory gives the matrix representation of projection linear maps, and their right inverses. For example, the matrix `(single (0 : fin 1) (i : fin n)).to_matrix` corresponds to the ith projection map from R^n to R. Any injective function `fin m → fin n` gives rise to a `pequiv`, whose matrix is the projection map from R^m → R^n represented by the same function. The transpose of this matrix is the right inverse of this map, sending anything not in the image to zero. ## notations This file uses the notation ` ⬝ ` for `matrix.mul` and `ᵀ` for `matrix.transpose`. -/ namespace pequiv open matrix universes u v variables {k l m n : Type*} variables {α : Type v} open_locale matrix /-- `to_matrix` returns a matrix containing ones and zeros. `f.to_matrix i j` is `1` if `f i = some j` and `0` otherwise -/ def to_matrix [decidable_eq n] [has_zero α] [has_one α] (f : m ≃. n) : matrix m n α | i j := if j ∈ f i then 1 else 0 lemma mul_matrix_apply [fintype m] [decidable_eq m] [semiring α] (f : l ≃. m) (M : matrix m n α) (i j) : (f.to_matrix ⬝ M) i j = option.cases_on (f i) 0 (λ fi, M fi j) := begin dsimp [to_matrix, matrix.mul_apply], cases h : f i with fi, { simp [h] }, { rw finset.sum_eq_single fi; simp [h, eq_comm] {contextual := tt} } end lemma to_matrix_symm [decidable_eq m] [decidable_eq n] [has_zero α] [has_one α] (f : m ≃. n) : (f.symm.to_matrix : matrix n m α) = f.to_matrixᵀ := by ext; simp only [transpose, mem_iff_mem f, to_matrix]; congr @[simp] lemma to_matrix_refl [decidable_eq n] [has_zero α] [has_one α] : ((pequiv.refl n).to_matrix : matrix n n α) = 1 := by ext; simp [to_matrix, one_apply]; congr lemma matrix_mul_apply [fintype m] [semiring α] [decidable_eq n] (M : matrix l m α) (f : m ≃. n) (i j) : (M ⬝ f.to_matrix) i j = option.cases_on (f.symm j) 0 (λ fj, M i fj) := begin dsimp [to_matrix, matrix.mul_apply], cases h : f.symm j with fj, { simp [h, ← f.eq_some_iff] }, { rw finset.sum_eq_single fj, { simp [h, ← f.eq_some_iff], }, { intros b H n, simp [h, ← f.eq_some_iff, n.symm], }, { simp, } } end lemma to_pequiv_mul_matrix [fintype m] [decidable_eq m] [semiring α] (f : m ≃ m) (M : matrix m n α) : (f.to_pequiv.to_matrix ⬝ M) = λ i, M (f i) := by { ext i j, rw [mul_matrix_apply, equiv.to_pequiv_apply] } lemma mul_to_pequiv_to_matrix {m n α : Type*} [fintype n] [decidable_eq n] [semiring α] (f : n ≃ n) (M : matrix m n α) : (M ⬝ f.to_pequiv.to_matrix) = M.submatrix id (f.symm) := matrix.ext $ λ i j, by rw [pequiv.matrix_mul_apply, ←equiv.to_pequiv_symm, equiv.to_pequiv_apply, matrix.submatrix_apply, id.def] lemma to_matrix_trans [fintype m] [decidable_eq m] [decidable_eq n] [semiring α] (f : l ≃. m) (g : m ≃. n) : ((f.trans g).to_matrix : matrix l n α) = f.to_matrix ⬝ g.to_matrix := begin ext i j, rw [mul_matrix_apply], dsimp [to_matrix, pequiv.trans], cases f i; simp end @[simp] lemma to_matrix_bot [decidable_eq n] [has_zero α] [has_one α] : ((⊥ : pequiv m n).to_matrix : matrix m n α) = 0 := rfl lemma to_matrix_injective [decidable_eq n] [monoid_with_zero α] [nontrivial α] : function.injective (@to_matrix m n α _ _ _) := begin classical, assume f g, refine not_imp_not.1 _, simp only [matrix.ext_iff.symm, to_matrix, pequiv.ext_iff, not_forall, exists_imp_distrib], assume i hi, use i, cases hf : f i with fi, { cases hg : g i with gi, { cc }, { use gi, simp, } }, { use fi, simp [hf.symm, ne.symm hi] } end lemma to_matrix_swap [decidable_eq n] [ring α] (i j : n) : (equiv.swap i j).to_pequiv.to_matrix = (1 : matrix n n α) - (single i i).to_matrix - (single j j).to_matrix + (single i j).to_matrix + (single j i).to_matrix := begin ext, dsimp [to_matrix, single, equiv.swap_apply_def, equiv.to_pequiv, one_apply], split_ifs; {simp * at *} <|> { exfalso, assumption }, end @[simp] lemma single_mul_single [fintype n] [decidable_eq k] [decidable_eq m] [decidable_eq n] [semiring α] (a : m) (b : n) (c : k) : ((single a b).to_matrix : matrix _ _ α) ⬝ (single b c).to_matrix = (single a c).to_matrix := by rw [← to_matrix_trans, single_trans_single] lemma single_mul_single_of_ne [fintype n] [decidable_eq n] [decidable_eq k] [decidable_eq m] [semiring α] {b₁ b₂ : n} (hb : b₁ ≠ b₂) (a : m) (c : k) : ((single a b₁).to_matrix : matrix _ _ α) ⬝ (single b₂ c).to_matrix = 0 := by rw [← to_matrix_trans, single_trans_single_of_ne hb, to_matrix_bot] /-- Restatement of `single_mul_single`, which will simplify expressions in `simp` normal form, when associativity may otherwise need to be carefully applied. -/ @[simp] lemma single_mul_single_right [fintype n] [fintype k] [decidable_eq n] [decidable_eq k] [decidable_eq m] [semiring α] (a : m) (b : n) (c : k) (M : matrix k l α) : (single a b).to_matrix ⬝ ((single b c).to_matrix ⬝ M) = (single a c).to_matrix ⬝ M := by rw [← matrix.mul_assoc, single_mul_single] /-- We can also define permutation matrices by permuting the rows of the identity matrix. -/ lemma equiv_to_pequiv_to_matrix [decidable_eq n] [has_zero α] [has_one α] (σ : equiv n n) (i j : n) : σ.to_pequiv.to_matrix i j = (1 : matrix n n α) (σ i) j := if_congr option.some_inj rfl rfl end pequiv
b9280d13f2da839eeff9d873be199a51ae566359
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/convex/gauge.lean
46f967daad3d7c1ac157ffa89b3ace29451efcf4
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
18,376
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.star 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 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 := (p.nonneg x).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, p.smul, 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 [p.smul, 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 (p.nonneg _) hε, refine hr ⟨hpε, (p x + ε)⁻¹ • x, _, smul_inv_smul₀ hpε.ne' _⟩, rw [p.mem_ball_zero, p.smul, 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
708253897ad533e3f9bcaa5344a165c6f1332757
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/special_functions/polynomials.lean
a16da0b2919bcf242e4d4672af8a8a954a30c353
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
6,131
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.asymptotics.asymptotic_equivalent import analysis.asymptotics.specific_asymptotics import data.polynomial.erase_lead /-! # Limits related to polynomial and rational functions This file proves basic facts about limits of polynomial and rationals functions. The main result is `eval_is_equivalent_at_top_eval_lead`, which states that for any polynomial `P` of degree `n` with leading coefficient `a`, the corresponding polynomial function is equivalent to `a * x^n` as `x` goes to +∞. We can then use this result to prove various limits for polynomial and rational functions, depending on the degrees and leading coefficients of the considered polynomials. -/ open filter finset asymptotics open_locale asymptotics topological_space namespace polynomial variables {𝕜 : Type*} [normed_linear_ordered_field 𝕜] [order_topology 𝕜] (P Q : polynomial 𝕜) lemma is_equivalent_at_top_lead : (λ x, eval x P) ~[at_top] (λ x, P.leading_coeff * x ^ P.nat_degree) := begin by_cases h : P = 0, { simp [h] }, { conv_lhs { funext, rw [polynomial.eval_eq_finset_sum, sum_range_succ, add_comm] }, exact is_equivalent.refl.add_is_o (is_o.sum $ λ i hi, is_o.const_mul_left (is_o.const_mul_right (λ hz, h $ leading_coeff_eq_zero.mp hz) $ is_o_pow_pow_at_top_of_lt (mem_range.mp hi)) _) } end lemma tendsto_at_top_of_leading_coeff_nonneg (hdeg : 1 ≤ P.degree) (hnng : 0 ≤ P.leading_coeff) : tendsto (λ x, eval x P) at_top at_top := P.is_equivalent_at_top_lead.symm.tendsto_at_top (tendsto_const_mul_pow_at_top (le_nat_degree_of_coe_le_degree hdeg) (lt_of_le_of_ne hnng $ ne.symm $ mt leading_coeff_eq_zero.mp $ ne_zero_of_coe_le_degree hdeg)) lemma tendsto_at_bot_of_leading_coeff_nonpos (hdeg : 1 ≤ P.degree) (hnps : P.leading_coeff ≤ 0) : tendsto (λ x, eval x P) at_top at_bot := P.is_equivalent_at_top_lead.symm.tendsto_at_bot (tendsto_neg_const_mul_pow_at_top (le_nat_degree_of_coe_le_degree hdeg) (lt_of_le_of_ne hnps $ mt leading_coeff_eq_zero.mp $ ne_zero_of_coe_le_degree hdeg)) lemma abs_tendsto_at_top (hdeg : 1 ≤ P.degree) : tendsto (λ x, abs $ eval x P) at_top at_top := begin by_cases hP : 0 ≤ P.leading_coeff, { exact tendsto_abs_at_top_at_top.comp (P.tendsto_at_top_of_leading_coeff_nonneg hdeg hP)}, { push_neg at hP, exact tendsto_abs_at_bot_at_top.comp (P.tendsto_at_bot_of_leading_coeff_nonpos hdeg hP.le)} end lemma is_equivalent_at_top_div : (λ x, (eval x P)/(eval x Q)) ~[at_top] λ x, P.leading_coeff/Q.leading_coeff * x^(P.nat_degree - Q.nat_degree : ℤ) := begin by_cases hP : P = 0, { simp [hP] }, by_cases hQ : Q = 0, { simp [hQ] }, refine (P.is_equivalent_at_top_lead.symm.div Q.is_equivalent_at_top_lead.symm).symm.trans (eventually_eq.is_equivalent ((eventually_gt_at_top 0).mono $ λ x hx, _)), simp [← div_mul_div, hP, hQ, fpow_sub hx.ne.symm] end lemma div_tendsto_zero_of_degree_lt (hdeg : P.degree < Q.degree) : tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 0) := begin by_cases hP : P = 0, { simp [hP, tendsto_const_nhds] }, rw ← nat_degree_lt_nat_degree_iff hP at hdeg, refine (is_equivalent_at_top_div P Q).symm.tendsto_nhds _, rw ← mul_zero, refine (tendsto_fpow_at_top_zero _).const_mul _, linarith end lemma div_tendsto_leading_coeff_div_of_degree_eq (hdeg : P.degree = Q.degree) : tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 $ P.leading_coeff / Q.leading_coeff) := begin refine (is_equivalent_at_top_div P Q).symm.tendsto_nhds _, rw show (P.nat_degree : ℤ) = Q.nat_degree, by simp [hdeg, nat_degree], simp [tendsto_const_nhds] end lemma div_tendsto_at_top_of_degree_gt' (hdeg : Q.degree < P.degree) (hpos : 0 < P.leading_coeff/Q.leading_coeff) : tendsto (λ x, (eval x P)/(eval x Q)) at_top at_top := begin have hQ : Q ≠ 0 := λ h, by {simp only [h, div_zero, leading_coeff_zero] at hpos, linarith}, rw ← nat_degree_lt_nat_degree_iff hQ at hdeg, refine (is_equivalent_at_top_div P Q).symm.tendsto_at_top _, apply tendsto.const_mul_at_top hpos, apply tendsto_fpow_at_top_at_top, linarith end lemma div_tendsto_at_top_of_degree_gt (hdeg : Q.degree < P.degree) (hQ : Q ≠ 0) (hnng : 0 ≤ P.leading_coeff/Q.leading_coeff) : tendsto (λ x, (eval x P)/(eval x Q)) at_top at_top := have ratio_pos : 0 < P.leading_coeff/Q.leading_coeff, from lt_of_le_of_ne hnng (div_ne_zero (λ h, ne_zero_of_degree_gt hdeg $ leading_coeff_eq_zero.mp h) (λ h, hQ $ leading_coeff_eq_zero.mp h)).symm, div_tendsto_at_top_of_degree_gt' P Q hdeg ratio_pos lemma div_tendsto_at_bot_of_degree_gt' (hdeg : Q.degree < P.degree) (hneg : P.leading_coeff/Q.leading_coeff < 0) : tendsto (λ x, (eval x P)/(eval x Q)) at_top at_bot := begin have hQ : Q ≠ 0 := λ h, by {simp only [h, div_zero, leading_coeff_zero] at hneg, linarith}, rw ← nat_degree_lt_nat_degree_iff hQ at hdeg, refine (is_equivalent_at_top_div P Q).symm.tendsto_at_bot _, apply tendsto.neg_const_mul_at_top hneg, apply tendsto_fpow_at_top_at_top, linarith end lemma div_tendsto_at_bot_of_degree_gt (hdeg : Q.degree < P.degree) (hQ : Q ≠ 0) (hnps : P.leading_coeff/Q.leading_coeff ≤ 0) : tendsto (λ x, (eval x P)/(eval x Q)) at_top at_bot := have ratio_neg : P.leading_coeff/Q.leading_coeff < 0, from lt_of_le_of_ne hnps (div_ne_zero (λ h, ne_zero_of_degree_gt hdeg $ leading_coeff_eq_zero.mp h) (λ h, hQ $ leading_coeff_eq_zero.mp h)), div_tendsto_at_bot_of_degree_gt' P Q hdeg ratio_neg lemma eval_div_tendsto_at_top_of_degree_gt (hdeg : Q.degree < P.degree) (hQ : Q ≠ 0) : tendsto (λ x, abs ((eval x P)/(eval x Q))) at_top at_top := begin by_cases h : 0 ≤ P.leading_coeff/Q.leading_coeff, { exact tendsto_abs_at_top_at_top.comp (P.div_tendsto_at_top_of_degree_gt Q hdeg hQ h) }, { push_neg at h, exact tendsto_abs_at_bot_at_top.comp (P.div_tendsto_at_bot_of_degree_gt Q hdeg hQ h.le) } end end polynomial
535a95290fa85addb9d6e3183b2754cdc8dcf894
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic.lean
971b9e085fba360870f79d406201702c283b0a96
[ "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
807
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.Meta.Tactic.Intro import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Contradiction import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Rewrite import Lean.Meta.Tactic.Generalize import Lean.Meta.Tactic.Replace import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Meta.Tactic.ElimInfo import Lean.Meta.Tactic.Delta import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Simp import Lean.Meta.Tactic.AuxLemma import Lean.Meta.Tactic.SplitIf import Lean.Meta.Tactic.Split import Lean.Meta.Tactic.Cleanup
d9ded4e8117e0808798ac28b9057d071fb8438a4
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/data/real/basic.lean
f062495ba23e0ae48b015797b4accda414364508
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
24,496
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice data.real.cau_seq_completion algebra.big_operators algebra.archimedean order.bounds def real := @cau_seq.completion.Cauchy ℚ _ _ _ abs _ notation `ℝ` := real namespace real open cau_seq cau_seq.completion def of_rat (x : ℚ) : ℝ := of_rat x def mk (x : cau_seq ℚ abs) : ℝ := cau_seq.completion.mk x def comm_ring_aux : comm_ring ℝ := cau_seq.completion.comm_ring instance : comm_ring ℝ := { ..comm_ring_aux } /- Extra instances to short-circuit type class resolution -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) instance : has_lt ℝ := ⟨λ x y, quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩⟩ @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := mk_eq theorem quotient_mk_eq_mk (f : cau_seq ℚ abs) : ⟦f⟧ = mk f := rfl theorem mk_eq_mk {f : cau_seq ℚ abs} : cau_seq.completion.mk f = mk f := rfl @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := iff_of_eq (congr_arg pos (sub_zero f)) protected def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨real.le⟩ @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := or_congr iff.rfl quotient.eq theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := quotient.induction_on₃ a b c (λ f g h, iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub)) instance : linear_order ℝ := { le := (≤), lt := (<), le_refl := λ a, or.inr rfl, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ f g h, by simpa [quotient_mk_eq_mk] using le_trans, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [quotient_mk_eq_mk] using lt_iff_le_not_le, le_antisymm := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [mk_eq, quotient_mk_eq_mk] using @cau_seq.le_antisymm _ _ f g, le_total := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [quotient_mk_eq_mk] using le_total f g } instance : partial_order ℝ := by apply_instance instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := quotient.induction_on₂ a b $ λ f g, show pos (f - 0) → pos (g - 0) → pos (f * g - 0), by simpa using cau_seq.mul_pos instance : linear_ordered_comm_ring ℝ := { add_le_add_left := λ a b h c, (le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h, zero_ne_one := ne_of_lt real.zero_lt_one, mul_nonneg := λ a b a0 b0, match a0, b0 with | or.inl a0, or.inl b0 := le_of_lt (real.mul_pos a0 b0) | or.inr a0, _ := by simp [a0.symm] | _, or.inr b0 := by simp [b0.symm] end, mul_pos := @real.mul_pos, zero_lt_one := real.zero_lt_one, add_lt_add_left := λ a b h c, (real.add_lt_add_iff_left c).2 h, ..real.comm_ring, ..real.linear_order } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_ring ℝ := by apply_instance instance : ordered_ring ℝ := by apply_instance instance : linear_ordered_semiring ℝ := by apply_instance instance : ordered_semiring ℝ := by apply_instance instance : ordered_comm_group ℝ := by apply_instance instance : ordered_cancel_comm_monoid ℝ := by apply_instance instance : ordered_comm_monoid ℝ := by apply_instance instance : domain ℝ := by apply_instance local attribute [instance] classical.prop_decidable noncomputable instance : discrete_linear_ordered_field ℝ := { decidable_le := by apply_instance, ..real.linear_ordered_comm_ring, ..real.domain, ..cau_seq.completion.discrete_field } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_field ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_semiring ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_group ℝ := by apply_instance noncomputable instance discrete_field : discrete_field ℝ := by apply_instance noncomputable instance : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : nonzero_comm_ring ℝ := by apply_instance noncomputable instance : decidable_linear_order ℝ := by apply_instance noncomputable instance : lattice.distrib_lattice ℝ := by apply_instance noncomputable instance : lattice.lattice ℝ := by apply_instance noncomputable instance : lattice.semilattice_inf ℝ := by apply_instance noncomputable instance : lattice.semilattice_sup ℝ := by apply_instance noncomputable instance : lattice.has_inf ℝ := by apply_instance noncomputable instance : lattice.has_sup ℝ := by apply_instance lemma le_of_forall_epsilon_le {a b : real} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, calc a ≤ b + (x - b) : h (x-b) $ sub_pos.2 hxb ... = x : by rw [add_comm]; simp open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := eq_cast of_rat rfl of_rat_add of_rat_mul theorem le_mk_of_forall_le {x : ℝ} {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := quotient.induction_on x $ λ g h, le_of_not_lt $ λ ⟨K, K0, hK⟩, let ⟨i, H⟩ := exists_forall_ge_and h $ exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in begin apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} : (∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x | ⟨i, H⟩ := by rw [← neg_le_neg_iff, ← mk_eq_mk, mk_neg]; exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, quotient.induction_on x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ /- mark `real` irreducible in order to prevent `auto_cases` unfolding reals, since users rarely want to consider real numbers as Cauchy sequences. Marking `comm_ring_aux` `irreducible` is done to ensure that there are no problems with non definitionally equal instances, caused by making `real` irreducible-/ attribute [irreducible] real comm_ring_aux noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable def Sup (S : set ℝ) : ℝ := if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable def Inf (S : set ℝ) : ℝ := -Sup {x | -x ∈ S} theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ open lattice noncomputable instance lattice : lattice ℝ := by apply_instance noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := real.Sup, Inf := real.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, decidable_le := classical.dec_rel _, ..real.linear_order, ..real.lattice} theorem Sup_empty : lattice.Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : lattice.Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Inf_empty : lattice.Inf (∅ : set ℝ) = 0 := show Inf ∅ = 0, by simp [Inf]; exact Sup_empty theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : lattice.Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb _ $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) ((sub_lt_self_iff _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x := suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin intros x x0, cases x0, cases le_total x 1 with x1 x1, { rcases H x0 x1 with ⟨y, y0, hy⟩, exact ⟨y, le_of_lt y0, hy⟩ }, { have := (inv_le_inv x0 zero_lt_one).2 x1, rw inv_one at this, rcases H (inv_pos x0) this with ⟨y, y0, hy⟩, refine ⟨y⁻¹, le_of_lt (inv_pos y0), _⟩, rw [← mul_inv', hy, inv_inv'] }, { exact ⟨0, by simp [x0.symm]⟩ } end, λ x x0 x1, begin let S := {y | 0 < y ∧ y * y ≤ x}, have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩, have ub : ∀ y ∈ S, (y:ℝ) ≤ 1, { intros y yS, cases yS with y0 yx, refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _, simpa using le_trans yx x1 }, have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb), refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩, { rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h, rcases h with ⟨y, ⟨y0, yx⟩, hy⟩, rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy, rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩, rw [div_lt_iff y0] at hz, exact not_lt_of_lt ((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz)) ((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) }, { let s := Sup S, let y := s + (x - s * s) / 3, replace h : 0 < x - s * s := sub_pos.2 h, have _30 := bit1_pos zero_le_one, have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30), refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩), rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul, ← le_div_iff (div_pos h _30), div_div_cancel (ne_of_gt h)], apply add_le_add, { simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) }, { rw [div_le_one_iff_le _30], refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _), exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } } end def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ | 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt | (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2 theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i | 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div]; apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _) | (n + 1) := le_max_left _ _ /- TODO(Mario): finish the proof theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧ mk ⟨sqrt_aux f, h⟩ = x := begin rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩, suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x, { exact this.imp (λ h e, ⟨x, x0, hx, e⟩) }, apply of_near, suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i, { rcases this with ⟨δ, δ0, hδ⟩, intros, } end -/ noncomputable def sqrt (x : ℝ) : ℝ := classical.some (sqrt_exists (le_max_left 0 x)) /-quotient.lift_on x (λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩) (λ f g e, begin rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩, rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩, refine xs.trans (eq.trans _ ys.symm), rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg], congr' 1, exact quotient.sound e end)-/ theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x := classical.some_spec (sqrt_exists (le_max_left 0 x)) /-quotient.induction_on x $ λ f, by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/ theorem sqrt_eq_zero_of_nonpos {x : ℝ} (h : x ≤ 0) : sqrt x = 0 := eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1 @[simp] theorem mul_self_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x * sqrt x = x := (sqrt_prop x).2.trans (max_eq_right h) @[simp] theorem sqrt_mul_self {x : ℝ} (h : 0 ≤ x) : sqrt (x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_iff_mul_self_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y * y = x := ⟨λ h, by rw [← h, mul_self_sqrt hx], λ h, by rw [← h, sqrt_mul_self hy]⟩ @[simp] theorem sqr_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x ^ 2 = x := by rw [pow_two, mul_self_sqrt h] @[simp] theorem sqrt_sqr {x : ℝ} (h : 0 ≤ x) : sqrt (x ^ 2) = x := by rw [pow_two, sqrt_mul_self h] theorem sqrt_eq_iff_sqr_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y ^ 2 = x := by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x := (le_total 0 x).elim (λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm) (λ h, by rw [← neg_mul_neg, sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h]) theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x := by rw [pow_two, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : sqrt 0 = 0 := by simpa using sqrt_mul_self (le_refl _) @[simp] theorem sqrt_one : sqrt 1 = 1 := by simpa using sqrt_mul_self zero_le_one @[simp] theorem sqrt_le {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y := by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), mul_self_sqrt hx, mul_self_sqrt hy] @[simp] theorem sqrt_lt {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y := lt_iff_lt_of_le_iff_le (sqrt_le hy hx) @[simp] theorem sqrt_inj {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero {x : ℝ} (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 := by simpa using sqrt_inj h (le_refl _) theorem sqrt_eq_zero' {x : ℝ} : sqrt x = 0 ↔ x ≤ 0 := (le_total x 0).elim (λ h, by simp [h, sqrt_eq_zero_of_nonpos]) (λ h, by simp [h]; simp [le_antisymm_iff, h]) @[simp] theorem sqrt_pos {x : ℝ} : 0 < sqrt x ↔ 0 < x := lt_iff_lt_of_le_iff_le (iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y := begin cases le_total 0 x with hx hx, { refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg}, rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc, mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] }, { rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy), sqrt_eq_zero'.2 hx, zero_mul] } end @[simp] theorem sqrt_mul {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y := by rw [mul_comm, sqrt_mul' _ hx, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ := (le_or_lt x 0).elim (λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h]) (λ h, by rw [ ← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos $ sqrt_pos.2 h), mul_self_sqrt (le_of_lt $ inv_pos h), ← mul_inv', mul_self_sqrt (le_of_lt h)]) @[simp] theorem sqrt_div {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y := by rw [division_def, sqrt_mul hx, sqrt_inv]; refl attribute [irreducible] real.le end real
fb9e94629283575c89e10bc7a0d0d595ab6d75f2
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/sites/types.lean
40d99d804ecce2d782dbf4a412be94cda2d1616f
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,506
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import category_theory.sites.canonical import category_theory.sites.sheaf_of_types /-! # Grothendieck Topology and Sheaves on the Category of Types In this file we define a Grothendieck topology on the category of types, and construct the canonical functor that sends a type to a sheaf over the category of types, and make this an equivalence of categories. Then we prove that the topology defined is the canonical topology. -/ universe u namespace category_theory /-- A Grothendieck topology associated to the category of all types. A sieve is a covering iff it is jointly surjective. -/ def types_grothendieck_topology : grothendieck_topology (Type u) := { sieves := λ α S, ∀ x : α, S (λ _ : punit, x), top_mem' := λ α x, trivial, pullback_stable' := λ α β S f hs x, hs (f x), transitive' := λ α S hs R hr x, hr (hs x) punit.star } /-- The discrete sieve on a type, which only includes arrows whose image is a subsingleton. -/ @[simps] def discrete_sieve (α : Type u) : sieve α := { arrows := λ β f, ∃ x, ∀ y, f y = x, downward_closed' := λ β γ f ⟨x, hx⟩ g, ⟨x, λ y, hx $ g y⟩ } lemma discrete_sieve_mem (α : Type u) : discrete_sieve α ∈ types_grothendieck_topology α := λ x, ⟨x, λ y, rfl⟩ /-- The discrete presieve on a type, which only includes arrows whose domain is a singleton. -/ def discrete_presieve (α : Type u) : presieve α := λ β f, ∃ x : β, ∀ y : β, y = x lemma generate_discrete_presieve_mem (α : Type u) : sieve.generate (discrete_presieve α) ∈ types_grothendieck_topology α := λ x, ⟨punit, id, λ _, x, ⟨punit.star, λ _, subsingleton.elim _ _⟩, rfl⟩ open presieve theorem is_sheaf_yoneda' {α : Type u} : is_sheaf types_grothendieck_topology (yoneda.obj α) := λ β S hs x hx, ⟨λ y, x _ (hs y) punit.star, λ γ f h, funext $ λ z, have _ := congr_fun (hx (𝟙 _) (λ _, z) (hs $ f z) h rfl) punit.star, by { convert this, exact rfl }, λ f hf, funext $ λ y, by convert congr_fun (hf _ (hs y)) punit.star⟩ /-- The yoneda functor that sends a type to a sheaf over the category of types -/ @[simps] def yoneda' : Type u ⥤ SheafOfTypes types_grothendieck_topology := { obj := λ α, ⟨yoneda.obj α, is_sheaf_yoneda'⟩, map := λ α β f, yoneda.map f } @[simp] lemma yoneda'_comp : yoneda'.{u} ⋙ induced_functor _ = yoneda := rfl open opposite /-- Given a presheaf `P` on the category of types, construct a map `P(α) → (α → P(*))` for all type `α`. -/ def eval (P : (Type u)ᵒᵖ ⥤ Type u) (α : Type u) (s : P.obj (op α)) (x : α) : P.obj (op punit) := P.map (↾λ _, x).op s /-- Given a sheaf `S` on the category of types, construct a map `(α → S(*)) → S(α)` that is inverse to `eval`. -/ noncomputable def types_glue (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) (α : Type u) (f : α → S.obj (op punit)) : S.obj (op α) := (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem α)).amalgamate (λ β g hg, S.map (↾λ x, punit.star).op $ f $ g $ classical.some hg) (λ β γ δ g₁ g₂ f₁ f₂ hf₁ hf₂ h, (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem δ)).is_separated_for.ext $ λ ε g ⟨x, hx⟩, have f₁ (classical.some hf₁) = f₂ (classical.some hf₂), from classical.some_spec hf₁ (g₁ $ g x) ▸ classical.some_spec hf₂ (g₂ $ g x) ▸ congr_fun h _, by { simp_rw [← functor_to_types.map_comp_apply, this, ← op_comp], refl }) lemma eval_types_glue {S hs α} (f) : eval.{u} S α (types_glue S hs α f) = f := funext $ λ x, (is_sheaf_for.valid_glue _ _ _ $ by exact ⟨punit.star, λ _, subsingleton.elim _ _⟩).trans $ by { convert functor_to_types.map_id_apply _ _, rw ← op_id, congr } lemma types_glue_eval {S hs α} (s) : types_glue.{u} S hs α (eval S α s) = s := (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem α)).is_separated_for.ext $ λ β f hf, (is_sheaf_for.valid_glue _ _ _ hf).trans $ (functor_to_types.map_comp_apply _ _ _ _).symm.trans $ by { rw ← op_comp, congr' 2, exact funext (λ x, congr_arg f (classical.some_spec hf x).symm) } /-- Given a sheaf `S`, construct an equivalence `S(α) ≃ (α → S(*))`. -/ @[simps] noncomputable def eval_equiv (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) (α : Type u) : S.obj (op α) ≃ (α → S.obj (op punit)) := { to_fun := eval S α, inv_fun := types_glue S hs α, left_inv := types_glue_eval, right_inv := eval_types_glue } lemma eval_map (S : (Type u)ᵒᵖ ⥤ Type u) (α β) (f : β ⟶ α) (s x) : eval S β (S.map f.op s) x = eval S α s (f x) := by { simp_rw [eval, ← functor_to_types.map_comp_apply, ← op_comp], refl } /-- Given a sheaf `S`, construct an isomorphism `S ≅ [-, S(*)]`. -/ @[simps] noncomputable def equiv_yoneda (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) : S ≅ yoneda.obj (S.obj (op punit)) := nat_iso.of_components (λ α, equiv.to_iso $ eval_equiv S hs $ unop α) $ λ α β f, funext $ λ s, funext $ λ x, eval_map S (unop α) (unop β) f.unop _ _ /-- Given a sheaf `S`, construct an isomorphism `S ≅ [-, S(*)]`. -/ @[simps] noncomputable def equiv_yoneda' (S : SheafOfTypes types_grothendieck_topology) : S ≅ yoneda'.obj (S.1.obj (op punit)) := { hom := (equiv_yoneda S.1 S.2).hom, inv := (equiv_yoneda S.1 S.2).inv, hom_inv_id' := (equiv_yoneda S.1 S.2).hom_inv_id, inv_hom_id' := (equiv_yoneda S.1 S.2).inv_hom_id } lemma eval_app (S₁ S₂ : SheafOfTypes.{u} types_grothendieck_topology) (f : S₁ ⟶ S₂) (α : Type u) (s : S₁.1.obj (op α)) (x : α) : eval S₂.1 α (f.app (op α) s) x = f.app (op punit) (eval S₁.1 α s x) := (congr_fun (f.2 (↾λ _ : punit, x).op) s).symm /-- `yoneda'` induces an equivalence of category between `Type u` and `Sheaf types_grothendieck_topology`. -/ @[simps] noncomputable def type_equiv : Type u ≌ SheafOfTypes types_grothendieck_topology := equivalence.mk yoneda' (induced_functor _ ⋙ (evaluation _ _).obj (op punit)) (nat_iso.of_components (λ α, /- α ≅ punit ⟶ α -/ { hom := λ x _, x, inv := λ f, f punit.star, hom_inv_id' := funext $ λ x, rfl, inv_hom_id' := funext $ λ f, funext $ λ y, punit.cases_on y rfl }) (λ α β f, rfl)) (iso.symm $ nat_iso.of_components (λ S, equiv_yoneda' S) (λ S₁ S₂ f, nat_trans.ext _ _ $ funext $ λ α, funext $ λ s, funext $ λ x, eval_app S₁ S₂ f (unop α) s x)) lemma subcanonical_types_grothendieck_topology : sheaf.subcanonical types_grothendieck_topology.{u} := sheaf.subcanonical.of_yoneda_is_sheaf _ (λ X, is_sheaf_yoneda') lemma types_grothendieck_topology_eq_canonical : types_grothendieck_topology.{u} = sheaf.canonical_topology (Type u) := le_antisymm subcanonical_types_grothendieck_topology $ Inf_le ⟨yoneda.obj (ulift bool), ⟨_, rfl⟩, grothendieck_topology.ext $ funext $ λ α, set.ext $ λ S, ⟨λ hs x, classical.by_contradiction $ λ hsx, have (λ _, ulift.up tt : (yoneda.obj (ulift bool)).obj (op punit)) = λ _, ulift.up ff := (hs punit (λ _, x)).is_separated_for.ext $ λ β f hf, funext $ λ y, hsx.elim $ S.2 hf $ λ _, y, bool.no_confusion $ ulift.up.inj $ (congr_fun this punit.star : _), λ hs β f, is_sheaf_yoneda' _ $ λ y, hs _⟩⟩ end category_theory
b2cd5e2722a423973683a639e1490aaa0b6c39cd
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/order/smul.lean
f80243dff13ee73122430251e245fc1e360acf6f
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
8,496
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import group_theory.group_action.group import algebra.smul_with_zero /-! # Ordered scalar product In this file we define * `ordered_smul R M` : an ordered additive commutative monoid `M` is an `ordered_smul` over an `ordered_semiring` `R` if the scalar product respects the order relation on the monoid and on the ring. There is a correspondence between this structure and convex cones, which is proven in `analysis/convex/cone.lean`. ## Implementation notes * We choose to define `ordered_smul` as a `Prop`-valued mixin, so that it can be used for actions, modules, and algebras (the axioms for an "ordered algebra" are exactly that the algebra is ordered as a module). * To get ordered modules and ordered vector spaces, it suffices to replace the `order_add_comm_monoid` and the `ordered_semiring` as desired. ## References * https://en.wikipedia.org/wiki/Ordered_module ## Tags ordered module, ordered scalar, ordered smul, ordered action, ordered vector space -/ /-- The ordered scalar product property is when an ordered additive commutative monoid with a partial order has a scalar multiplication which is compatible with the order. -/ @[protect_proj] class ordered_smul (R M : Type*) [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] : Prop := (smul_lt_smul_of_pos : ∀ {a b : M}, ∀ {c : R}, a < b → 0 < c → c • a < c • b) (lt_of_smul_lt_smul_of_pos : ∀ {a b : M}, ∀ {c : R}, c • a < c • b → 0 < c → a < b) namespace order_dual variables {R M : Type*} instance [has_scalar R M] : has_scalar R (order_dual M) := { smul := λ k x, order_dual.rec (λ x', (k • x' : M)) x } instance [has_zero R] [add_zero_class M] [h : smul_with_zero R M] : smul_with_zero R (order_dual M) := { zero_smul := λ m, order_dual.rec (zero_smul _) m, smul_zero := λ r, order_dual.rec (smul_zero' _) r, ..order_dual.has_scalar } instance [monoid R] [mul_action R M] : mul_action R (order_dual M) := { one_smul := λ m, order_dual.rec (one_smul _) m, mul_smul := λ r, order_dual.rec mul_smul r, ..order_dual.has_scalar } instance [monoid_with_zero R] [add_monoid M] [mul_action_with_zero R M] : mul_action_with_zero R (order_dual M) := { ..order_dual.mul_action, ..order_dual.smul_with_zero } instance [monoid_with_zero R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (order_dual M) := { smul_add := λ k a, order_dual.rec (λ a' b, order_dual.rec (smul_add _ _) b) a, smul_zero := λ r, order_dual.rec smul_zero r } instance [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] : ordered_smul R (order_dual M) := { smul_lt_smul_of_pos := λ a b, @ordered_smul.smul_lt_smul_of_pos R M _ _ _ _ b a, lt_of_smul_lt_smul_of_pos := λ a b, @ordered_smul.lt_of_smul_lt_smul_of_pos R M _ _ _ _ b a } @[simp] lemma to_dual_smul [has_scalar R M] {c : R} {a : M} : to_dual (c • a) = c • to_dual a := rfl @[simp] lemma of_dual_smul [has_scalar R M] {c : R} {a : order_dual M} : of_dual (c • a) = c • of_dual a := rfl end order_dual section ordered_smul variables {R M : Type*} [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] {a b : M} {c : R} lemma smul_lt_smul_of_pos : a < b → 0 < c → c • a < c • b := ordered_smul.smul_lt_smul_of_pos lemma smul_le_smul_of_nonneg (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c • a ≤ c • b := begin by_cases H₁ : c = 0, { simp [H₁, zero_smul] }, { by_cases H₂ : a = b, { rw H₂ }, { exact le_of_lt (smul_lt_smul_of_pos (lt_of_le_of_ne h₁ H₂) (lt_of_le_of_ne h₂ (ne.symm H₁))), } } end lemma smul_nonneg (hc : 0 ≤ c) (ha : 0 ≤ a) : 0 ≤ c • a := calc (0 : M) = c • (0 : M) : (smul_zero' M c).symm ... ≤ c • a : smul_le_smul_of_nonneg ha hc lemma smul_nonpos_of_nonneg_of_nonpos (hc : 0 ≤ c) (ha : a ≤ 0) : c • a ≤ 0 := @smul_nonneg R (order_dual M) _ _ _ _ _ _ hc ha lemma eq_of_smul_eq_smul_of_pos_of_le (h₁ : c • a = c • b) (hc : 0 < c) (hle : a ≤ b) : a = b := hle.lt_or_eq.resolve_left $ λ hlt, (smul_lt_smul_of_pos hlt hc).ne h₁ lemma lt_of_smul_lt_smul_of_nonneg (h : c • a < c • b) (hc : 0 ≤ c) : a < b := hc.eq_or_lt.elim (λ hc, false.elim $ lt_irrefl (0:M) $ by rwa [← hc, zero_smul, zero_smul] at h) (ordered_smul.lt_of_smul_lt_smul_of_pos h) lemma smul_lt_smul_iff_of_pos (hc : 0 < c) : c • a < c • b ↔ a < b := ⟨λ h, lt_of_smul_lt_smul_of_nonneg h hc.le, λ h, smul_lt_smul_of_pos h hc⟩ lemma smul_pos_iff_of_pos (hc : 0 < c) : 0 < c • a ↔ 0 < a := calc 0 < c • a ↔ c • 0 < c • a : by rw smul_zero' ... ↔ 0 < a : smul_lt_smul_iff_of_pos hc alias smul_pos_iff_of_pos ↔ _ smul_pos lemma monotone_smul_left (hc : 0 ≤ c) : monotone (has_scalar.smul c : M → M) := λ a b h, smul_le_smul_of_nonneg h hc lemma strict_mono_smul_left (hc : 0 < c) : strict_mono (has_scalar.smul c : M → M) := λ a b h, smul_lt_smul_of_pos h hc end ordered_smul /-- If `R` is a linear ordered semifield, then it suffices to verify only the first axiom of `ordered_smul`. Moreover, it suffices to verify that `a < b` and `0 < c` imply `c • a ≤ c • b`. We have no semifields in `mathlib`, so we use the assumption `∀ c ≠ 0, is_unit c` instead. -/ lemma ordered_smul.mk'' {R M : Type*} [linear_ordered_semiring R] [ordered_add_comm_monoid M] [mul_action_with_zero R M] (hR : ∀ {c : R}, c ≠ 0 → is_unit c) (hlt : ∀ ⦃a b : M⦄ ⦃c : R⦄, a < b → 0 < c → c • a ≤ c • b) : ordered_smul R M := begin have hlt' : ∀ ⦃a b : M⦄ ⦃c : R⦄, a < b → 0 < c → c • a < c • b, { refine λ a b c hab hc, (hlt hab hc).lt_of_ne _, rw [ne.def, (hR hc.ne').smul_left_cancel], exact hab.ne }, refine { smul_lt_smul_of_pos := hlt', .. }, intros a b c h hc, rcases (hR hc.ne') with ⟨c, rfl⟩, rw [← inv_smul_smul c a, ← inv_smul_smul c b], refine hlt' h (pos_of_mul_pos_left _ hc.le), simp only [c.mul_inv, zero_lt_one] end /-- If `R` is a linear ordered field, then it suffices to verify only the first axiom of `ordered_smul`. -/ lemma ordered_smul.mk' {k M : Type*} [linear_ordered_field k] [ordered_add_comm_monoid M] [mul_action_with_zero k M] (hlt : ∀ ⦃a b : M⦄ ⦃c : k⦄, a < b → 0 < c → c • a ≤ c • b) : ordered_smul k M := ordered_smul.mk'' (λ c hc, is_unit.mk0 _ hc) hlt instance linear_ordered_semiring.to_ordered_smul {R : Type*} [linear_ordered_semiring R] : ordered_smul R R := { smul_lt_smul_of_pos := ordered_semiring.mul_lt_mul_of_pos_left, lt_of_smul_lt_smul_of_pos := λ _ _ _ h hc, lt_of_mul_lt_mul_left h hc.le } section field variables {k M : Type*} [linear_ordered_field k] [ordered_add_comm_group M] [mul_action_with_zero k M] [ordered_smul k M] {a b : M} {c : k} lemma smul_le_smul_iff_of_pos (hc : 0 < c) : c • a ≤ c • b ↔ a ≤ b := ⟨λ h, inv_smul_smul₀ hc.ne' a ▸ inv_smul_smul₀ hc.ne' b ▸ smul_le_smul_of_nonneg h (inv_nonneg.2 hc.le), λ h, smul_le_smul_of_nonneg h hc.le⟩ lemma smul_lt_iff_of_pos (hc : 0 < c) : c • a < b ↔ a < c⁻¹ • b := calc c • a < b ↔ c • a < c • c⁻¹ • b : by rw [smul_inv_smul₀ hc.ne'] ... ↔ a < c⁻¹ • b : smul_lt_smul_iff_of_pos hc lemma lt_smul_iff_of_pos (hc : 0 < c) : a < c • b ↔ c⁻¹ • a < b := calc a < c • b ↔ c • c⁻¹ • a < c • b : by rw [smul_inv_smul₀ hc.ne'] ... ↔ c⁻¹ • a < b : smul_lt_smul_iff_of_pos hc lemma smul_le_iff_of_pos (hc : 0 < c) : c • a ≤ b ↔ a ≤ c⁻¹ • b := calc c • a ≤ b ↔ c • a ≤ c • c⁻¹ • b : by rw [smul_inv_smul₀ hc.ne'] ... ↔ a ≤ c⁻¹ • b : smul_le_smul_iff_of_pos hc lemma le_smul_iff_of_pos (hc : 0 < c) : a ≤ c • b ↔ c⁻¹ • a ≤ b := calc a ≤ c • b ↔ c • c⁻¹ • a ≤ c • b : by rw [smul_inv_smul₀ hc.ne'] ... ↔ c⁻¹ • a ≤ b : smul_le_smul_iff_of_pos hc variables (M) /-- Left scalar multiplication as an order isomorphism. -/ @[simps] def order_iso.smul_left {c : k} (hc : 0 < c) : M ≃o M := { to_fun := λ b, c • b, inv_fun := λ b, c⁻¹ • b, left_inv := inv_smul_smul₀ hc.ne', right_inv := smul_inv_smul₀ hc.ne', map_rel_iff' := λ b₁ b₂, smul_le_smul_iff_of_pos hc } end field
8e8d43e985743d40c591255c7ff7ac4b33afe065
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/system/random_auto.lean
0a6113826493ddd2549437a5fd1a82df5b8a6b0d
[]
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
3,273
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default universes u l namespace Mathlib /- Basic random number generator support based on the one available on the Haskell library -/ /- Interface for random number generators. -/ /- `range` returns the range of values returned by class random_gen (g : Type u) where range : g → ℕ × ℕ next : g → ℕ × g split : g → g × g the generator. -/ /- `next` operation returns a natural number that is uniformly distributed the range returned by `range` (including both end points), and a new generator. -/ /- The 'split' operation allows one to obtain two distinct random number generators. This is very useful in functional programs (for example, when passing a random number generator down to recursive calls). -/ /- "Standard" random number generator. -/ structure std_gen where s1 : ℕ s2 : ℕ def std_range : ℕ × ℕ := (1, bit0 (bit1 (bit0 (bit1 (bit0 (bit1 (bit0 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 1)))))))))))))))))))))))))))))) protected instance std_gen.has_repr : has_repr std_gen := has_repr.mk fun (_x : std_gen) => sorry def std_next : std_gen → ℕ × std_gen := sorry def std_split : std_gen → std_gen × std_gen := sorry protected instance std_gen.random_gen : random_gen std_gen := random_gen.mk (fun (_x : std_gen) => std_range) std_next std_split /-- Return a standard number generator. -/ def mk_std_gen (s : optParam ℕ 0) : std_gen := sorry /- Auxiliary function for random_nat_val. Generate random values until we exceed the target magnitude. `gen_lo` and `gen_mag` are the generator lower bound and magnitude. The parameter `r` is the "remaining" magnitude. -/ /-- Generate a random natural number in the interval [lo, hi]. -/ def rand_nat {gen : Type u} [random_gen gen] (g : gen) (lo : ℕ) (hi : ℕ) : ℕ × gen := let lo' : ℕ := ite (lo > hi) hi lo; let hi' : ℕ := ite (lo > hi) lo hi; sorry /-- Generate a random Boolean. -/ def rand_bool {gen : Type u} [random_gen gen] (g : gen) : Bool × gen := sorry end Mathlib
6827120e88d75b06aef37a5b86b7fb943f13c9e2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/LE.lean
cecf470432f5f4245122c35fe5f21f3bc01dea54
[ "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
100
lean
inductive LE' : Nat → Nat → Prop where | refl (n : Nat) : LE' n n #check LE'.refl #print LE'
dd022899e17728e028ecbe6f3e13685e20a08e4d
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_1310.lean
773f48faab16832de92a21533dbe59dba65a6a16
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
126
lean
import data.real.basic import tactic example (a : ℝ) : 0 ≤ a^2 := begin -- library_search, exact pow_two_nonneg a end
1776aac34d75654c53baa085c899dd7302dbff09
2914802b4ed2844bcc7ef2a02cda40ec82fb975f
/hott/algebra/category/nat_trans.hlean
3b144836732c4e65af860db3ad85031a787f265b
[ "Apache-2.0" ]
permissive
UlrikBuchholtz/lean
60a81367f049cddb37083d3fe3e6fd2f96b7d5e7
cc70845332e63a1f1be21dc1f96d17269fc85909
refs/heads/master
1,586,129,615,121
1,467,727,039,000
1,468,085,570,000
30,432,484
0
0
null
1,423,255,902,000
1,423,255,902,000
null
UTF-8
Lean
false
false
7,489
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Jakob von Raumer -/ import .functor.basic open eq category functor is_trunc equiv sigma.ops sigma is_equiv function pi funext iso structure nat_trans {C : Precategory} {D : Precategory} (F G : C ⇒ D) : Type := (natural_map : Π (a : C), hom (F a) (G a)) (naturality : Π {a b : C} (f : hom a b), G f ∘ natural_map a = natural_map b ∘ F f) namespace nat_trans infixl ` ⟹ `:25 := nat_trans -- \==> variables {B C D E : Precategory} {F G H I : C ⇒ D} {F' G' : D ⇒ E} {F'' G'' : E ⇒ B} {J : C ⇒ C} attribute natural_map [coercion] protected definition compose [constructor] (η : G ⟹ H) (θ : F ⟹ G) : F ⟹ H := nat_trans.mk (λ a, η a ∘ θ a) (λ a b f, abstract calc H f ∘ (η a ∘ θ a) = (H f ∘ η a) ∘ θ a : by rewrite assoc ... = (η b ∘ G f) ∘ θ a : by rewrite naturality ... = η b ∘ (G f ∘ θ a) : by rewrite assoc ... = η b ∘ (θ b ∘ F f) : by rewrite naturality ... = (η b ∘ θ b) ∘ F f : by rewrite assoc end) infixr ` ∘n `:60 := nat_trans.compose definition compose_def (η : G ⟹ H) (θ : F ⟹ G) (c : C) : (η ∘n θ) c = η c ∘ θ c := idp protected definition id [reducible] [constructor] {F : C ⇒ D} : nat_trans F F := mk (λa, id) (λa b f, !id_right ⬝ !id_left⁻¹) protected definition ID [reducible] [constructor] (F : C ⇒ D) : nat_trans F F := (@nat_trans.id C D F) notation 1 := nat_trans.id definition constant_nat_trans [constructor] (C : Precategory) {D : Precategory} {d d' : D} (g : d ⟶ d') : constant_functor C d ⟹ constant_functor C d' := mk (λc, g) (λc c' f, !id_comp_eq_comp_id) definition nat_trans_mk_eq {η₁ η₂ : Π (a : C), hom (F a) (G a)} (nat₁ : Π (a b : C) (f : hom a b), G f ∘ η₁ a = η₁ b ∘ F f) (nat₂ : Π (a b : C) (f : hom a b), G f ∘ η₂ a = η₂ b ∘ F f) (p : η₁ ~ η₂) : nat_trans.mk η₁ nat₁ = nat_trans.mk η₂ nat₂ := apd011 nat_trans.mk (eq_of_homotopy p) !is_prop.elimo definition nat_trans_eq {η₁ η₂ : F ⟹ G} : natural_map η₁ ~ natural_map η₂ → η₁ = η₂ := by induction η₁; induction η₂; apply nat_trans_mk_eq protected definition assoc (η₃ : H ⟹ I) (η₂ : G ⟹ H) (η₁ : F ⟹ G) : η₃ ∘n (η₂ ∘n η₁) = (η₃ ∘n η₂) ∘n η₁ := nat_trans_eq (λa, !assoc) protected definition id_left (η : F ⟹ G) : 1 ∘n η = η := nat_trans_eq (λa, !id_left) protected definition id_right (η : F ⟹ G) : η ∘n 1 = η := nat_trans_eq (λa, !id_right) protected definition sigma_char (F G : C ⇒ D) : (Σ (η : Π (a : C), hom (F a) (G a)), Π (a b : C) (f : hom a b), G f ∘ η a = η b ∘ F f) ≃ (F ⟹ G) := begin fapply equiv.mk, -- TODO(Leo): investigate why we need to use rexact in the following line {intro S, apply nat_trans.mk, rexact (S.2)}, fapply adjointify, intro H, fapply sigma.mk, intro a, exact (H a), intro a b f, exact (naturality H f), intro η, apply nat_trans_eq, intro a, apply idp, intro S, fapply sigma_eq, { apply eq_of_homotopy, intro a, apply idp}, { apply is_prop.elimo} end definition is_set_nat_trans [instance] : is_set (F ⟹ G) := by apply is_trunc_is_equiv_closed; apply (equiv.to_is_equiv !nat_trans.sigma_char) definition change_natural_map [constructor] (η : F ⟹ G) (f : Π (a : C), F a ⟶ G a) (p : Πa, η a = f a) : F ⟹ G := nat_trans.mk f (λa b g, p a ▸ p b ▸ naturality η g) definition nat_trans_functor_compose [constructor] (η : G ⟹ H) (F : E ⇒ C) : G ∘f F ⟹ H ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_compose [constructor] (F : D ⇒ E) (η : G ⟹ H) : F ∘f G ⟹ F ∘f H := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (H f) ∘ F (η a) = F (H f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ G f) : by rewrite (naturality η f) ... = F (η b) ∘ F (G f) : by rewrite respect_comp) definition nat_trans_id_functor_compose [constructor] (η : J ⟹ 1) (F : E ⇒ C) : J ∘f F ⟹ F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition id_nat_trans_functor_compose [constructor] (η : 1 ⟹ J) (F : E ⇒ C) : F ⟹ J ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_id_compose [constructor] (F : C ⇒ D) (η : J ⟹ 1) : F ∘f J ⟹ F := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F f ∘ F (η a) = F (f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ J f) : by rewrite (naturality η f) ... = F (η b) ∘ F (J f) : by rewrite respect_comp) definition functor_id_nat_trans_compose [constructor] (F : C ⇒ D) (η : 1 ⟹ J) : F ⟹ F ∘f J := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (J f) ∘ F (η a) = F (J f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ f) : by rewrite (naturality η f) ... = F (η b) ∘ F f : by rewrite respect_comp) infixr ` ∘nf ` :62 := nat_trans_functor_compose infixr ` ∘fn ` :62 := functor_nat_trans_compose infixr ` ∘n1f `:62 := nat_trans_id_functor_compose infixr ` ∘1nf `:62 := id_nat_trans_functor_compose infixr ` ∘f1n `:62 := functor_id_nat_trans_compose infixr ` ∘fn1 `:62 := functor_nat_trans_id_compose definition nf_fn_eq_fn_nf_pt (η : F ⟹ G) (θ : F' ⟹ G') (c : C) : (θ (G c)) ∘ (F' (η c)) = (G' (η c)) ∘ (θ (F c)) := (naturality θ (η c))⁻¹ variable (F') definition nf_fn_eq_fn_nf_pt' (η : F ⟹ G) (θ : F'' ⟹ G'') (c : C) : (θ (F' (G c))) ∘ (F'' (F' (η c))) = (G'' (F' (η c))) ∘ (θ (F' (F c))) := (naturality θ (F' (η c)))⁻¹ variable {F'} definition nf_fn_eq_fn_nf (η : F ⟹ G) (θ : F' ⟹ G') : (θ ∘nf G) ∘n (F' ∘fn η) = (G' ∘fn η) ∘n (θ ∘nf F) := nat_trans_eq (λ c, nf_fn_eq_fn_nf_pt η θ c) definition fn_n_distrib (F' : D ⇒ E) (η : G ⟹ H) (θ : F ⟹ G) : F' ∘fn (η ∘n θ) = (F' ∘fn η) ∘n (F' ∘fn θ) := nat_trans_eq (λc, by apply respect_comp) definition n_nf_distrib (η : G ⟹ H) (θ : F ⟹ G) (F' : B ⇒ C) : (η ∘n θ) ∘nf F' = (η ∘nf F') ∘n (θ ∘nf F') := nat_trans_eq (λc, idp) definition fn_id (F' : D ⇒ E) : F' ∘fn nat_trans.ID F = 1 := nat_trans_eq (λc, by apply respect_id) definition id_nf (F' : B ⇒ C) : nat_trans.ID F ∘nf F' = 1 := nat_trans_eq (λc, idp) definition id_fn (η : G ⟹ H) (c : C) : (1 ∘fn η) c = η c := idp definition nf_id (η : G ⟹ H) (c : C) : (η ∘nf 1) c = η c := idp definition nat_trans_of_eq [reducible] [constructor] (p : F = G) : F ⟹ G := nat_trans.mk (λc, hom_of_eq (ap010 to_fun_ob p c)) (λa b f, eq.rec_on p (!id_right ⬝ !id_left⁻¹)) definition compose_rev [unfold_full] (θ : F ⟹ G) (η : G ⟹ H) : F ⟹ H := η ∘n θ end nat_trans attribute nat_trans.compose_rev [trans] attribute nat_trans.id [refl]
82c7350f34837dbab58377ed3109745cca31f537
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/newfrontend2.lean
8ded42cfd48cc73c06e9e09a9adcbe7e2b8e6a68
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
467
lean
new_frontend def foo {α} (a : Option α) (b : α) : α := match a with | some a => a | none => b structure S := (x : Nat) #check if 0 == 1 then true else false def f (x : Nat) : Nat := if x < 5 then x+1 else x-1 def x := 1 #check foo x x #check match 1 with x => x + 1 #check match 1 : Int with x => x + 1 #check match 1 with | x => x + 1 #check match 1 : Int with | x => x + 1 def g (x : Nat × Nat) (y : Nat) := x.1 + x.2 + y #check (g ⟨·, 1⟩ ·)
83a4fb7cc83aaac8d28b78dec0f65a31482bc9bc
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/data/real/ennreal.lean
0b44b6da27e78dd6647001a01f332c482cd71ade
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,557
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, Yury Kudryashov -/ import data.real.nnreal import data.set.intervals /-! # Extended non-negative reals We define `ennreal = ℝ≥0∞ := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ℝ≥0∞` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ℝ≥0∞` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ nnreal.of_real` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0∞`: the type of the extended nonnegative real numbers; * `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ℝ≥0∞` for `⊤ : ℝ≥0∞`. -/ noncomputable theory open classical set open_locale classical big_operators nnreal variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered, derive nontrivial] def ennreal := with_top ℝ≥0 localized "notation `ℝ≥0∞` := ennreal" in ennreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} instance : inhabited ℝ≥0∞ := ⟨0⟩ instance : has_coe ℝ≥0 ℝ≥0∞ := ⟨ option.some ⟩ instance : can_lift ℝ≥0∞ ℝ≥0 := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ℝ≥0∞) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ℝ≥0∞ → ℝ≥0 | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ℝ≥0∞) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ℝ≥0∞ := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ℝ≥0∞).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ℝ≥0∞}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ℝ≥0∞} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ℝ≥0∞}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ℝ≥0∞ _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) := rfl @[simp] lemma to_real_nonneg {a : ℝ≥0∞} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ℝ≥0∞).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ℝ≥0∞).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (r : ℝ≥0∞).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ℝ≥0∞).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ℝ≥0∞).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ℝ≥0∞) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ℝ≥0∞} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ℝ≥0∞ → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none lemma to_nnreal_eq_zero_iff (x : ℝ≥0∞) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:ℝ≥0) = (0:ℝ≥0∞) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ℝ≥0∞) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ℝ≥0∞) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ℝ≥0∞) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ℝ≥0∞) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : ℝ≥0 → ℝ≥0∞) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ℝ≥0∞) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ℝ≥0∞) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ℝ≥0∞) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ℝ≥0∞) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ℝ≥0∞) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ℝ≥0∞) = bit1 r := by simp [bit1] lemma coe_two : ((2:ℝ≥0) : ℝ≥0∞) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ℝ≥0∞) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1 : ℝ≥0∞) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _) @[simp] lemma zero_lt_two : (0:ℝ≥0∞) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ℝ≥0∞) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ℝ≥0∞) ≠ ∞ := coe_two ▸ coe_ne_top /-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ℝ≥0∞ → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ℝ≥0∞ → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top (order_dual α) _ _ lemma supr_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top (order_dual α) _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal (order_dual α) _ _ @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ℝ≥0∞` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞ := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ≥0∞) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ℝ≥0∞).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ℝ≥0∞) = r^n := of_nnreal_hom.map_pow r n @[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top @[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ℝ≥0∞} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ℝ≥0∞ _ _ ∞, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ℝ≥0∞} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ := with_top.mul_lt_top lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ℝ≥0∞} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] } end lemma mul_self_lt_top_iff {a : ℝ≥0∞} : a * a < ⊤ ↔ a < ⊤ := by { rw [ennreal.mul_lt_top_iff, and_self, or_self, or_iff_left_iff_imp], rintro rfl, norm_num } @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ℝ≥0∞) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ℝ≥0∞) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ℝ≥0∞) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ℝ≥0∞) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ℝ≥0∞) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n := with_top.coe_nat n @[simp] lemma of_real_coe_nat (n : ℕ) : ennreal.of_real n = n := by simp [ennreal.of_real] @[simp] lemma nat_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : ℕ) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ℝ≥0∞)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [nonpos_iff_eq_zero.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [pos_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ∞ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ∞ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ∞) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_pos_le_add : ∀{a b : ℝ≥0∞}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_pos_le_add h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ℝ≥0∞) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases exists_between h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ℝ≥0∞) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : ℝ≥0 := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ℝ≥0∞) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[simp, norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ℝ≥0∞) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ℝ≥0∞) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ℝ≥0∞) := λ _ _, coe_nat_lt_coe_nat.2 @[simp, norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ℝ≥0∞) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ℝ≥0∞ := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃n:ℕ, r < n := begin lift r to ℝ≥0 using h, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin lift a to ℝ≥0 using ne_top_of_lt ac, lift b to ℝ≥0 using ne_top_of_lt bd, cases c, { simp }, cases d, { simp }, simp only [← coe_add, some_eq_coe, coe_lt_coe] at *, exact add_lt_add ac bd end @[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ℝ≥0∞) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ℝ≥0∞) = max r p := coe_mono.map_max lemma le_of_top_imp_top_of_to_nnreal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) : a ≤ b := begin by_cases ha : a = ⊤, { rw h ha, exact le_top, }, by_cases hb : b = ⊤, { rw hb, exact le_top, }, rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe], exact h_nnreal ha hb, end end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ℝ≥0∞) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ℝ≥0∞) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ℝ≥0∞} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ℝ≥0∞) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} end complete_lattice section mul @[mono] lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul @[mono] lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := begin rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩, lift a to ℝ≥0 using ne_top_of_lt aa', rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩, lift b to ℝ≥0 using ne_top_of_lt bb', norm_cast at *, calc ↑(a * b) < ↑(a' * b') : coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa')) ... = ↑a' * ↑b' : coe_mul ... ≤ c * d : mul_le_mul a'c.le b'd.le end lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (pos_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section sub instance : has_sub ℝ≥0∞ := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ℝ≥0∞) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ℝ≥0∞) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ℝ≥0∞}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ℝ≥0∞}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, Inf_le h) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, pos_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact pos_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ℝ≥0∞) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a) @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ℝ≥0∞} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top {s : finset α} {f : α → ℝ≥0∞} (h : ∀a∈s, f a < ∞) : (∏ a in s, f a) < ∞ := with_top.prod_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ℝ≥0∞} : (∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ℝ≥0∞} : ∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ℝ≥0∞} : (∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) := with_top.sum_eq_top_iff /-- seeing `ℝ≥0∞` as `ℝ≥0` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a < ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ℝ≥0∞` as `real` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a < ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } lemma of_real_sum_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∑ i in s, f i) = ∑ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_sum, coe_eq_coe], exact nnreal.of_real_sum_of_nonneg hf, end end sum section interval variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ℝ≥0∞ := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : div_inv_monoid ℝ≥0∞ := { inv := has_inv.inv, .. (infer_instance : monoid ℝ≥0∞) } @[simp] lemma inv_zero : (0 : ℝ≥0∞)⁻¹ = ∞ := show Inf {b : ℝ≥0∞ | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ℝ≥0∞) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ℝ≥0∞) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, inv_zero, coe_zero, le_top] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ℝ≥0∞) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ℝ≥0∞) = p / r := by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ℝ≥0∞)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 inv_one @[simp] lemma div_one {a : ℝ≥0∞} : a / 1 = a := by rw [div_eq_mul_inv, inv_one, mul_one] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv (pow_ne_zero _ h), ← inv_pow', coe_pow] end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ℝ≥0∞, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ℝ≥0∞, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ℝ≥0∞} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] } lemma div_lt_top {x y : ℝ≥0∞} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ := mul_lt_top h1 (inv_lt_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := pos_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [pos_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_le_one : a⁻¹ ≤ 1 ↔ 1 ≤ a := inv_le_iff_inv_le.trans $ by rw inv_one lemma one_le_inv : 1 ≤ a⁻¹ ↔ a ≤ 1 := le_inv_iff_le_inv.trans $ by rw inv_one @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] lemma pow_le_pow_of_le_one {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n := begin rw [← @inv_inv a, ← ennreal.inv_pow, ← @ennreal.inv_pow a⁻¹, inv_le_inv], exact pow_le_pow (one_le_inv.2 ha) h end @[simp] lemma div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_eq_mul_inv, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [div_eq_mul_inv, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ℝ≥0∞) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_eq_mul_inv, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_eq_mul_inv], refine (le_div_iff_mul_le _ _).symm; simpa end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_eq_mul_inv, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 using ht, norm_cast at *, exact mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ℝ≥0∞} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y := begin refine le_of_forall_ge_of_dense (λ r hr, _), lift r to ℝ≥0 using ne_top_of_lt hr, exact h r hr end lemma eq_top_of_forall_nnreal_le {x : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r ≤ x) : x = ∞ := top_unique $ le_of_forall_nnreal_lt $ λ r hr, h r lemma div_add_div_same {a b c : ℝ≥0∞} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_eq_mul_inv, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma mul_div_le : a * (b / a) ≤ b := begin by_cases h0 : a = 0, { simp [h0] }, by_cases hI : a = ∞, { simp [hI] }, rw mul_div_cancel' h0 hI, exact le_refl b end lemma inv_two_add_inv_two : (2:ℝ≥0∞)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_eq_mul_inv, div_self two_ne_zero two_ne_top] lemma add_halves (a : ℝ≥0∞) : a / 2 + a / 2 = a := by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_eq_mul_inv] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [pos_iff_ne_zero, not_or_distrib] lemma half_pos {a : ℝ≥0∞} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ℝ≥0∞) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ℝ≥0∞} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := begin lift a to ℝ≥0 using ht, have h : (2 : ℝ≥0∞) = ((2 : ℝ≥0) : ℝ≥0∞), from rfl, have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ℝ≥0∞) - 2⁻¹ = 2⁻¹ := by simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ℝ≥0∞} (h : a ≠ 0) : ∃n:ℕ, (n:ℝ≥0∞)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ℝ≥0∞), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ℝ≥0∞)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ℝ≥0∞) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end lemma exists_inv_two_pow_lt (ha : a ≠ 0) : ∃ n : ℕ, 2⁻¹ ^ n < a := begin rcases exists_inv_nat_lt ha with ⟨n, hn⟩, simp only [← ennreal.inv_pow], refine ⟨n, lt_trans (inv_lt_inv.2 _) hn⟩, norm_cast, exact n.lt_two_pow end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 nnreal.of_real_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] lemma of_real_le_of_le_to_real {a : ℝ} {b : ℝ≥0∞} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ℝ≥0∞} (hb : b ≠ ∞) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ℝ≥0∞} (ha : 0 ≤ a) (hb : b ≠ ∞) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ℝ≥0∞} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) : (ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ := by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (nnreal.of_real x) (by simp [hx]), coe_eq_coe, nnreal.of_real_inv.symm] lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) : ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y := by rw [div_eq_inv_mul, div_eq_mul_inv, of_real_mul (inv_nonneg.2 hy.le), of_real_inv_of_pos hy, mul_comm] lemma to_real_of_real_mul (c : ℝ) (a : ℝ≥0∞) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_nnreal_mul_top (a : ℝ≥0∞) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ℝ≥0∞) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ℝ≥0∞) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[simp] lemma to_real_top_mul (a : ℝ≥0∞) : ennreal.to_real (∞ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a < ∞) (hb : b < ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha.ne, lift b to ℝ≥0 using hb.ne, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ℝ≥0∞ →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } lemma to_nnreal_mul {a b : ℝ≥0∞}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal := to_nnreal_hom.map_mul a b lemma to_nnreal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n := to_nnreal_hom.map_pow a n lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal := to_nnreal_hom.map_prod _ _ /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ℝ≥0∞ →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ lemma of_real_prod_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∏ i in s, f i) = ∏ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_prod, coe_eq_coe], exact nnreal.of_real_prod_of_nonneg hf, end @[simp] lemma to_nnreal_bit0 {x : ℝ≥0∞} : (bit0 x).to_nnreal = bit0 (x.to_nnreal) := begin by_cases hx_top : x = ∞, { simp [hx_top, bit0_eq_top_iff.mpr rfl], }, exact to_nnreal_add (lt_top_iff_ne_top.mpr hx_top) (lt_top_iff_ne_top.mpr hx_top), end @[simp] lemma to_nnreal_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).to_nnreal = bit1 (x.to_nnreal) := by simp [bit1, bit1, to_nnreal_add (lt_top_iff_ne_top.mpr (by rwa [ne.def, bit0_eq_top_iff])) ennreal.one_lt_top] @[simp] lemma to_real_bit0 {x : ℝ≥0∞} : (bit0 x).to_real = bit0 (x.to_real) := by simp [ennreal.to_real] @[simp] lemma to_real_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).to_real = bit1 (x.to_real) := by simp [ennreal.to_real, hx_top] @[simp] lemma of_real_bit0 {r : ℝ} (hr : 0 ≤ r) : ennreal.of_real (bit0 r) = bit0 (ennreal.of_real r) := of_real_add hr hr @[simp] lemma of_real_bit1 {r : ℝ} (hr : 0 ≤ r) : ennreal.of_real (bit1 r) = bit1 (ennreal.of_real r) := (of_real_add (by simp [hr]) zero_le_one).trans (by simp [nnreal.of_real_one, bit1, hr]) end real section infi variables {ι : Sort*} {f g : ι → ℝ≥0∞} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ℝ≥0∞} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ℝ≥0∞} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ℝ≥0∞} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr @[simp] lemma supr_eq_zero {ι : Sort*} {f : ι → ℝ≥0∞} : (⨆ i, f i) = 0 ↔ ∀ i, f i = 0 := supr_eq_bot lemma sup_eq_zero {a b : ℝ≥0∞} : a ⊔ b = 0 ↔ a = 0 ∧ b = 0 := sup_eq_bot_iff lemma supr_coe_nat : (⨆n:ℕ, (n : ℝ≥0∞)) = ∞ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ℝ≥0∞` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_left {a b c : ℝ≥0∞} : a < ∞ → a + b ≤ a + c → b ≤ c := by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe] /-- `le_of_add_le_add_right` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ℝ≥0∞` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_right {a b c : ℝ≥0∞} : a < ∞ → b + a ≤ c + a → b ≤ c := by simpa only [add_comm _ a] using le_of_add_le_add_left end ennreal
bd7431187ce651f4b8bf9c4969e565e088945539
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/3.3/x33_library.lean
d53515252e95d3f0e87dc3958d1875de99ae2251
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
6,180
lean
/- Library 3.3: Programming Semantics — Denotational Semantics -/ /- This file contains some basic material for the Hoare logic lecture, exercise, and homework. This file contains the following concepts: * `state`: representing the state space of an imperative program (defined as `string → ℕ`) * `∅` is the empty state; mapping every variable to `0` * `s.update n v` or `s & n ::= v`: replace the name `n` in the state `s` by value `v` * `s n` variable `n` of state `s` * `program` syntax for WHILE programs over `state` as state space. This is a slight modification of the lecture 3.1. Instead of over an arbitrary state space `σ` we are now fixed on `state`; and also `assign` only allows changing one variable. * `(p, s) ⟹ t`: big-step semantics over `program` It is all under the `lecture` namespace. -/ universes u attribute [pattern] or.intro_left or.intro_right meta def tactic.dec_trivial := `[exact dec_trivial] @[simp] lemma not_not_iff (p : Prop) [decidable p] : ¬ (¬ p) ↔ p := by by_cases p; simp [h] @[simp] lemma and_imp (p q r : Prop) : ((p ∧ q) → r) ↔ (p → q → r) := iff.intro (assume h hp hq, h ⟨hp, hq⟩) (assume h ⟨hp, hq⟩, h hp hq) @[simp] lemma exists_false_iff {α : Sort u} : (∃a:α, false) ↔ false := iff.intro (assume ⟨a, h⟩, h) (assume h, h.elim) @[simp] lemma mem_set_of {α : Type} (p : α → Prop) (a : α) : a ∈ {a | p a} ↔ p a := by refl @[simp] lemma mem_union {α : Type} (s t : set α) (a : α) : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := by refl namespace lecture /- `state` to represent state spaces -/ def state := string → ℕ def state.update (name : string) (val : ℕ) (s : state) : state := λn, if n = name then val else s n notation s ` & ` n ` ::= ` v := state.update n v s namespace state instance : has_emptyc state := ⟨λ_, 0⟩ @[simp] lemma update_apply (name : string) (val : ℕ) (s : state) : (s & name ::= val) name = val := if_pos rfl @[simp] lemma update_apply_ne (name name' : string) (val : ℕ) (s : state) (h : name' ≠ name . tactic.dec_trivial): (s & name ::= val) name' = s name' := if_neg h @[simp] lemma update_override (name : string) (val₁ val₂ : ℕ) (s : state) : (s & name ::= val₂ & name ::= val₁) = (s & name ::= val₁) := by funext name'; by_cases name' = name; simp [h] @[simp] lemma update_swap (name₁ name₂ : string) (val₁ val₂ : ℕ) (s : state) (h : name₁ ≠ name₂ . tactic.dec_trivial): (s & name₂ ::= val₂ & name₁ ::= val₁) = (s & name₁ ::= val₁ & name₂ ::= val₂) := by funext name'; by_cases h₁ : name' = name₁; by_cases h₂ : name' = name₂; simp * at * end state example (s : state) : (s & "a" ::= 0 & "a" ::= 2) = (s & "a" ::= 2) := by simp example (s : state) : (s & "a" ::= 0 & "b" ::= 2) = (s & "b" ::= 2 & "a" ::= 0) := by simp /- A WHILE programming language -/ inductive program : Type | skip {} : program | assign : string → (state → ℕ) → program | seq : program → program → program | ite : (state → Prop) → program → program → program | while : (state → Prop) → program → program infixr ` ;; `:90 := program.seq open program /- We use the **big step** semantics -/ inductive big_step : (program × state) → state → Prop | skip {s} : big_step (skip, s) s | assign {n f s} : big_step (assign n f, s) (s.update n (f s)) | seq {p₁ p₂ s u} (t) (h₁ : big_step (p₁, s) t) (h₂ : big_step (p₂, t) u) : big_step (seq p₁ p₂, s) u | ite_true {c : state → Prop} {p₁ p₀ s t} (hs : c s) (h : big_step (p₁, s) t) : big_step (ite c p₁ p₀, s) t | ite_false {c : state → Prop} {p₁ p₀ s t} (hs : ¬ c s) (h : big_step (p₀, s) t) : big_step (ite c p₁ p₀, s) t | while_true {c : state → Prop} {p s u} (t) (hs : c s) (hp : big_step (p, s) t) (hw : big_step (while c p, t) u) : big_step (while c p, s) u | while_false {c : state → Prop} {p s} (hs : ¬ c s) : big_step (while c p, s) s infix ` ⟹ `:110 := big_step section inversion_rules variables (s t : state) (n : string) (p p₀ p₁ p₂ : program) (c : state → Prop) (f : state → ℕ) @[simp] lemma big_step_skip_iff : (skip, s) ⟹ t ↔ t = s := iff.intro (assume h, match t, h with _, big_step.skip := by refl end) (assume h, match t, h with _, rfl := big_step.skip end) @[simp] lemma big_step_assign_iff : (assign n f, s) ⟹ t ↔ t = s.update n (f s) := iff.intro (assume h, match t, h with _, big_step.assign := rfl end) (assume h, match t, h with _, rfl := big_step.assign end) @[simp] lemma big_step_seq_iff : (seq p₁ p₂, s) ⟹ t ↔ (∃u, (p₁, s) ⟹ u ∧ (p₂, u) ⟹ t) := iff.intro (assume h, match h with big_step.seq u h₁ h₂ := ⟨u, h₁, h₂⟩ end) (assume h, match h with ⟨u, h₁, h₂⟩ := big_step.seq u h₁ h₂ end) @[simp] lemma big_step_ite_iff : (ite c p₁ p₀, s) ⟹ t ↔ ((c s ∧ (p₁, s) ⟹ t) ∨ (¬ c s ∧ (p₀, s) ⟹ t)) := iff.intro (assume h, match h with | big_step.ite_true hs h := or.intro_left _ ⟨hs, h⟩ | big_step.ite_false hs h := or.intro_right _ ⟨hs, h⟩ end) (assume h, match h with | or.intro_left _ ⟨hs, h⟩ := big_step.ite_true hs h | or.intro_right _ ⟨hs, h⟩ := big_step.ite_false hs h end) lemma big_step_while_iff : (while c p, s) ⟹ t ↔ (∃u, c s ∧ (p, s) ⟹ u ∧ (while c p, u) ⟹ t) ∨ (¬ c s ∧ t = s) := iff.intro (assume h, match t, h with | t, big_step.while_true u hs h₁ h₂ := or.intro_left _ ⟨u, hs, h₁, h₂⟩ | s, big_step.while_false hs := or.intro_right _ ⟨hs, rfl⟩ end) (assume h, match t, h with | _, or.intro_left _ ⟨u, hs, h₁, h₂⟩ := big_step.while_true u hs h₁ h₂ | _, or.intro_right _ ⟨hs, rfl⟩ := big_step.while_false hs end) @[simp] lemma big_step_while_true_iff (hs : c s) : (while c p, s) ⟹ t ↔ (∃u, (p, s) ⟹ u ∧ (while c p, u) ⟹ t) := by rw [big_step_while_iff]; simp [hs] @[simp] lemma big_step_while_false_iff (hs : ¬ c s) : (while c p, s) ⟹ t ↔ t = s := by rw [big_step_while_iff]; simp [hs] end inversion_rules end lecture
cbc4f8af246c02d10f228bb84b0124abe87790ca
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/erased.lean
6c197646fc5330e16923aeaa2053de132219b74d
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
2,139
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A type for VM-erased data. -/ import data.set.basic data.equiv.basic /-- `erased α` is the same as `α`, except that the elements of `erased α` are erased in the VM in the same way as types and proofs. This can be used to track data without storing it literally. -/ def erased (α : Sort*) : Sort* := Σ' s : α → Prop, ∃ a, (λ b, a = b) = s namespace erased @[inline] def mk {α} (a : α) : erased α := ⟨λ b, a = b, a, rfl⟩ noncomputable def out {α} : erased α → α | ⟨s, h⟩ := classical.some h @[reducible] def out_type (a : erased Sort*) : Sort* := out a theorem out_proof {p : Prop} (a : erased p) : p := out a @[simp] theorem out_mk {α} (a : α) : (mk a).out = a := begin let h, show classical.some h = a, have := classical.some_spec h, exact cast (congr_fun this a).symm rfl end @[simp] theorem mk_out {α} : ∀ (a : erased α), mk (out a) = a | ⟨s, h⟩ := by simp [mk]; congr; exact classical.some_spec h noncomputable def equiv (α) : erased α ≃ α := ⟨out, mk, mk_out, out_mk⟩ instance (α : Type*) : has_repr (erased α) := ⟨λ _, "erased"⟩ def choice {α} (h : nonempty α) : erased α := mk (classical.choice h) theorem nonempty_iff {α} : nonempty (erased α) ↔ nonempty α := ⟨λ ⟨a⟩, ⟨a.out⟩, λ ⟨a⟩, ⟨mk a⟩⟩ instance {α} [h : nonempty α] : nonempty (erased α) := erased.nonempty_iff.2 h instance {α} [h : inhabited α] : inhabited (erased α) := ⟨mk (default _)⟩ def bind {α β} (a : erased α) (f : α → erased β) : erased β := ⟨λ b, (f a.out).1 b, (f a.out).2⟩ @[simp] theorem bind_eq_out {α β} (a f) : @bind α β a f = f a.out := by delta bind bind._proof_1; cases f a.out; refl def join {α} (a : erased (erased α)) : erased α := bind a id @[simp] theorem join_eq_out {α} (a) : @join α a = a.out := bind_eq_out _ _ instance : monad erased := { pure := @mk, bind := @bind } instance : is_lawful_monad erased := by refine {..}; intros; simp end erased
8e7ce434a4042cfd5e5535a7649566e54ecd2645
39ef80a23ca45a679ce3047fabd002248e3ee410
/src/real-analysis/06_sub_sequences.lean
a8c09889b88737b913265b61fc35af0c126e548c
[ "MIT" ]
permissive
sanjitdp/lean-projects
5baa4d97f38b0d5af41e4960dc69ecc7c65a1e4c
05b9a58e8bda3baebd4269536db39815a73cb123
refs/heads/main
1,690,059,014,811
1,630,696,075,000
1,630,696,075,000
399,831,128
0
1
null
null
null
null
UTF-8
Lean
false
false
3,271
lean
import tuto_lib /- This file continues the elementary study of limits of sequences. It can be skipped if the previous file was too easy, it won't introduce any new tactic or trick. Remember useful lemmas: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub_comm (x y : ℝ) : |x - y| = |y - x| ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q and the definition: def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε You can also use a property proved in the previous file: unique_limit : seq_limit u l → seq_limit u l' → l = l' def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m -/ variable { φ : ℕ → ℕ} /- The next lemma is proved by an easy induction, but we haven't seen induction in this tutorial. If you did the natural number game then you can delete the proof below and try to reconstruct it. -/ /-- An extraction is greater than id -/ lemma id_le_extraction' : extraction φ → ∀ n, n ≤ φ n := begin intros hyp n, induction n with n hn, { exact nat.zero_le _ }, { exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) }, end /-- Extractions take arbitrarily large values for arbitrarily large inputs. -/ -- 0039 lemma extraction_ge : extraction φ → ∀ N N', ∃ n ≥ N', φ n ≥ N := begin sorry end /-- A real number `a` is a cluster point of a sequence `u` if `u` has a subsequence converging to `a`. def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a -/ variables {u : ℕ → ℝ} {a l : ℝ} /- In the exercise, we use `∃ n ≥ N, ...` which is the abbreviation of `∃ n, n ≥ N ∧ ...`. Lean can read this abbreviation, but displays it as the confusing: `∃ (n : ℕ) (H : n ≥ N)` One gets used to it. Alternatively, one can get rid of it using the lemma exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q -/ /-- If `a` is a cluster point of `u` then there are values of `u` arbitrarily close to `a` for arbitrarily large input. -/ -- 0040 lemma near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε := begin sorry end /- The above exercice can be done in five lines. Hint: you can use the anonymous constructor syntax when proving existential statements. -/ /-- If `u` tends to `l` then its subsequences tend to `l`. -/ -- 0041 lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin sorry end /-- If `u` tends to `l` all its cluster points are equal to `l`. -/ -- 0042 lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l := begin sorry end /-- Cauchy_sequence sequence -/ def cauchy_sequence (u : ℕ → ℝ) := ∀ ε > 0, ∃ N, ∀ p q, p ≥ N → q ≥ N → |u p - u q| ≤ ε -- 0043 example : (∃ l, seq_limit u l) → cauchy_sequence u := begin sorry end /- In the next exercise, you can reuse near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε -/ -- 0044 example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l := begin sorry end
ef1a9d4a72fbf013a9dea8ce4c207c3ae5f17a15
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/discriminant.lean
1d851a10e5461d47cd1d0717a82f75d0507f7036
[ "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
16,461
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.trace import ring_theory.norm import number_theory.number_field.basic /-! # Discriminant of a family of vectors Given an `A`-algebra `B` and `b`, an `ι`-indexed family of elements of `B`, we define the *discriminant* of `b` as the determinant of the matrix whose `(i j)`-th element is the trace of `b i * b j`. ## Main definition * `algebra.discr A b` : the discriminant of `b : ι → B`. ## Main results * `algebra.discr_zero_of_not_linear_independent` : if `b` is not linear independent, then `algebra.discr A b = 0`. * `algebra.discr_of_matrix_vec_mul` and `discr_of_matrix_mul_vec` : formulas relating `algebra.discr A ι b` with `algebra.discr A ((P.map (algebra_map A B)).vec_mul b)` and `algebra.discr A ((P.map (algebra_map A B)).mul_vec b)`. * `algebra.discr_not_zero_of_basis` : over a field, if `b` is a basis, then `algebra.discr K b ≠ 0`. * `algebra.discr_eq_det_embeddings_matrix_reindex_pow_two` : if `L/K` is a field extension and `b : ι → L`, then `discr K b` is the square of the determinant of the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : L →ₐ[K] E` is the embedding in an algebraically closed field `E` corresponding to `j : ι` via a bijection `e : ι ≃ (L →ₐ[K] E)`. * `algebra.discr_of_power_basis_eq_prod` : the discriminant of a power basis. * `discr_is_integral` : if `K` and `L` are fields and `is_scalar_tower R K L`, is `b : ι → L` satisfies ` ∀ i, is_integral R (b i)`, then `is_integral R (discr K b)`. * `discr_mul_is_integral_mem_adjoin` : let `K` be the fraction field of an integrally closed domain `R` and let `L` be a finite separable extension of `K`. Let `B : power_basis K L` be such that `is_integral R B.gen`. Then for all, `z : L` we have `(discr K B.basis) • z ∈ adjoin R ({B.gen} : set L)`. ## Implementation details Our definition works for any `A`-algebra `B`, but note that if `B` is not free as an `A`-module, then `trace A B = 0` by definition, so `discr A b = 0` for any `b`. -/ universes u v w z open_locale matrix big_operators open matrix finite_dimensional fintype polynomial finset intermediate_field namespace algebra variables (A : Type u) {B : Type v} (C : Type z) {ι : Type w} variables [comm_ring A] [comm_ring B] [algebra A B] [comm_ring C] [algebra A C] section discr /-- Given an `A`-algebra `B` and `b`, an `ι`-indexed family of elements of `B`, we define `discr A ι b` as the determinant of `trace_matrix A ι b`. -/ noncomputable def discr (A : Type u) {B : Type v} [comm_ring A] [comm_ring B] [algebra A B] [fintype ι] (b : ι → B) := by { classical, exact (trace_matrix A b).det } lemma discr_def [decidable_eq ι] [fintype ι] (b : ι → B) : discr A b = (trace_matrix A b).det := by convert rfl variables {ι' : Type*} [fintype ι'] [fintype ι] section basic @[simp] lemma discr_reindex (b : basis ι A B) (f : ι ≃ ι') : discr A (b ∘ ⇑(f.symm)) = discr A b := begin classical, rw [← basis.coe_reindex, discr_def, trace_matrix_reindex, det_reindex_self, ← discr_def] end /-- If `b` is not linear independent, then `algebra.discr A b = 0`. -/ lemma discr_zero_of_not_linear_independent [is_domain A] {b : ι → B} (hli : ¬linear_independent A b) : discr A b = 0 := begin classical, obtain ⟨g, hg, i, hi⟩ := fintype.not_linear_independent_iff.1 hli, have : (trace_matrix A b).mul_vec g = 0, { ext i, have : ∀ j, (trace A B) (b i * b j) * g j = (trace A B) (((g j) • (b j)) * b i), { intro j, simp [mul_comm], }, simp only [mul_vec, dot_product, trace_matrix, pi.zero_apply, trace_form_apply, λ j, this j, ← linear_map.map_sum, ← sum_mul, hg, zero_mul, linear_map.map_zero] }, by_contra h, rw discr_def at h, simpa [matrix.eq_zero_of_mul_vec_eq_zero h this] using hi, end variable {A} /-- Relation between `algebra.discr A ι b` and `algebra.discr A ((P.map (algebra_map A B)).vec_mul b)`. -/ lemma discr_of_matrix_vec_mul [decidable_eq ι] (b : ι → B) (P : matrix ι ι A) : discr A ((P.map (algebra_map A B)).vec_mul b) = P.det ^ 2 * discr A b := by rw [discr_def, trace_matrix_of_matrix_vec_mul, det_mul, det_mul, det_transpose, mul_comm, ← mul_assoc, discr_def, pow_two] /-- Relation between `algebra.discr A ι b` and `algebra.discr A ((P.map (algebra_map A B)).mul_vec b)`. -/ lemma discr_of_matrix_mul_vec [decidable_eq ι] (b : ι → B) (P : matrix ι ι A) : discr A ((P.map (algebra_map A B)).mul_vec b) = P.det ^ 2 * discr A b := by rw [discr_def, trace_matrix_of_matrix_mul_vec, det_mul, det_mul, det_transpose, mul_comm, ← mul_assoc, discr_def, pow_two] end basic section field variables (K : Type u) {L : Type v} (E : Type z) [field K] [field L] [field E] variables [algebra K L] [algebra K E] variables [module.finite K L] [is_alg_closed E] /-- Over a field, if `b` is a basis, then `algebra.discr K b ≠ 0`. -/ lemma discr_not_zero_of_basis [is_separable K L] (b : basis ι K L) : discr K b ≠ 0 := begin casesI is_empty_or_nonempty ι, { simp [discr] }, { have := span_eq_top_of_linear_independent_of_card_eq_finrank b.linear_independent (finrank_eq_card_basis b).symm, rw [discr_def, trace_matrix_def], simp_rw [← basis.mk_apply b.linear_independent this.ge], rw [← trace_matrix_def, trace_matrix_of_basis, ← bilin_form.nondegenerate_iff_det_ne_zero], exact trace_form_nondegenerate _ _ }, end /-- Over a field, if `b` is a basis, then `algebra.discr K b` is a unit. -/ lemma discr_is_unit_of_basis [is_separable K L] (b : basis ι K L) : is_unit (discr K b) := is_unit.mk0 _ (discr_not_zero_of_basis _ _) variables (b : ι → L) (pb : power_basis K L) /-- If `L/K` is a field extension and `b : ι → L`, then `discr K b` is the square of the determinant of the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : L →ₐ[K] E` is the embedding in an algebraically closed field `E` corresponding to `j : ι` via a bijection `e : ι ≃ (L →ₐ[K] E)`. -/ lemma discr_eq_det_embeddings_matrix_reindex_pow_two [decidable_eq ι] [is_separable K L] (e : ι ≃ (L →ₐ[K] E)) : algebra_map K E (discr K b) = (embeddings_matrix_reindex K E b e).det ^ 2 := by rw [discr_def, ring_hom.map_det, ring_hom.map_matrix_apply, trace_matrix_eq_embeddings_matrix_reindex_mul_trans, det_mul, det_transpose, pow_two] /-- The discriminant of a power basis. -/ lemma discr_power_basis_eq_prod (e : fin pb.dim ≃ (L →ₐ[K] E)) [is_separable K L] : algebra_map K E (discr K pb.basis) = ∏ i : fin pb.dim, ∏ j in Ioi i, (e j pb.gen- (e i pb.gen)) ^ 2 := begin rw [discr_eq_det_embeddings_matrix_reindex_pow_two K E pb.basis e, embeddings_matrix_reindex_eq_vandermonde, det_transpose, det_vandermonde, ← prod_pow], congr, ext i, rw [← prod_pow] end /-- A variation of `of_power_basis_eq_prod`. -/ lemma discr_power_basis_eq_prod' [is_separable K L] (e : fin pb.dim ≃ (L →ₐ[K] E)) : algebra_map K E (discr K pb.basis) = ∏ i : fin pb.dim, ∏ j in Ioi i, -((e j pb.gen - e i pb.gen) * (e i pb.gen - e j pb.gen)) := begin rw [discr_power_basis_eq_prod _ _ _ e], congr, ext i, congr, ext j, ring end local notation `n` := finrank K L /-- A variation of `of_power_basis_eq_prod`. -/ lemma discr_power_basis_eq_prod'' [is_separable K L] (e : fin pb.dim ≃ (L →ₐ[K] E)) : algebra_map K E (discr K pb.basis) = (-1) ^ (n * (n - 1) / 2) * ∏ i : fin pb.dim, ∏ j in Ioi i, (e j pb.gen - e i pb.gen) * (e i pb.gen - e j pb.gen) := begin rw [discr_power_basis_eq_prod' _ _ _ e], simp_rw [λ i j, neg_eq_neg_one_mul ((e j pb.gen- (e i pb.gen)) * (e i pb.gen- (e j pb.gen))), prod_mul_distrib], congr, simp only [prod_pow_eq_pow_sum, prod_const], congr, rw [← @nat.cast_inj ℚ, nat.cast_sum], have : ∀ (x : fin pb.dim), (↑x + 1) ≤ pb.dim := by simp [nat.succ_le_iff, fin.is_lt], simp_rw [fin.card_Ioi, nat.sub_sub, add_comm 1], simp only [nat.cast_sub, this, finset.card_fin, nsmul_eq_mul, sum_const, sum_sub_distrib, nat.cast_add, nat.cast_one, sum_add_distrib, mul_one], rw [← nat.cast_sum, ← @finset.sum_range ℕ _ pb.dim (λ i, i), sum_range_id ], have hn : n = pb.dim, { rw [← alg_hom.card K L E, ← fintype.card_fin pb.dim], exact card_congr (equiv.symm e) }, have h₂ : 2 ∣ (pb.dim * (pb.dim - 1)) := even_iff_two_dvd.1 (nat.even_mul_self_pred _), have hne : ((2 : ℕ) : ℚ) ≠ 0 := by simp, have hle : 1 ≤ pb.dim, { rw [← hn, nat.one_le_iff_ne_zero, ← zero_lt_iff, finite_dimensional.finrank_pos_iff], apply_instance }, rw [hn, nat.cast_div h₂ hne, nat.cast_mul, nat.cast_sub hle], field_simp, ring, end /-- Formula for the discriminant of a power basis using the norm of the field extension. -/ lemma discr_power_basis_eq_norm [is_separable K L] : discr K pb.basis = (-1) ^ (n * (n - 1) / 2) * (norm K (aeval pb.gen (minpoly K pb.gen).derivative)) := begin let E := algebraic_closure L, letI := λ (a b : E), classical.prop_decidable (eq a b), have e : fin pb.dim ≃ (L →ₐ[K] E), { refine equiv_of_card_eq _, rw [fintype.card_fin, alg_hom.card], exact (power_basis.finrank pb).symm }, have hnodup : (map (algebra_map K E) (minpoly K pb.gen)).roots.nodup := nodup_roots (separable.map (is_separable.separable K pb.gen)), have hroots : ∀ σ : L →ₐ[K] E, σ pb.gen ∈ (map (algebra_map K E) (minpoly K pb.gen)).roots, { intro σ, rw [mem_roots, is_root.def, eval_map, ← aeval_def, aeval_alg_hom_apply], repeat { simp [minpoly.ne_zero (is_separable.is_integral K pb.gen)] } }, apply (algebra_map K E).injective, rw [ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_neg, ring_hom.map_one, discr_power_basis_eq_prod'' _ _ _ e], congr, rw [norm_eq_prod_embeddings, prod_prod_Ioi_mul_eq_prod_prod_off_diag], conv_rhs { congr, skip, funext, rw [← aeval_alg_hom_apply, aeval_root_derivative_of_splits (minpoly.monic (is_separable.is_integral K pb.gen)) (is_alg_closed.splits_codomain _) (hroots σ), ← finset.prod_mk _ (hnodup.erase _)] }, rw [prod_sigma', prod_sigma'], refine prod_bij (λ i hi, ⟨e i.2, e i.1 pb.gen⟩) (λ i hi, _) (λ i hi, by simp at hi) (λ i j hi hj hij, _) (λ σ hσ, _), { simp only [true_and, finset.mem_mk, mem_univ, mem_sigma], rw [multiset.mem_erase_of_ne (λ h, _)], { exact hroots _ }, { simp only [true_and, mem_univ, ne.def, mem_sigma, mem_compl, mem_singleton] at hi, rw [← power_basis.lift_equiv_apply_coe, ← power_basis.lift_equiv_apply_coe] at h, exact hi (e.injective $ pb.lift_equiv.injective $ subtype.eq h.symm) } }, { simp only [equiv.apply_eq_iff_eq, heq_iff_eq] at hij, have h := hij.2, rw [← power_basis.lift_equiv_apply_coe, ← power_basis.lift_equiv_apply_coe] at h, refine sigma.eq (equiv.injective e (equiv.injective _ (subtype.eq h))) (by simp [hij.1]) }, { simp only [true_and, finset.mem_mk, mem_univ, mem_sigma] at ⊢ hσ, simp only [sigma.exists, exists_prop, mem_compl, mem_singleton, ne.def], refine ⟨e.symm (power_basis.lift pb σ.2 _), e.symm σ.1, ⟨λ h, _, sigma.eq _ _⟩⟩, { rw [aeval_def, eval₂_eq_eval_map, ← is_root.def, ← mem_roots], { exact multiset.erase_subset _ _ hσ }, { simp [minpoly.ne_zero (is_separable.is_integral K pb.gen)] } }, { replace h := alg_hom.congr_fun (equiv.injective _ h) pb.gen, rw [power_basis.lift_gen] at h, rw [← h] at hσ, exact hnodup.not_mem_erase hσ }, all_goals { simp } } end section integral variables {R : Type z} [comm_ring R] [algebra R K] [algebra R L] [is_scalar_tower R K L] local notation `is_integral` := _root_.is_integral /-- If `K` and `L` are fields and `is_scalar_tower R K L`, and `b : ι → L` satisfies ` ∀ i, is_integral R (b i)`, then `is_integral R (discr K b)`. -/ lemma discr_is_integral {b : ι → L} (h : ∀ i, is_integral R (b i)) : is_integral R (discr K b) := begin classical, rw [discr_def], exact is_integral.det (λ i j, is_integral_trace (is_integral_mul (h i) (h j))) end /-- If `b` and `b'` are `ℚ`-bases of a number field `K` such that `∀ i j, is_integral ℤ (b.to_matrix b' i j)` and `∀ i j, is_integral ℤ (b'.to_matrix b i j)` then `discr ℚ b = discr ℚ b'`. -/ lemma discr_eq_discr_of_to_matrix_coeff_is_integral [number_field K] {b : basis ι ℚ K} {b' : basis ι' ℚ K} (h : ∀ i j, is_integral ℤ (b.to_matrix b' i j)) (h' : ∀ i j, is_integral ℤ (b'.to_matrix b i j)) : discr ℚ b = discr ℚ b' := begin replace h' : ∀ i j, is_integral ℤ (b'.to_matrix ((b.reindex (b.index_equiv b'))) i j), { intros i j, convert h' i ((b.index_equiv b').symm j), simpa }, classical, rw [← (b.reindex (b.index_equiv b')).to_matrix_map_vec_mul b', discr_of_matrix_vec_mul, ← one_mul (discr ℚ b), basis.coe_reindex, discr_reindex], congr, have hint : is_integral ℤ (((b.reindex (b.index_equiv b')).to_matrix b').det) := is_integral.det (λ i j, h _ _), obtain ⟨r, hr⟩ := is_integrally_closed.is_integral_iff.1 hint, have hunit : is_unit r, { have : is_integral ℤ ((b'.to_matrix (b.reindex (b.index_equiv b'))).det) := is_integral.det (λ i j, h' _ _), obtain ⟨r', hr'⟩ := is_integrally_closed.is_integral_iff.1 this, refine is_unit_iff_exists_inv.2 ⟨r', _⟩, suffices : algebra_map ℤ ℚ (r * r') = 1, { rw [← ring_hom.map_one (algebra_map ℤ ℚ)] at this, exact (is_fraction_ring.injective ℤ ℚ) this }, rw [ring_hom.map_mul, hr, hr', ← det_mul, basis.to_matrix_mul_to_matrix_flip, det_one] }, rw [← ring_hom.map_one (algebra_map ℤ ℚ), ← hr], cases int.is_unit_iff.1 hunit with hp hm, { simp [hp] }, { simp [hm] } end /-- Let `K` be the fraction field of an integrally closed domain `R` and let `L` be a finite separable extension of `K`. Let `B : power_basis K L` be such that `is_integral R B.gen`. Then for all, `z : L` that are integral over `R`, we have `(discr K B.basis) • z ∈ adjoin R ({B.gen} : set L)`. -/ lemma discr_mul_is_integral_mem_adjoin [is_domain R] [is_separable K L] [is_integrally_closed R] [is_fraction_ring R K] {B : power_basis K L} (hint : is_integral R B.gen) {z : L} (hz : is_integral R z) : (discr K B.basis) • z ∈ adjoin R ({B.gen} : set L) := begin have hinv : is_unit (trace_matrix K B.basis).det := by simpa [← discr_def] using discr_is_unit_of_basis _ B.basis, have H : (trace_matrix K B.basis).det • (trace_matrix K B.basis).mul_vec (B.basis.equiv_fun z) = (trace_matrix K B.basis).det • (λ i, trace K L (z * B.basis i)), { congr, exact trace_matrix_of_basis_mul_vec _ _ }, have cramer := mul_vec_cramer (trace_matrix K B.basis) (λ i, trace K L (z * B.basis i)), suffices : ∀ i, ((trace_matrix K B.basis).det • (B.basis.equiv_fun z)) i ∈ (⊥ : subalgebra R K), { rw [← B.basis.sum_repr z, finset.smul_sum], refine subalgebra.sum_mem _ (λ i hi, _), replace this := this i, rw [← discr_def, pi.smul_apply, mem_bot] at this, obtain ⟨r, hr⟩ := this, rw [basis.equiv_fun_apply] at hr, rw [← smul_assoc, ← hr, algebra_map_smul], refine subalgebra.smul_mem _ _ _, rw [B.basis_eq_pow i], refine subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton _)) _}, intro i, rw [← H, ← mul_vec_smul] at cramer, replace cramer := congr_arg (mul_vec (trace_matrix K B.basis)⁻¹) cramer, rw [mul_vec_mul_vec, nonsing_inv_mul _ hinv, mul_vec_mul_vec, nonsing_inv_mul _ hinv, one_mul_vec, one_mul_vec] at cramer, rw [← congr_fun cramer i, cramer_apply, det_apply], refine subalgebra.sum_mem _ (λ σ _, subalgebra.zsmul_mem _ (subalgebra.prod_mem _ (λ j _, _)) _), by_cases hji : j = i, { simp only [update_column_apply, hji, eq_self_iff_true, power_basis.coe_basis], exact mem_bot.2 (is_integrally_closed.is_integral_iff.1 $ is_integral_trace $ is_integral_mul hz $ is_integral.pow hint _) }, { simp only [update_column_apply, hji, power_basis.coe_basis], exact mem_bot.2 (is_integrally_closed.is_integral_iff.1 $ is_integral_trace $ is_integral_mul (is_integral.pow hint _) (is_integral.pow hint _)) } end end integral end field end discr end algebra
6b4ed52eed1974dba8dd7e1ae49998cc89c04e6b
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/playground/uf1.lean
4ae25b2f7e55d6808064cc80799000185ccaaf0b
[ "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
4,655
lean
def StateT (m : Type → Type) (σ : Type) (α : Type) := (Unit × σ) → m (α × σ) namespace StateT variables {m : Type → Type} [Monad m] {σ : Type} {α β : Type} @[inline] protected def pure (a : α) : StateT m σ α := λ ⟨_, s⟩, pure (a, s) @[inline] protected def bind (x : StateT m σ α) (f : α → StateT m σ β) : StateT m σ β := λ p, do (a, s') ← x p, f a ((), s') @[inline] def read : StateT m σ σ := λ ⟨_, s⟩, pure (s, s) @[inline] def write (s' : σ) : StateT m σ Unit := λ ⟨_, s⟩, pure ((), s') @[inline] def updt (f : σ → σ) : StateT m σ Unit := λ ⟨_, s⟩, pure ((), f s) instance : Monad (StateT m σ) := {pure := @StateT.pure _ _ _, bind := @StateT.bind _ _ _} end StateT def ExceptT (m : Type → Type) (ε : Type) (α : Type) := { e : Except ε Unit // e = Except.ok () } → m (Except ε α) namespace ExceptT variables {m : Type → Type} [Monad m] {ε : Type} {α β : Type} @[inline] protected def pure (a : α) : ExceptT m ε α := λ e, match e with | ⟨Except.ok _, h⟩ := pure (Except.ok a) | ⟨Except.error _, h⟩ := Except.noConfusion h @[inline] protected def bind (x : ExceptT m ε α) (f : α → ExceptT m ε β) : ExceptT m ε β := λ e, do v ← x e, match v with | Except.error e := pure (Except.error e) | Except.ok a := f a ⟨Except.ok (), rfl⟩ @[inline] def error (e : ε) : ExceptT m ε α := λ e', match e' with | ⟨Except.ok _, h⟩ := pure (Except.error e) | ⟨Except.error _, h⟩ := Except.noConfusion h @[inline] def lift (x : m α) : ExceptT m ε α := λ e, do {a ← x, pure (Except.ok a)} instance : Monad (ExceptT m ε) := {pure := @ExceptT.pure _ _ _, bind := @ExceptT.bind _ _ _} end ExceptT abbreviation Node := Nat structure nodeData := (find : Node) (rank : Nat := 0) abbreviation ufData := Array nodeData abbreviation M (α : Type) := ExceptT (StateT id ufData) String α @[inline] def read : M ufData := ExceptT.lift StateT.read @[inline] def write (s : ufData) : M Unit := ExceptT.lift (StateT.write s) @[inline] def updt (f : ufData → ufData) : M Unit := ExceptT.lift (StateT.updt f) @[inline] def error {α : Type} (e : String) : M α := ExceptT.error e def run {α : Type} (x : M α) (s : ufData := Array.nil) : Except String α × ufData := x ⟨Except.ok (), rfl⟩ ((), s) def capacity : M Nat := do d ← read, pure d.size def findEntryAux : Nat → Node → M nodeData | 0 n := error "out of fuel" | (i+1) n := do s ← read, if h : n < s.size then do { let e := s.read ⟨n, h⟩, if e.find = n then pure e else do e₁ ← findEntryAux i e.find, updt (λ s, s.write' n e₁), pure e₁ } else error "invalid Node" def findEntry (n : Node) : M nodeData := do c ← capacity, findEntryAux c n def find (n : Node) : M Node := do e ← findEntry n, pure e.find def mk : M Node := do n ← capacity, updt $ λ s, s.push {find := n, rank := 1}, pure n def union (n₁ n₂ : Node) : M Unit := do r₁ ← findEntry n₁, r₂ ← findEntry n₂, if r₁.find = r₂.find then pure () else updt $ λ s, if r₁.rank < r₂.rank then s.write' r₁.find { find := r₂.find } else if r₁.rank = r₂.rank then let s₁ := s.write' r₁.find { find := r₂.find } in s₁.write' r₂.find { rank := r₂.rank + 1, .. r₂} else s.write' r₂.find { find := r₁.find } def mkNodes : Nat → M Unit | 0 := pure () | (n+1) := mk *> mkNodes n def checkEq (n₁ n₂ : Node) : M Unit := do r₁ ← find n₁, r₂ ← find n₂, unless (r₁ = r₂) $ error "nodes are not equal" def mergePackAux : Nat → Nat → Nat → M Unit | 0 _ _ := pure () | (i+1) n d := do c ← capacity, if (n+d) < c then union n (n+d) *> mergePackAux i (n+1) d else pure () def mergePack (d : Nat) : M Unit := do c ← capacity, mergePackAux c 0 d def numEqsAux : Nat → Node → Nat → M Nat | 0 _ r := pure r | (i+1) n r := do c ← capacity, if n < c then do { n₁ ← find n, numEqsAux i (n+1) (if n = n₁ then r else r+1) } else pure r def numEqs : M Nat := do c ← capacity, numEqsAux c 0 0 def test (n : Nat) : M Nat := if n < 2 then error "input must be greater than 1" else do mkNodes n, mergePack 50000, mergePack 10000, mergePack 5000, mergePack 1000, numEqs def main (xs : List String) : IO UInt32 := let n := xs.head.toNat in match run (test n) with | (Except.ok v, s) := IO.println ("ok " ++ toString v) *> pure 0 | (Except.error e, s) := IO.println ("Error : " ++ e) *> pure 1
9fbe04dc6eddf68ae0ed7defbe654abc59437bc7
a46270e2f76a375564f3b3e9c1bf7b635edc1f2c
/10.3.lean
d7eebe86e2c9fa5b69d63d670843887c77defb57
[ "CC0-1.0" ]
permissive
wudcscheme/lean-exercise
88ea2506714eac343de2a294d1132ee8ee6d3a20
5b23b9be3d361fff5e981d5be3a0a1175504b9f6
refs/heads/master
1,678,958,930,293
1,583,197,205,000
1,583,197,205,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
123
lean
instance list_has_add {α : Type*} [has_add α] : has_add (list α) := ⟨list.append⟩ #reduce [0, 2, 4] + [1, 3, 5]
de426f9a278d8a2531fc611ca851ea4b4a909d88
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/ideal/basic.lean
b085195f21f2025a67333f055fe2aa8584d28ddb
[ "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
23,114
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn import order.atoms import order.compactly_generated import tactic.abel import data.nat.choose.sum import linear_algebra.finsupp /-! # Ideals over a ring This file defines `ideal R`, the type of (left) ideals over a ring `R`. Note that over commutative rings, left ideals and two-sided ideals are equivalent. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support right ideals, and two-sided ideals over non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators pointwise /-- A (left) ideal in a semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [semiring R] := submodule R R section semiring namespace ideal variables [semiring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem variables (a) lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem a variables {a} @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h lemma sum_mem (I : ideal α) {ι : Type*} {t : finset ι} {f : ι → α} : (∀c∈t, f c ∈ I) → (∑ i in t, f i) ∈ I := submodule.sum_mem I theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := h.exists_left_inv in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := hy.exists_left_inv, have := I.mul_mem_left y' h, rwa [← mul_assoc, hy', one_mul] at this, end /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s @[simp] lemma submodule_span_eq {s : set α} : submodule.span α s = ideal.span s := rfl @[simp] lemma span_empty : span (∅ : set α) = ⊥ := submodule.span_empty @[simp] lemma span_univ : span (set.univ : set α) = ⊤ := submodule.span_univ lemma span_union (s t : set α) : span (s ∪ t) = span s ⊔ span t := submodule.span_union _ _ lemma span_Union {ι} (s : ι → set α) : span (⋃ i, s i) = ⨆ i, span (s i) := submodule.span_Union _ lemma mem_span {s : set α} (x) : x ∈ span s ↔ ∀ p : ideal α, s ⊆ p → x ∈ p := mem_Inter₂ lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma span_insert (x) (s : set α) : span (insert x s) = span ({x} : set α) ⊔ span s := submodule.span_insert x s lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] @[simp] lemma span_one : span (1 : set α) = ⊤ := by rw [←set.singleton_one, span_singleton_one] lemma span_eq_top_iff_finite (s : set α) : span s = ⊤ ↔ ∃ s' : finset α, ↑s' ⊆ s ∧ span (s' : set α) = ⊤ := begin simp_rw eq_top_iff_one, exact ⟨submodule.mem_span_finite_of_mem_span, λ ⟨s', h₁, h₂⟩, span_mono h₁ h₂⟩ end /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x + b = a } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ class is_prime (I : ideal α) : Prop := (ne_top' : I ≠ ⊤) (mem_or_mem' : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I) theorem is_prime_iff {I : ideal α} : is_prime I ↔ I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ theorem is_prime.ne_top {I : ideal α} (hI : I.is_prime) : I ≠ ⊤ := hI.1 theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.mem_or_mem (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { rw pow_zero at H, exact (mt (eq_top_iff_one _).2 hI.1).elim H }, { rw pow_succ at H, exact or.cases_on (hI.mem_or_mem H) id ih } end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime_iff, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem lemma bot_prime {R : Type*} [ring R] [is_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ class is_maximal (I : ideal α) : Prop := (out : is_coatom I) theorem is_maximal_def {I : ideal α} : I.is_maximal ↔ is_coatom I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_maximal.ne_top {I : ideal α} (h : I.is_maximal) : I ≠ ⊤ := (is_maximal_def.1 h).1 theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := is_maximal_def.trans $ and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.1.2 _ h)⟩ instance : is_coatomic (ideal α) := begin apply complete_lattice.coatomic_of_top_compact, rw ←span_singleton_one, exact submodule.singleton_span_is_compact_element 1, end /-- **Krull's theorem**: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := let ⟨m, hm⟩ := (eq_top_or_exists_le_coatom I).resolve_left hI in ⟨m, ⟨⟨hm.1⟩, hm.2⟩⟩ variables (α) /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) bot_ne_top in ⟨I, hI⟩ variables {α} instance [nontrivial α] : nontrivial (ideal α) := begin rcases @exists_maximal α _ _ with ⟨M, hM, _⟩, exact nontrivial_of_ne M ⊤ hM end /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [semiring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, ∃ i ∈ I, y * x + i = 1 := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, z, hz, hy⟩, refine ⟨y, z, _, hy.symm⟩, rwa ← span_eq I, end section lattice variables {R : Type u} [semiring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Sort*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Sort*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, I.zero_mem, add_mem' := λ a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := λ a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl end pi end ideal end semiring section comm_semiring variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different -- order. namespace ideal variables [comm_semiring α] (I : ideal α) @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [comm_ring α] [is_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime_iff, prime, span_singleton_eq_top, hp, mem_span_singleton] theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin let J : ideal α := submodule.span α (insert x ↑I), have IJ : I ≤ J := (set.subset.trans (subset_insert _ _) subset_span), have xJ : x ∈ J := ideal.subset_span (set.mem_insert x I), cases is_maximal_iff.1 H with _ oJ, specialize oJ J x IJ hx xJ, rcases submodule.mem_span_insert.mp oJ with ⟨a, b, h, oe⟩, obtain (F : y * 1 = y * (a • x + b)) := congr_arg (λ g : α, y * g) oe, rw [← mul_one y, F, mul_add, mul_comm, smul_eq_mul, mul_assoc], refine submodule.add_mem I (I.mul_mem_left a hxy) (submodule.smul_mem I y _), rwa submodule.span_eq at h, end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime lemma span_singleton_lt_span_singleton [comm_ring β] [is_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [comm_ring β] [is_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left b h variables {b} lemma pow_mem_of_mem (ha : a ∈ I) (n : ℕ) (hn : 0 < n) : a ^ n ∈ I := nat.cases_on n (not.elim dec_trivial) (λ m hm, (pow_succ a m).symm ▸ I.mul_mem_right (a^m) ha) hn theorem is_prime.mul_mem_iff_mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I ↔ x ∈ I ∨ y ∈ I := λ x y, ⟨hI.mem_or_mem, by { rintro (h | h), exacts [I.mul_mem_right y h, I.mul_mem_left x h] }⟩ theorem is_prime.pow_mem_iff_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (hn : 0 < n) : r ^ n ∈ I ↔ r ∈ I := ⟨hI.mem_of_pow_mem n, (λ hr, I.pow_mem_of_mem hr n hn)⟩ theorem pow_multiset_sum_mem_span_pow (s : multiset α) (n : ℕ) : s.sum ^ (s.card * n + 1) ∈ span ((s.map (λ x, x ^ (n + 1))).to_finset : set α) := begin induction s using multiset.induction_on with a s hs, { simp }, simp only [finset.coe_insert, multiset.map_cons, multiset.to_finset_cons, multiset.sum_cons, multiset.card_cons, add_pow], refine submodule.sum_mem _ _, intros c hc, rw mem_span_insert, by_cases h : n+1 ≤ c, { refine ⟨a ^ (c - (n + 1)) * s.sum ^ ((s.card + 1) * n + 1 - c) * (((s.card + 1) * n + 1).choose c), 0, submodule.zero_mem _, _⟩, rw mul_comm _ (a ^ (n + 1)), simp_rw ← mul_assoc, rw [← pow_add, add_zero, add_tsub_cancel_of_le h], }, { use 0, simp_rw [zero_mul, zero_add], refine ⟨_,_,rfl⟩, replace h : c ≤ n := nat.lt_succ_iff.mp (not_le.mp h), have : (s.card + 1) * n + 1 - c = s.card * n + 1 + (n - c), { rw [add_mul, one_mul, add_assoc, add_comm n 1, ← add_assoc, add_tsub_assoc_of_le h] }, rw [this, pow_add], simp_rw [mul_assoc, mul_comm (s.sum ^ (s.card * n + 1)), ← mul_assoc], exact mul_mem_left _ _ hs } end theorem sum_pow_mem_span_pow {ι} (s : finset ι) (f : ι → α) (n : ℕ) : (∑ i in s, f i) ^ (s.card * n + 1) ∈ span ((λ i, f i ^ (n + 1)) '' s) := begin convert pow_multiset_sum_mem_span_pow (s.1.map f) n, { rw multiset.card_map, refl }, rw [multiset.map_map, multiset.to_finset_map, finset.val_to_finset, finset.coe_image] end theorem span_pow_eq_top (s : set α) (hs : span s = ⊤) (n : ℕ) : span ((λ x, x ^ n) '' s) = ⊤ := begin rw eq_top_iff_one, cases n, { obtain rfl | ⟨x, hx⟩ := eq_empty_or_nonempty s, { rw [set.image_empty, hs], trivial }, { exact subset_span ⟨_, hx, pow_zero _⟩ } }, rw [eq_top_iff_one, span, finsupp.mem_span_iff_total] at hs, rcases hs with ⟨f, hf⟩, change f.support.sum (λ a, f a * a) = 1 at hf, have := sum_pow_mem_span_pow f.support (λ a, f a * a) n, rw [hf, one_pow] at this, refine (span_le).mpr _ this, rintros _ hx, simp_rw [finset.mem_coe, set.mem_image] at hx, rcases hx with ⟨x, hx, rfl⟩, have : span ({x ^ (n + 1)} : set α) ≤ span ((λ (x : α), x ^ (n + 1)) '' s), { rw [span_le, set.singleton_subset_iff], exact subset_span ⟨x, x.prop, rfl⟩ }, refine this _, rw [mul_pow, mem_span_singleton], exact ⟨f x ^ (n + 1), mul_comm _ _⟩ end end ideal end comm_semiring section ring namespace ideal variables [ring α] (I : ideal α) {a b : α} protected lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := neg_mem_iff protected lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left protected lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := sub_mem lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' end ideal end ring section division_ring variables {K : Type u} [division_ring K] (I : ideal K) namespace ideal /-- All ideals in a division ring are trivial. -/ lemma eq_bot_or_top : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end lemma eq_bot_of_prime [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal : is_maximal (⊥ : ideal K) := ⟨⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩⟩ end ideal end division_ring section comm_ring namespace ideal theorem mul_sub_mul_mem {R : Type*} [comm_ring R] (I : ideal R) {a b c d : R} (h1 : a - b ∈ I) (h2 : c - d ∈ I) : a * c - b * d ∈ I := begin rw (show a * c - b * d = (a - b) * c + b * (c - d), by {rw [sub_mul, mul_sub], abel}), exact I.add_mem (I.mul_mem_right _ h1) (I.mul_mem_left _ h2), end end ideal end comm_ring namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := set_like.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : ¬ is_field R) : M ≠ ⊥ := begin rintros h, rw h at max, rcases max with ⟨⟨h1, h2⟩⟩, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, { simp }, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.1.2 I Ibot at Itop, end end ideal variables {a b : α} /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [semiring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_semiring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end
3d16d517489fbfcf39317010f9b847e081b496ae
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebraic_geometry/prime_spectrum.lean
2b9d1791aa26f8efe3cc3c68ce9732ae2e647849
[]
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
13,225
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.opens import Mathlib.ring_theory.ideal.prod import Mathlib.linear_algebra.finsupp import Mathlib.algebra.punit_instances import Mathlib.PostPort universes u u_1 v namespace Mathlib /-! # Prime spectrum of a commutative ring The prime spectrum of a commutative ring is the type of all prime ideals. It is naturally endowed with a topology: the Zariski topology. (It is also naturally endowed with a sheaf of rings, which is constructed in `algebraic_geometry.structure_sheaf`.) ## Main definitions * `prime_spectrum R`: The prime spectrum of a commutative ring `R`, i.e., the set of all prime ideals of `R`. * `zero_locus s`: The zero locus of a subset `s` of `R` is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`. * `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R` is the intersection of points in `t` (viewed as prime ideals). ## Conventions We denote subsets of rings with `s`, `s'`, etc... whereas we denote subsets of prime spectra with `t`, `t'`, etc... ## Inspiration/contributors The contents of this file draw inspiration from <https://github.com/ramonfmir/lean-scheme> which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau, and Chris Hughes (on an earlier repository). -/ /-- The prime spectrum of a commutative ring `R` is the type of all prime ideals of `R`. It is naturally endowed with a topology (the Zariski topology), and a sheaf of commutative rings (see `algebraic_geometry.structure_sheaf`). It is a fundamental building block in algebraic geometry. -/ def prime_spectrum (R : Type u) [comm_ring R] := Subtype fun (I : ideal R) => ideal.is_prime I namespace prime_spectrum /-- A method to view a point in the prime spectrum of a commutative ring as an ideal of that ring. -/ def as_ideal {R : Type u} [comm_ring R] (x : prime_spectrum R) : ideal R := subtype.val x protected instance is_prime {R : Type u} [comm_ring R] (x : prime_spectrum R) : ideal.is_prime (as_ideal x) := subtype.property x /-- The prime spectrum of the zero ring is empty. -/ theorem punit (x : prime_spectrum PUnit) : False := iff.mp (ideal.ne_top_iff_one (subtype.val x)) (and.left (subtype.property x)) (subsingleton.elim 0 1 ▸ ideal.zero_mem (subtype.val x)) /-- The prime spectrum of `R × S` is in bijection with the disjoint unions of the prime spectrum of `R` and the prime spectrum of `S`. -/ def prime_spectrum_prod (R : Type u) [comm_ring R] (S : Type v) [comm_ring S] : prime_spectrum (R × S) ≃ prime_spectrum R ⊕ prime_spectrum S := ideal.prime_ideals_equiv R S @[simp] theorem prime_spectrum_prod_symm_inl_as_ideal {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (x : prime_spectrum R) : as_ideal (coe_fn (equiv.symm (prime_spectrum_prod R S)) (sum.inl x)) = ideal.prod (as_ideal x) ⊤ := sorry @[simp] theorem prime_spectrum_prod_symm_inr_as_ideal {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (x : prime_spectrum S) : as_ideal (coe_fn (equiv.symm (prime_spectrum_prod R S)) (sum.inr x)) = ideal.prod ⊤ (as_ideal x) := sorry theorem ext {R : Type u} [comm_ring R] {x : prime_spectrum R} {y : prime_spectrum R} : x = y ↔ as_ideal x = as_ideal y := subtype.ext_iff_val /-- The zero locus of a set `s` of elements of a commutative ring `R` is the set of all prime ideals of the ring that contain the set `s`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R` where all "functions" in `s` vanish simultaneously. -/ def zero_locus {R : Type u} [comm_ring R] (s : set R) : set (prime_spectrum R) := set_of fun (x : prime_spectrum R) => s ⊆ ↑(as_ideal x) @[simp] theorem mem_zero_locus {R : Type u} [comm_ring R] (x : prime_spectrum R) (s : set R) : x ∈ zero_locus s ↔ s ⊆ ↑(as_ideal x) := iff.rfl @[simp] theorem zero_locus_span {R : Type u} [comm_ring R] (s : set R) : zero_locus ↑(ideal.span s) = zero_locus s := set.ext fun (x : prime_spectrum R) => galois_insertion.gc (submodule.gi R R) s (as_ideal x) /-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is the intersection of all the prime ideals in the set `t`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `R` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) : ideal R := infi fun (x : prime_spectrum R) => infi fun (h : x ∈ t) => as_ideal x theorem coe_vanishing_ideal {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) : ↑(vanishing_ideal t) = set_of fun (f : R) => ∀ (x : prime_spectrum R), x ∈ t → f ∈ as_ideal x := sorry theorem mem_vanishing_ideal {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) (f : R) : f ∈ vanishing_ideal t ↔ ∀ (x : prime_spectrum R), x ∈ t → f ∈ as_ideal x := sorry theorem subset_zero_locus_iff_le_vanishing_ideal {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) (I : ideal R) : t ⊆ zero_locus ↑I ↔ I ≤ vanishing_ideal t := sorry /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ theorem gc (R : Type u) [comm_ring R] : galois_connection (fun (I : ideal R) => zero_locus ↑I) fun (t : order_dual (set (prime_spectrum R))) => vanishing_ideal t := fun (I : ideal R) (t : order_dual (set (prime_spectrum R))) => subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ theorem gc_set (R : Type u) [comm_ring R] : galois_connection (fun (s : set R) => zero_locus s) fun (t : order_dual (set (prime_spectrum R))) => ↑(vanishing_ideal t) := sorry theorem subset_zero_locus_iff_subset_vanishing_ideal (R : Type u) [comm_ring R] (t : set (prime_spectrum R)) (s : set R) : t ⊆ zero_locus s ↔ s ⊆ ↑(vanishing_ideal t) := gc_set R s t -- TODO: we actually get the radical ideal, -- but I think that isn't in mathlib yet. theorem subset_vanishing_ideal_zero_locus {R : Type u} [comm_ring R] (s : set R) : s ⊆ ↑(vanishing_ideal (zero_locus s)) := galois_connection.le_u_l (gc_set R) s theorem le_vanishing_ideal_zero_locus {R : Type u} [comm_ring R] (I : ideal R) : I ≤ vanishing_ideal (zero_locus ↑I) := galois_connection.le_u_l (gc R) I theorem subset_zero_locus_vanishing_ideal {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) : t ⊆ zero_locus ↑(vanishing_ideal t) := galois_connection.l_u_le (gc R) t theorem zero_locus_bot {R : Type u} [comm_ring R] : zero_locus ↑⊥ = set.univ := galois_connection.l_bot (gc R) @[simp] theorem zero_locus_singleton_zero {R : Type u} [comm_ring R] : zero_locus 0 = set.univ := zero_locus_bot @[simp] theorem zero_locus_empty {R : Type u} [comm_ring R] : zero_locus ∅ = set.univ := galois_connection.l_bot (gc_set R) @[simp] theorem vanishing_ideal_univ {R : Type u} [comm_ring R] : vanishing_ideal ∅ = ⊤ := eq.mpr (id (Eq.refl (vanishing_ideal ∅ = ⊤))) (eq.mp (Eq.refl (vanishing_ideal ⊤ = ⊤)) (galois_connection.u_top (gc R))) theorem zero_locus_empty_of_one_mem {R : Type u} [comm_ring R] {s : set R} (h : 1 ∈ s) : zero_locus s = ∅ := sorry theorem zero_locus_empty_iff_eq_top {R : Type u} [comm_ring R] {I : ideal R} : zero_locus ↑I = ∅ ↔ I = ⊤ := sorry @[simp] theorem zero_locus_univ {R : Type u} [comm_ring R] : zero_locus set.univ = ∅ := zero_locus_empty_of_one_mem (set.mem_univ 1) theorem zero_locus_sup {R : Type u} [comm_ring R] (I : ideal R) (J : ideal R) : zero_locus ↑(I ⊔ J) = zero_locus ↑I ∩ zero_locus ↑J := galois_connection.l_sup (gc R) theorem zero_locus_union {R : Type u} [comm_ring R] (s : set R) (s' : set R) : zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' := galois_connection.l_sup (gc_set R) theorem vanishing_ideal_union {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) (t' : set (prime_spectrum R)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := galois_connection.u_inf (gc R) theorem zero_locus_supr {R : Type u} [comm_ring R] {ι : Sort u_1} (I : ι → ideal R) : zero_locus ↑(supr fun (i : ι) => I i) = set.Inter fun (i : ι) => zero_locus ↑(I i) := galois_connection.l_supr (gc R) theorem zero_locus_Union {R : Type u} [comm_ring R] {ι : Sort u_1} (s : ι → set R) : zero_locus (set.Union fun (i : ι) => s i) = set.Inter fun (i : ι) => zero_locus (s i) := galois_connection.l_supr (gc_set R) theorem zero_locus_bUnion {R : Type u} [comm_ring R] (s : set (set R)) : zero_locus (set.Union fun (s' : set R) => set.Union fun (H : s' ∈ s) => s') = set.Inter fun (s' : set R) => set.Inter fun (H : s' ∈ s) => zero_locus s' := sorry theorem vanishing_ideal_Union {R : Type u} [comm_ring R] {ι : Sort u_1} (t : ι → set (prime_spectrum R)) : vanishing_ideal (set.Union fun (i : ι) => t i) = infi fun (i : ι) => vanishing_ideal (t i) := galois_connection.u_infi (gc R) theorem zero_locus_inf {R : Type u} [comm_ring R] (I : ideal R) (J : ideal R) : zero_locus ↑(I ⊓ J) = zero_locus ↑I ∪ zero_locus ↑J := sorry theorem union_zero_locus {R : Type u} [comm_ring R] (s : set R) (s' : set R) : zero_locus s ∪ zero_locus s' = zero_locus ↑(ideal.span s ⊓ ideal.span s') := sorry theorem sup_vanishing_ideal_le {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) (t' : set (prime_spectrum R)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := sorry theorem mem_compl_zero_locus_iff_not_mem {R : Type u} [comm_ring R] {f : R} {I : prime_spectrum R} : I ∈ (zero_locus (singleton f)ᶜ) ↔ ¬f ∈ as_ideal I := sorry /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ protected instance zariski_topology {R : Type u} [comm_ring R] : topological_space (prime_spectrum R) := topological_space.of_closed (set.range zero_locus) sorry sorry sorry theorem is_open_iff {R : Type u} [comm_ring R] (U : set (prime_spectrum R)) : is_open U ↔ ∃ (s : set R), Uᶜ = zero_locus s := sorry theorem is_closed_iff_zero_locus {R : Type u} [comm_ring R] (Z : set (prime_spectrum R)) : is_closed Z ↔ ∃ (s : set R), Z = zero_locus s := sorry theorem is_closed_zero_locus {R : Type u} [comm_ring R] (s : set R) : is_closed (zero_locus s) := eq.mpr (id (Eq._oldrec (Eq.refl (is_closed (zero_locus s))) (propext (is_closed_iff_zero_locus (zero_locus s))))) (Exists.intro s rfl) /-- The function between prime spectra of commutative rings induced by a ring homomorphism. This function is continuous. -/ def comap {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (f : R →+* S) : prime_spectrum S → prime_spectrum R := fun (y : prime_spectrum S) => { val := ideal.comap f (as_ideal y), property := sorry } @[simp] theorem comap_as_ideal {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (f : R →+* S) (y : prime_spectrum S) : as_ideal (comap f y) = ideal.comap f (as_ideal y) := rfl @[simp] theorem comap_id {R : Type u} [comm_ring R] : comap (ring_hom.id R) = id := funext fun (_x : prime_spectrum R) => subtype.ext (ideal.ext fun (_x_1 : R) => iff.rfl) @[simp] theorem comap_comp {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] {S' : Type u_1} [comm_ring S'] (f : R →+* S) (g : S →+* S') : comap (ring_hom.comp g f) = comap f ∘ comap g := funext fun (_x : prime_spectrum S') => subtype.ext (ideal.ext fun (_x_1 : R) => iff.rfl) @[simp] theorem preimage_comap_zero_locus {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (f : R →+* S) (s : set R) : comap f ⁻¹' zero_locus s = zero_locus (⇑f '' s) := sorry theorem comap_continuous {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (f : R →+* S) : continuous (comap f) := sorry theorem zero_locus_vanishing_ideal_eq_closure {R : Type u} [comm_ring R] (t : set (prime_spectrum R)) : zero_locus ↑(vanishing_ideal t) = closure t := sorry /-- The prime spectrum of a commutative ring is a compact topological space. -/ protected instance compact_space {R : Type u} [comm_ring R] : compact_space (prime_spectrum R) := sorry /-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/ def basic_open {R : Type u} [comm_ring R] (r : R) : topological_space.opens (prime_spectrum R) := { val := set_of fun (x : prime_spectrum R) => ¬r ∈ as_ideal x, property := sorry } theorem is_open_basic_open {R : Type u} [comm_ring R] {a : R} : is_open ↑(basic_open a) := subtype.property (basic_open a)