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
683d17b056049d120a23659fe5583045129f2311
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/pkg/user_ext/lakefile.lean
2588ea8e195bf331c74e452dad7793c2f9725643
[ "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
86
lean
import Lake open System Lake DSL package user_ext @[default_target] lean_lib UserExt
a562132dca940523070525ee0686b48c64c04ead
7571914d3f4d9677288f35ab1a53a2ad70a62bd7
/tests/lean/run/tuple_head_issue.lean
de26fa61c7aed3629ad987c03e52f5e343e1c620
[ "Apache-2.0" ]
permissive
picrin/lean-1
a395fed5287995f09a15a190bb24609919a0727f
b50597228b42a7eaa01bf8cb7a4fb1a98e7a8aab
refs/heads/master
1,610,757,735,162
1,502,008,413,000
1,502,008,413,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
152
lean
open nat universe variables u variable {α : Type u} def head (n) : vector α (succ n) → α | ⟨[], H⟩ := by contradiction | ⟨a::b, H⟩ := a
45b7c7c57494644e2157afd4088c682fbd7e7dfa
0bebf71b69ba876e3ff052251728b46e79d4f55b
/differential_geometry_in_hott/lean/spheres.lean
c2970b7157661e59f23bfa2771700197763c9a86
[]
no_license
glangmead/writing
448f4b3880d5478bc0a511c8d7038ab1cd95e0a6
296aa7ebc5c880fe1e1b7a594be67113d8cba677
refs/heads/master
1,688,939,782,411
1,687,865,154,000
1,687,865,154,000
212,832,461
0
0
null
null
null
null
UTF-8
Lean
false
false
6,733
lean
import geometry.manifold.real_instances noncomputable theory variable (n : ℕ) theorem finset.image_val_univ_eq_range (n : ℕ) : finset.image (λ (x : fin n), x.val) finset.univ = finset.range n := begin ext j, -- sigh rw [finset.mem_range, finset.mem_image], split, rintro ⟨⟨j,hj⟩, _, rfl⟩, exact hj, intro hj, use ⟨j, hj⟩, split, apply finset.mem_univ, refl, end theorem finset.sum_univ_fin_eq_sum_range (n : ℕ) (f : fin n → ℝ) : finset.sum finset.univ f = (finset.range n).sum (λ i, if hi : i < n then f ⟨i, hi⟩ else 0) := begin set F : ℕ → ℝ := λ i, if hi : i < n then f ⟨i, hi⟩ else 0 with hF, have H : f = λ (i : fin n), F (i.val), { ext i, rw hF, show f i = dite (i.val < n) (λ (hi : i.val < n), f ⟨i.val, hi⟩) (λ (hi : ¬i.val < n), 0), rw dif_pos i.is_lt, cases i, refl, }, rw H, rw ←finset.sum_image, { congr', apply finset.image_val_univ_eq_range, }, intros _ _ _ _, exact fin.eq_of_veq, end theorem finset.sum_div {α : Type*} {s : finset α} (f : α → ℝ) (d : ℝ) : finset.sum s (λ a, f a / d) = finset.sum s f / d := begin by_cases hd : d = 0, rw [hd, div_zero], convert finset.sum_const_zero, ext _, rw div_zero, rw [div_eq_mul_inv, finset.sum_mul], congr', end def unit_sphere (n) := { x : euclidean_space (n + 1) // finset.univ.sum (λ i, (x i) ^ 2) = 1} open finset def stereographic_projection_inv_north (n) : (euclidean_space n) → (unit_sphere n) := λx, ⟨λ(i : fin (n + 1)), (if lt : i.val < n then (2 * (x (fin.cast_lt i lt)) / (finset.univ.sum (λ j, (x j) ^ 2) + 1)) else (((finset.univ.sum (λj, (x j)^2) - 1) / (finset.univ.sum (λ j, (x j)^2) + 1)))), begin rw [sum_univ_fin_eq_sum_range, sum_range_succ, dif_pos (nat.lt_succ_self n), dif_neg (lt_irrefl n)], suffices : ((sum univ (λ (j : fin n), x j ^ 2) - 1) / (sum univ (λ (j : fin n), x j ^ 2) + 1)) ^ 2 + (sum (range n) (λ (i : ℕ), if hi : i < n then (2 * x ⟨i, hi⟩)^2 else 0) / (sum univ (λ (j : fin n), x j ^ 2) + 1) ^ 2) = 1, { convert this using 2, clear this, rw ←sum_div, apply finset.sum_congr, refl, intros i hi, rw finset.mem_range at hi, rw dif_pos (lt_trans hi (nat.lt_succ_self n)), rw dif_pos hi, rw dif_pos hi, rw pow_div, congr', }, rw pow_div, rw ←add_div, rw div_eq_one_iff_eq, swap, { apply ne_of_gt, apply pow_pos, apply lt_of_lt_of_le zero_lt_one, apply le_add_of_nonneg_left', apply sum_nonneg, intros, rw pow_two, apply mul_self_nonneg, }, rw [sub_eq_add_neg, pow_two, pow_two, add_mul_self_eq, add_mul_self_eq], rw [neg_mul_neg, mul_neg_one, mul_one, mul_one], rw add_comm, repeat {rw ←add_assoc}, congr' 1, rw [add_assoc, add_left_comm], apply congr_arg, apply add_neg_eq_of_eq_add, rw [mul_sum, ←sum_add_distrib], rw sum_univ_fin_eq_sum_range, apply sum_congr, refl, intros i hi, rw mem_range at hi, rw [dif_pos hi, dif_pos hi], ring, end ⟩ instance sphere_top_space (n) : topological_space (unit_sphere n) := subtype.topological_space instance sphere_has_coe_to_euclidean_space (n) : has_coe (unit_sphere n) (euclidean_space (n + 1)) := coe_subtype def fin_embedding (n) : has_coe (fin n) (fin (n + 1)) := { coe := by exact fin.succ } meta def my_tac : tactic unit := `[ repeat { {left, assumption} <|> right <|> assumption } ] -- The unit sphere minus its north pole will be a coordinate chart via stereographic projection -- def unit_sphere_minus_north_pole (n) := { x : unit_sphere n // ((x : (euclidean_space (n + 1))) n) ≤ 1 } def unit_sphere_minus_north_pole (n) : set (unit_sphere n) := {x | (x : (euclidean_space (n + 1))) n < 1} -- instance sphere_minus_np_top_space (n) : topological_space (unit_sphere_minus_north_pole n) := subtype.topological_space -- instance sphere_minus_np_has_coe_to_sphere (n) : has_coe (unit_sphere_minus_north_pole n) (unit_sphere n) := coe_subtype -- instance sphere_minus_np_has_coe_to_euclidean_space (n) : has_coe (unit_sphere_minus_north_pole n) (euclidean_space (n + 1)) := sorry -- def stereographic_projection_north (n) : (unit_sphere_minus_north_pole (n + 1)) → (euclidean_space (n + 1)) := -- λ sphere i, ((sphere : euclidean_space (n + 2)) i) * (1 - ((sphere : euclidean_space (n + 2)) (n + 1)))⁻¹ def stereographic_projection_north_local_equiv : local_equiv (unit_sphere n) (euclidean_space n) := { source := unit_sphere_minus_north_pole n, target := {x : (euclidean_space n) | true}, to_fun := λ sphere, (λi, ((sphere : euclidean_space (n + 1)) i) * (1 - ((sphere : euclidean_space (n + 1)) (n + 1)))⁻¹), inv_fun := stereographic_projection_inv_north n, map_source := begin simp at *, end, -- all these fields say that the functions `to_fun` and `inv_fun` are inverse map_target := begin end, -- to each other on the sets `source` and `target` left_inv := sorry, right_inv := sorry } def stereographic_projection_north : local_homeomorph (unit_sphere n) (euclidean_space n) := { ..stereographic_projection_north_local_equiv n } lemma continuous_sp_north (n:ℕ) : continuous (stereographic_projection_north n) := begin unfold stereographic_projection_north, apply continuous.mul _ _, end -- The unit sphere minus its south pole will be a coordinate chart via stereographic projection def unit_sphere_minus_south_pole (n) := { x : unit_sphere n // (-1 ≤ (x : (euclidean_space (n + 1))) n) } instance sphere_minus_sp_top_space (n) : topological_space (unit_sphere_minus_south_pole n) := subtype.topological_space #check continuous_inv #check real.continuous_inv #check inv_eq_one_div #check continuous.comp #check continuous.mul -- Stereographic projection: -- define -- prove continuous -- prove inverse -- prove inverse continuous -- prove homeomorphism -- prove overlaps are smooth -- prove diffeomorphism -- define sphere as manifold def stereographic_projection_south (n) : (unit_sphere_minus_south_pole n) → (euclidean_space n) := λ sphere i, ((sphere : euclidean_space (n + 1)) i) * (1 - ((sphere : euclidean_space (n + 1)) n))⁻¹ def unit_sphere_manifold_core (n) [has_zero (fin n)] : manifold_core (euclidean_space n) (unit_sphere n) := { atlas := _, chart_at := _, mem_chart_source := _, chart_mem_atlas := _, open_source := _, continuous_to_fun := _ } def stereographic_projection_north_inv (n) : (euclidean_space n) → (unit_sphere_minus_north_pole n) := sorry --λ x, let denom := 1 + finset.univ.sum (λ i, (x i) ^ 2) in def stereo_homeomorph (n) : homeomorph (unit_sphere_minus_north_pole n) (euclidean_space n) := sorry -- image_i = src_i / (1 - src_0)
b1551a6db388f65c2ce68b47565aa7e8b2c9244a
b73bd2854495d87ad5ce4f247cfcd6faa7e71c7e
/src/game/world3/level4.lean
03fe77181a8d8d6ba9c3b5f462ab3808ed431b52
[]
no_license
agusakov/category-theory-game
20db0b26270e0c95a3d5605498570273d72f731d
652dd7e90ae706643b2a597e2c938403653e167d
refs/heads/master
1,669,201,216,310
1,595,740,057,000
1,595,740,057,000
280,895,295
12
0
null
null
null
null
UTF-8
Lean
false
false
997
lean
import category_theory.category.default universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory variables (C : Type u) [category.{v} C] --rewrite this /- # Category world ## Level 7: Cancellations With monomorphisms and epimorphisms, we get some new useful cancellation laws. You will notice that the following two lemmas are pretty similar to the lemma we had in level 5 of world 1. See if you can spot the difference. -/ /- Lemma If $$f : X ⟶ Y$$ and $$g : X ⟶ Y$$ are morphisms such that $$f = g$$, then $$f ≫ h = g ≫ h$$. -/ lemma cancel_epi_id' (X Y : C) (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := begin split, intro hyp, rw ← category.comp_id f at hyp, rw category.assoc at hyp, rw category.id_comp at hyp, rw ← cancel_epi f, exact hyp, intro hyp, rw hyp, exact category.comp_id f, end end category_theory
11acfbaca33a68d014ba34c1e88ba738e0864e6b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/algebra/ordered/liminf_limsup.lean
16e954577ba93c0d1593b18e2cd2985a75ee1a33
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,248
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import topology.algebra.ordered.basic import order.liminf_limsup /-! # Lemmas about liminf and limsup in an order topology. -/ open filter open_locale topological_space classical universes u v variables {α : Type u} {β : Type v} section liminf_limsup section order_closed_topology variables [semilattice_sup α] [topological_space α] [order_topology α] lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, eventually_of_forall h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma filter.tendsto.is_bounded_under_le {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u := (is_bounded_le_nhds a).mono h lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) := (is_bounded_le_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_ge {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u := h.is_bounded_under_le.is_cobounded_flip end order_closed_topology section order_closed_topology variables [semilattice_inf α] [topological_space α] [order_topology α] lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) := @is_bounded_le_nhds (order_dual α) _ _ _ a lemma filter.tendsto.is_bounded_under_ge {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u := (is_bounded_ge_nhds a).mono h lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) := (is_bounded_ge_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_le {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u := h.is_bounded_under_ge.is_cobounded_flip end order_closed_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : ∀ᶠ a in f, a < b := let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → b < f.Liminf → ∀ᶠ a in f, b < a := @lt_mem_sets_of_Limsup_lt (order_dual α) _ variables [topological_space α] [order_topology α] /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ 𝓝 a := tendsto_order.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a := cInf_eq_of_forall_ge_of_forall_gt_exists_lt (is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_mem_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from match dense_or_discrete a b with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from (is_bounded_ge_nhds a).mono h, have hb_le : is_bounded (≤) f, from (is_bounded_le_nhds a).mono h, le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hb_le hb_ge ... ≤ (𝓝 a).Limsup : Limsup_le_Limsup_of_le h hb_ge.is_cobounded_flip (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) hb_le.is_cobounded_flip) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α} [ne_bot f], f ≤ 𝓝 a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ /-- If a function has a limit, then its limsup coincides with its limit. -/ theorem filter.tendsto.limsup_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : limsup f u = a := Limsup_eq_of_le_nhds h /-- If a function has a limit, then its liminf coincides with its limit. -/ theorem filter.tendsto.liminf_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : liminf f u = a := Liminf_eq_of_le_nhds h end conditionally_complete_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] -- In complete_linear_order, the above theorems take a simpler form /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (hinf : liminf f u = a) (hsup : limsup f u = a) : tendsto u f (𝓝 a) := le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot hsup hinf /-- If a number `a` is less than or equal to the `liminf` of a function `f` at some filter and is greater than or equal to the `limsup` of `f`, then `f` tends to `a` along this filter. -/ theorem tendsto_of_le_liminf_of_limsup_le {f : filter β} {u : β → α} {a : α} (hinf : a ≤ liminf f u) (hsup : limsup f u ≤ a) : tendsto u f (𝓝 a) := if hf : f = ⊥ then hf.symm ▸ tendsto_bot else by haveI : ne_bot f := ⟨hf⟩; exact tendsto_of_liminf_eq_limsup (le_antisymm (le_trans liminf_le_limsup hsup) hinf) (le_antisymm hsup (le_trans hinf liminf_le_limsup)) end complete_linear_order end liminf_limsup
e75f23aeadcc70fe0a226cfbba68fc994e51f3e3
367134ba5a65885e863bdc4507601606690974c1
/src/data/mv_polynomial/monad.lean
f38e824e42e24705e1cb245f0c21e49d052e472c
[ "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
13,426
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.mv_polynomial.rename /-! # Monad operations on `mv_polynomial` This file defines two monadic operations on `mv_polynomial`. Given `p : mv_polynomial σ R`, * `mv_polynomial.bind₁` and `mv_polynomial.join₁` operate on the variable type `σ`. * `mv_polynomial.bind₂` and `mv_polynomial.join₂` operate on the coefficient type `R`. - `mv_polynomial.bind₁ f φ` with `f : σ → mv_polynomial τ R` and `φ : mv_polynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : mv_polynomial τ R`. - `mv_polynomial.join₁ φ` with `φ : mv_polynomial (mv_polynomial σ R) R` collapses `φ` to a `mv_polynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : mv_polynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `mv_polynomial.bind₂ f φ` with `f : R →+* mv_polynomial σ S` and `φ : mv_polynomial σ R` is the `mv_polynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `mv_polynomial σ R`. - `mv_polynomial.join₂ φ` with `φ : mv_polynomial σ (mv_polynomial σ R)` collapses `φ` to a `mv_polynomial σ R`, by considering `φ` as polynomial expression in `mv_polynomial σ R`. These operations themselves have algebraic structure: `mv_polynomial.bind₁` and `mv_polynomial.join₁` are algebra homs and `mv_polynomial.bind₂` and `mv_polynomial.join₂` are ring homs. They interact in convenient ways with `mv_polynomial.rename`, `mv_polynomial.map`, `mv_polynomial.vars`, and other polynomial operations. Indeed, `mv_polynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `mv_polynomial.map` is the "map" operation for the other pair. ## Implementation notes We add an `is_lawful_monad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `monad`, since it is not a monad in `Type` but in `CommRing` (or rather `CommSemiRing`). -/ open_locale big_operators noncomputable theory namespace mv_polynomial open finsupp variables {σ : Type*} {τ : Type*} variables {R S T : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring T] /-- `bind₁` is the "left hand side" bind operation on `mv_polynomial`, operating on the variable type. Given a polynomial `p : mv_polynomial σ R` and a map `f : σ → mv_polynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ (f : σ → mv_polynomial τ R) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval f /-- `bind₂` is the "right hand side" bind operation on `mv_polynomial`, operating on the coefficient type. Given a polynomial `p : mv_polynomial σ R` and a map `f : R → mv_polynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ (f : R →+* mv_polynomial σ S) : mv_polynomial σ R →+* mv_polynomial σ S := eval₂_hom f X /-- `join₁` is the monadic join operation corresponding to `mv_polynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ : mv_polynomial (mv_polynomial σ R) R →ₐ[R] mv_polynomial σ R := aeval id /-- `join₂` is the monadic join operation corresponding to `mv_polynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ : mv_polynomial σ (mv_polynomial σ R) →+* mv_polynomial σ R := eval₂_hom (ring_hom.id _) X @[simp] lemma aeval_eq_bind₁ (f : σ → mv_polynomial τ R) : aeval f = bind₁ f := rfl @[simp] lemma eval₂_hom_C_eq_bind₁ (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl @[simp] lemma eval₂_hom_eq_bind₂ (f : R →+* mv_polynomial σ S) : eval₂_hom f X = bind₂ f := rfl section variables (σ R) @[simp] lemma aeval_id_eq_join₁ : aeval id = @join₁ σ R _ := rfl lemma eval₂_hom_C_id_eq_join₁ (φ : mv_polynomial (mv_polynomial σ R) R) : eval₂_hom C id φ = join₁ φ := rfl @[simp] lemma eval₂_hom_id_X_eq_join₂ : eval₂_hom (ring_hom.id _) X = @join₂ σ R _ := rfl end -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards local attribute [-simp] aeval_eq_bind₁ eval₂_hom_C_eq_bind₁ eval₂_hom_eq_bind₂ aeval_id_eq_join₁ eval₂_hom_id_X_eq_join₂ @[simp] lemma bind₁_X_right (f : σ → mv_polynomial τ R) (i : σ) : bind₁ f (X i) = f i := aeval_X f i @[simp] lemma bind₂_X_right (f : R →+* mv_polynomial σ S) (i : σ) : bind₂ f (X i) = X i := eval₂_hom_X' f X i @[simp] lemma bind₁_X_left : bind₁ (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by { ext1 i, simp } lemma aeval_X_left : aeval (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by rw [aeval_eq_bind₁, bind₁_X_left] lemma aeval_X_left_apply (φ : mv_polynomial σ R) : aeval X φ = φ := by rw [aeval_eq_bind₁, bind₁_X_left, alg_hom.id_apply] variable (f : σ → mv_polynomial τ R) @[simp] lemma bind₁_C_right (f : σ → mv_polynomial τ R) (x) : bind₁ f (C x) = C x := by simp [bind₁, C, aeval_monomial, finsupp.prod_zero_index]; refl @[simp] lemma bind₂_C_right (f : R →+* mv_polynomial σ S) (r : R) : bind₂ f (C r) = f r := eval₂_hom_C f X r @[simp] lemma bind₂_C_left : bind₂ (C : R →+* mv_polynomial σ R) = ring_hom.id _ := by { ext1; simp } @[simp] lemma bind₂_comp_C (f : R →+* mv_polynomial σ S) : (bind₂ f).comp C = f := ring_hom.ext $ bind₂_C_right _ @[simp] lemma join₂_map (f : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : join₂ (map f φ) = bind₂ f φ := by simp only [join₂, bind₂, eval₂_hom_map_hom, ring_hom.id_comp] @[simp] lemma join₂_comp_map (f : R →+* mv_polynomial σ S) : join₂.comp (map f) = bind₂ f := ring_hom.ext $ join₂_map _ lemma aeval_id_rename (f : σ → mv_polynomial τ R) (p : mv_polynomial σ R) : aeval id (rename f p) = aeval f p := by rw [aeval_rename, function.comp.left_id] @[simp] lemma join₁_rename (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : join₁ (rename f φ) = bind₁ f φ := aeval_id_rename _ _ @[simp] lemma bind₁_id : bind₁ (@id (mv_polynomial σ R)) = join₁ := rfl @[simp] lemma bind₂_id : bind₂ (ring_hom.id (mv_polynomial σ R)) = join₂ := rfl lemma bind₁_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) (φ : mv_polynomial σ R) : (bind₁ g) (bind₁ f φ) = bind₁ (λ i, bind₁ g (f i)) φ := by simp [bind₁, ← comp_aeval] lemma bind₁_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) : (bind₁ g).comp (bind₁ f) = bind₁ (λ i, bind₁ g (f i)) := by { ext1, apply bind₁_bind₁ } lemma bind₂_comp_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) : (bind₂ g).comp (bind₂ f) = bind₂ ((bind₂ g).comp f) := by { ext1; simp } lemma bind₂_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) (φ : mv_polynomial σ R) : (bind₂ g) (bind₂ f φ) = bind₂ ((bind₂ g).comp f) φ := ring_hom.congr_fun (bind₂_comp_bind₂ f g) φ lemma rename_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) : (rename g).comp (bind₁ f) = bind₁ (λ i, rename g $ f i) := by { ext1 i, simp } lemma rename_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) (φ : mv_polynomial σ R) : rename g (bind₁ f φ) = bind₁ (λ i, rename g $ f i) φ := alg_hom.congr_fun (rename_comp_bind₁ f g) φ lemma map_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* T) (φ : mv_polynomial σ R) : map g (bind₂ f φ) = bind₂ ((map g).comp f) φ := begin simp only [bind₂, eval₂_comp_right, coe_eval₂_hom, eval₂_map], congr' 1 with : 1, simp only [function.comp_app, map_X] end lemma bind₁_comp_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) : (bind₁ f).comp (rename g) = bind₁ (f ∘ g) := by { ext1 i, simp } lemma bind₁_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) (φ : mv_polynomial σ R) : bind₁ f (rename g φ) = bind₁ (f ∘ g) φ := alg_hom.congr_fun (bind₁_comp_rename f g) φ lemma bind₂_map (f : S →+* mv_polynomial σ T) (g : R →+* S) (φ : mv_polynomial σ R) : bind₂ f (map g φ) = bind₂ (f.comp g) φ := by simp [bind₂] @[simp] lemma map_comp_C (f : R →+* S) : (map f).comp (C : R →+* mv_polynomial σ R) = C.comp f := by { ext1, apply map_C } -- mixing the two monad structures lemma hom_bind₁ (f : mv_polynomial τ R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : f (bind₁ g φ) = eval₂_hom (f.comp C) (λ i, f (g i)) φ := by rw [bind₁, map_aeval, algebra_map_eq] lemma map_bind₁ (f : R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : map f (bind₁ g φ) = bind₁ (λ (i : σ), (map f) (g i)) (map f φ) := by { rw [hom_bind₁, map_comp_C, ← eval₂_hom_map_hom], refl } @[simp] lemma eval₂_hom_comp_C (f : R →+* S) (g : σ → S) : (eval₂_hom f g).comp C = f := by { ext1 r, exact eval₂_C f g r } lemma eval₂_hom_bind₁ (f : R →+* S) (g : τ → S) (h : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₁ h φ) = eval₂_hom f (λ i, eval₂_hom f g (h i)) φ := by rw [hom_bind₁, eval₂_hom_comp_C] lemma aeval_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : aeval f (bind₁ g φ) = aeval (λ i, aeval f (g i)) φ := eval₂_hom_bind₁ _ _ _ _ lemma aeval_comp_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) : (aeval f).comp (bind₁ g) = aeval (λ i, aeval f (g i)) := by { ext1, apply aeval_bind₁ } lemma eval₂_hom_comp_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) : (eval₂_hom f g).comp (bind₂ h) = eval₂_hom ((eval₂_hom f g).comp h) g := by { ext1; simp } lemma eval₂_hom_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₂ h φ) = eval₂_hom ((eval₂_hom f g).comp h) g φ := ring_hom.congr_fun (eval₂_hom_comp_bind₂ f g h) φ lemma aeval_bind₂ [algebra S T] (f : σ → T) (g : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : aeval f (bind₂ g φ) = eval₂_hom ((↑(aeval f : _ →ₐ[S] _) : _ →+* _).comp g) f φ := eval₂_hom_bind₂ _ _ _ _ lemma eval₂_hom_C_left (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl lemma bind₁_monomial (f : σ → mv_polynomial τ R) (d : σ →₀ ℕ) (r : R) : bind₁ f (monomial d r) = C r * ∏ i in d.support, f i ^ d i := by simp only [monomial_eq, alg_hom.map_mul, bind₁_C_right, finsupp.prod, alg_hom.map_prod, alg_hom.map_pow, bind₁_X_right] lemma bind₂_monomial (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) (r : R) : bind₂ f (monomial d r) = f r * monomial d 1 := by simp only [monomial_eq, ring_hom.map_mul, bind₂_C_right, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, bind₂_X_right, C_1, one_mul] @[simp] lemma bind₂_monomial_one (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) : bind₂ f (monomial d 1) = monomial d 1 := by rw [bind₂_monomial, f.map_one, one_mul] instance monad : monad (λ σ, mv_polynomial σ R) := { map := λ α β f p, rename f p, pure := λ _, X, bind := λ _ _ p f, bind₁ f p } instance is_lawful_functor : is_lawful_functor (λ σ, mv_polynomial σ R) := { id_map := by intros; simp [(<$>)], comp_map := by intros; simp [(<$>)] } instance is_lawful_monad : is_lawful_monad (λ σ, mv_polynomial σ R) := { pure_bind := by intros; simp [pure, bind], bind_assoc := by intros; simp [bind, ← bind₁_comp_bind₁] } /- Possible TODO for the future: Enable the following definitions, and write a lot of supporting lemmas. def bind (f : R →+* mv_polynomial τ S) (g : σ → mv_polynomial τ S) : mv_polynomial σ R →+* mv_polynomial τ S := eval₂_hom f g def join (f : R →+* S) : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := aeval (map f) def ajoin [algebra R S] : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := join (algebra_map R S) -/ end mv_polynomial
d0fe58571bc99b61ecb9792fab5d49db658f4c44
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Module/abelian.lean
c5bee70e2efed206f62f5d116e959395ec1e7752
[ "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
3,302
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import linear_algebra.isomorphisms import algebra.category.Module.kernels import algebra.category.Module.limits import category_theory.abelian.exact /-! # The category of left R-modules is abelian. Additionally, two linear maps are exact in the categorical sense iff `range f = ker g`. -/ open category_theory open category_theory.limits noncomputable theory universes v u namespace Module variables {R : Type u} [ring R] {M N : Module.{v} R} (f : M ⟶ N) /-- In the category of modules, every monomorphism is normal. -/ def normal_mono (hf : mono f) : normal_mono f := { Z := of R (N ⧸ f.range), g := f.range.mkq, w := linear_map.range_mkq_comp _, is_limit := is_kernel.iso_kernel _ _ (kernel_is_limit _) /- The following [invalid Lean code](https://github.com/leanprover-community/lean/issues/341) might help you understand what's going on here: ``` calc M ≃ₗ[R] f.ker.quotient : (submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] r.range.mkq.ker : linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm ``` -/ (linear_equiv.to_Module_iso' ((submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ≪≫ₗ ((linear_map.quot_ker_equiv_range f) ≪≫ₗ (linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm)))) $ by { ext, refl } } /-- In the category of modules, every epimorphism is normal. -/ def normal_epi (hf : epi f) : normal_epi f := { W := of R f.ker, g := f.ker.subtype, w := linear_map.comp_ker_subtype _, is_colimit := is_cokernel.cokernel_iso _ _ (cokernel_is_colimit _) (linear_equiv.to_Module_iso' /- The following invalid Lean code might help you understand what's going on here: ``` calc f.ker.subtype.range.quotient ≃ₗ[R] f.ker.quotient : submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _) ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] N : linear_equiv.of_top _ (range_eq_top_of_epi _) ``` -/ (((submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _)) ≪≫ₗ (linear_map.quot_ker_equiv_range f)) ≪≫ₗ (linear_equiv.of_top _ (range_eq_top_of_epi _)))) $ by { ext, refl } } /-- The category of R-modules is abelian. -/ instance : abelian (Module R) := { has_finite_products := ⟨by apply_instance⟩, has_kernels := by apply_instance, has_cokernels := has_cokernels_Module, normal_mono_of_mono := λ X Y, normal_mono, normal_epi_of_epi := λ X Y, normal_epi } variables {O : Module.{v} R} (g : N ⟶ O) open linear_map local attribute [instance] preadditive.has_equalizers_of_has_kernels theorem exact_iff : exact f g ↔ f.range = g.ker := begin rw abelian.exact_iff' f g (kernel_is_limit _) (cokernel_is_colimit _), exact ⟨λ h, le_antisymm (range_le_ker_iff.2 h.1) (ker_le_range_iff.2 h.2), λ h, ⟨range_le_ker_iff.1 $ le_of_eq h, ker_le_range_iff.1 $ le_of_eq h.symm⟩⟩ end end Module
013069c54ce1e9cbf4731c2a4919fbd18e33344d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/transfer_instance.lean
3cfb04ec04e043279380642e7fdf110c0285c483
[]
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
11,451
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.data.equiv.basic import Mathlib.algebra.field import Mathlib.algebra.module.default import Mathlib.algebra.algebra.basic import Mathlib.algebra.group.type_tags import Mathlib.ring_theory.ideal.basic import Mathlib.PostPort universes u v u_1 u_2 namespace Mathlib /-! # Transfer algebraic structures across `equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. Note that most of these constructions can also be obtained using the `transport` tactic. ## Tags equiv, group, ring, field, module, algebra -/ namespace equiv /-- Transfer `has_one` across an `equiv` -/ protected def has_zero {α : Type u} {β : Type v} (e : α ≃ β) [HasZero β] : HasZero α := { zero := coe_fn (equiv.symm e) 0 } theorem zero_def {α : Type u} {β : Type v} (e : α ≃ β) [HasZero β] : 0 = coe_fn (equiv.symm e) 0 := rfl /-- Transfer `has_mul` across an `equiv` -/ protected def has_add {α : Type u} {β : Type v} (e : α ≃ β) [Add β] : Add α := { add := fun (x y : α) => coe_fn (equiv.symm e) (coe_fn e x + coe_fn e y) } theorem add_def {α : Type u} {β : Type v} (e : α ≃ β) [Add β] (x : α) (y : α) : x + y = coe_fn (equiv.symm e) (coe_fn e x + coe_fn e y) := rfl /-- Transfer `has_div` across an `equiv` -/ protected def has_sub {α : Type u} {β : Type v} (e : α ≃ β) [Sub β] : Sub α := { sub := fun (x y : α) => coe_fn (equiv.symm e) (coe_fn e x - coe_fn e y) } theorem div_def {α : Type u} {β : Type v} (e : α ≃ β) [Div β] (x : α) (y : α) : x / y = coe_fn (equiv.symm e) (coe_fn e x / coe_fn e y) := rfl /-- Transfer `has_inv` across an `equiv` -/ protected def has_inv {α : Type u} {β : Type v} (e : α ≃ β) [has_inv β] : has_inv α := has_inv.mk fun (x : α) => coe_fn (equiv.symm e) (coe_fn e x⁻¹) theorem neg_def {α : Type u} {β : Type v} (e : α ≃ β) [Neg β] (x : α) : -x = coe_fn (equiv.symm e) (-coe_fn e x) := rfl /-- Transfer `has_scalar` across an `equiv` -/ protected def has_scalar {α : Type u} {β : Type v} (e : α ≃ β) {R : Type u_1} [has_scalar R β] : has_scalar R α := has_scalar.mk fun (r : R) (x : α) => coe_fn (equiv.symm e) (r • coe_fn e x) theorem smul_def {α : Type u} {β : Type v} (e : α ≃ β) {R : Type u_1} [has_scalar R β] (r : R) (x : α) : r • x = coe_fn (equiv.symm e) (r • coe_fn e x) := rfl /-- An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β` where the multiplicative structure on `α` is the one obtained by transporting a multiplicative structure on `β` back along `e`. -/ def mul_equiv {α : Type u} {β : Type v} (e : α ≃ β) [Mul β] : let _inst : Mul α := equiv.has_mul e; α ≃* β := let _inst : Mul α := equiv.has_mul e; mul_equiv.mk (to_fun e) (inv_fun e) (left_inv e) (right_inv e) sorry @[simp] theorem mul_equiv_apply {α : Type u} {β : Type v} (e : α ≃ β) [Mul β] (a : α) : coe_fn (mul_equiv e) a = coe_fn e a := rfl theorem mul_equiv_symm_apply {α : Type u} {β : Type v} (e : α ≃ β) [Mul β] (b : β) : coe_fn (mul_equiv.symm (mul_equiv e)) b = coe_fn (equiv.symm e) b := Eq.refl (coe_fn (mul_equiv.symm (mul_equiv e)) b) /-- An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β` where the ring structure on `α` is the one obtained by transporting a ring structure on `β` back along `e`. -/ def ring_equiv {α : Type u} {β : Type v} (e : α ≃ β) [Add β] [Mul β] : let _inst : Add α := equiv.has_add e; let _inst_3 : Mul α := equiv.has_mul e; α ≃+* β := let _inst : Add α := equiv.has_add e; let _inst_3 : Mul α := equiv.has_mul e; ring_equiv.mk (to_fun e) (inv_fun e) (left_inv e) (right_inv e) sorry sorry @[simp] theorem ring_equiv_apply {α : Type u} {β : Type v} (e : α ≃ β) [Add β] [Mul β] (a : α) : coe_fn (ring_equiv e) a = coe_fn e a := rfl theorem ring_equiv_symm_apply {α : Type u} {β : Type v} (e : α ≃ β) [Add β] [Mul β] (b : β) : coe_fn (ring_equiv.symm (ring_equiv e)) b = coe_fn (equiv.symm e) b := Eq.refl (coe_fn (ring_equiv.symm (ring_equiv e)) b) /-- Transfer `semigroup` across an `equiv` -/ protected def semigroup {α : Type u} {β : Type v} (e : α ≃ β) [semigroup β] : semigroup α := semigroup.mk Mul.mul sorry /-- Transfer `comm_semigroup` across an `equiv` -/ protected def comm_semigroup {α : Type u} {β : Type v} (e : α ≃ β) [comm_semigroup β] : comm_semigroup α := comm_semigroup.mk semigroup.mul sorry sorry /-- Transfer `monoid` across an `equiv` -/ protected def monoid {α : Type u} {β : Type v} (e : α ≃ β) [monoid β] : monoid α := monoid.mk semigroup.mul sorry 1 sorry sorry /-- Transfer `comm_monoid` across an `equiv` -/ protected def add_comm_monoid {α : Type u} {β : Type v} (e : α ≃ β) [add_comm_monoid β] : add_comm_monoid α := add_comm_monoid.mk add_comm_semigroup.add sorry add_monoid.zero sorry sorry sorry /-- Transfer `group` across an `equiv` -/ protected def group {α : Type u} {β : Type v} (e : α ≃ β) [group β] : group α := group.mk monoid.mul sorry monoid.one sorry sorry has_inv.inv Div.div sorry /-- Transfer `comm_group` across an `equiv` -/ protected def comm_group {α : Type u} {β : Type v} (e : α ≃ β) [comm_group β] : comm_group α := comm_group.mk group.mul sorry group.one sorry sorry group.inv group.div sorry sorry /-- Transfer `semiring` across an `equiv` -/ protected def semiring {α : Type u} {β : Type v} (e : α ≃ β) [semiring β] : semiring α := semiring.mk Add.add sorry 0 sorry sorry sorry Mul.mul sorry monoid.one sorry sorry sorry sorry sorry sorry /-- Transfer `comm_semiring` across an `equiv` -/ protected def comm_semiring {α : Type u} {β : Type v} (e : α ≃ β) [comm_semiring β] : comm_semiring α := comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry sorry sorry sorry /-- Transfer `ring` across an `equiv` -/ protected def ring {α : Type u} {β : Type v} (e : α ≃ β) [ring β] : ring α := ring.mk semiring.add sorry semiring.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry /-- Transfer `comm_ring` across an `equiv` -/ protected def comm_ring {α : Type u} {β : Type v} (e : α ≃ β) [comm_ring β] : comm_ring α := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry comm_monoid.mul sorry comm_monoid.one sorry sorry sorry sorry sorry /-- Transfer `nonzero` across an `equiv` -/ protected theorem nontrivial {α : Type u} {β : Type v} (e : α ≃ β) [nontrivial β] : nontrivial α := sorry /-- Transfer `domain` across an `equiv` -/ protected def domain {α : Type u} {β : Type v} (e : α ≃ β) [domain β] : domain α := domain.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry sorry /-- Transfer `integral_domain` across an `equiv` -/ protected def integral_domain {α : Type u} {β : Type v} (e : α ≃ β) [integral_domain β] : integral_domain α := integral_domain.mk domain.add sorry domain.zero sorry sorry domain.neg domain.sub sorry sorry domain.mul sorry domain.one sorry sorry sorry sorry sorry sorry sorry /-- Transfer `division_ring` across an `equiv` -/ protected def division_ring {α : Type u} {β : Type v} (e : α ≃ β) [division_ring β] : division_ring α := division_ring.mk domain.add sorry 0 sorry sorry domain.neg domain.sub sorry sorry domain.mul sorry 1 sorry sorry sorry sorry has_inv.inv Div.div sorry sorry sorry /-- Transfer `field` across an `equiv` -/ protected def field {α : Type u} {β : Type v} (e : α ≃ β) [field β] : field α := field.mk integral_domain.add sorry integral_domain.zero sorry sorry integral_domain.neg integral_domain.sub sorry sorry integral_domain.mul sorry integral_domain.one sorry sorry sorry sorry sorry division_ring.inv sorry sorry sorry /-- Transfer `mul_action` across an `equiv` -/ protected def mul_action {α : Type u} {β : Type v} (R : Type u_1) [monoid R] (e : α ≃ β) [mul_action R β] : mul_action R α := mul_action.mk sorry sorry /-- Transfer `distrib_mul_action` across an `equiv` -/ protected def distrib_mul_action {α : Type u} {β : Type v} (R : Type u_1) [monoid R] (e : α ≃ β) [add_comm_monoid β] : let _inst : add_comm_monoid α := equiv.add_comm_monoid e; [_inst_3 : distrib_mul_action R β] → distrib_mul_action R α := fun (_inst_3 : distrib_mul_action R β) => let _inst_4 : add_comm_monoid α := equiv.add_comm_monoid e; distrib_mul_action.mk sorry sorry /-- Transfer `semimodule` across an `equiv` -/ protected def semimodule {α : Type u} {β : Type v} (R : Type u_1) [semiring R] (e : α ≃ β) [add_comm_monoid β] : let _inst : add_comm_monoid α := equiv.add_comm_monoid e; [_inst_3 : semimodule R β] → semimodule R α := let _inst : add_comm_monoid α := equiv.add_comm_monoid e; fun (_inst_3 : semimodule R β) => semimodule.mk sorry sorry /-- An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β` where the `R`-module structure on `α` is the one obtained by transporting an `R`-module structure on `β` back along `e`. -/ def linear_equiv {α : Type u} {β : Type v} (R : Type u_1) [semiring R] (e : α ≃ β) [add_comm_monoid β] [semimodule R β] : let _inst : add_comm_monoid α := equiv.add_comm_monoid e; let _inst_4 : semimodule R α := equiv.semimodule R e; linear_equiv R α β := let _inst : add_comm_monoid α := equiv.add_comm_monoid e; let _inst_4 : semimodule R α := equiv.semimodule R e; linear_equiv.mk (add_equiv.to_fun (add_equiv e)) sorry sorry (add_equiv.inv_fun (add_equiv e)) sorry sorry /-- Transfer `algebra` across an `equiv` -/ protected def algebra {α : Type u} {β : Type v} (R : Type u_1) [comm_semiring R] (e : α ≃ β) [semiring β] : let _inst : semiring α := equiv.semiring e; [_inst_3 : algebra R β] → algebra R α := let _inst : semiring α := equiv.semiring e; fun (_inst_3 : algebra R β) => ring_hom.to_algebra' (ring_hom.comp (↑(ring_equiv.symm (ring_equiv e))) (algebra_map R β)) sorry /-- An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β` where the `R`-algebra structure on `α` is the one obtained by transporting an `R`-algebra structure on `β` back along `e`. -/ def alg_equiv {α : Type u} {β : Type v} (R : Type u_1) [comm_semiring R] (e : α ≃ β) [semiring β] [algebra R β] : let _inst : semiring α := equiv.semiring e; let _inst_4 : algebra R α := equiv.algebra R e; alg_equiv R α β := let _inst : semiring α := equiv.semiring e; let _inst_4 : algebra R α := equiv.algebra R e; alg_equiv.mk (ring_equiv.to_fun (ring_equiv e)) (ring_equiv.inv_fun (ring_equiv e)) sorry sorry sorry sorry sorry end equiv namespace ring_equiv protected theorem local_ring {A : Type u_1} {B : Type u_2} [comm_ring A] [local_ring A] [comm_ring B] (e : A ≃+* B) : local_ring B := local_of_surjective (↑e) (equiv.surjective (to_equiv e))
c325db71578813bb8d1cf4de1c3360da68e518eb
43390109ab88557e6090f3245c47479c123ee500
/src/Euclid_old/tarski_5.lean
d05e031beb5e5783e14812d34d95c38ff4cbe5ee
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,101
lean
import Euclid.tarski_4 open classical set namespace Euclidean_plane variables {point : Type} [Euclidean_plane point] local attribute [instance] prop_decidable -- Line Reflections noncomputable def mid (a b : point) : point := classical.some (eight22 a b) theorem ten1 (a b : point) : M a (mid a b) b := (classical.some_spec (eight22 a b)).1 @[simp] theorem mid.refl (a : point) : mid a a = a := (seven3.1 $ ten1 a a).symm theorem mid.symm (a b : point) : mid a b = mid b a := seven17 (ten1 a b) (ten1 b a).symm @[simp] theorem mid_to_Sa (a b : point) : S (mid a b) a = b := (seven6 $ ten1 a b).symm @[simp] theorem mid_to_Sb (a b : point) : S (mid a b) b = a := mid.symm b a ▸ mid_to_Sa b a @[simp] theorem mid_of_S (a b : point) : mid b (S a b) = a := seven17 (ten1 b (S a b)) (seven5 a b) theorem mid.neq {a b : point} : a ≠ b → mid a b ≠ a := --λ h h1, h ((seven11 a) ▸ h1 ▸ mid_to_Sa a b) begin intros h h1, apply h, suffices : eqd (mid a b) a (mid a b) b, rw h1 at this, exact id_eqd this.symm, exact (ten1 a b).2 end theorem ten2 {p : point} {A : set point} (h : line A) (h_1 : p ∉ A) : ∃! q, mid p q ∈ A ∧ perp A (l p q) := begin rcases h with ⟨a, b, h₁, h₂⟩, rw h₂ at *, cases eight18 (six14 h₁) h_1 with x hx, apply exists_unique.intro (S x p), split, rw seven17 (ten1 p (S x p)) (seven5 x p), exact hx.1.1, apply (eight14f hx.1.2.symm (or.inl (seven5 x p).1) _).symm, intro h_2, have h1 : p = x := seven10.1 h_2.symm, subst x, exact h_1 hx.1.1, intros y hy, have h1 : p ≠ y, intro h_2, rw [←h_2, mid.refl p] at hy, exact h_1 hy.1, have h2 := ten1 p y, have h3 : mid p y = x, apply hx.2, refine ⟨hy.1,_⟩, suffices : l p y = l p (mid p y), rw ←this, exact hy.2, apply six18 (six14 h1), intro h_2, rw ←h_2 at h2, exact h1 (id_eqd h2.2.symm), simp, right, left, exact h2.1.symm, rw h3 at *, exact unique_of_exists_unique (seven4 x p) h2 (seven5 x p) end noncomputable def Sl {A : set point} (h : line A) (a : point) : point := if h1 : a ∉ A then classical.some (ten2 h h1) else a theorem ten3a {A : set point} (h : line A) {a : point} (h1 : a ∉ A) : mid a (Sl h a) ∈ A ∧ perp A (l a (Sl h a)) := begin unfold Sl, rw dif_pos h1, exact (classical.some_spec (ten2 h h1)).1 end theorem ten3b {A : set point} (h : line A) {a : point} (h1 : a ∈ A) : Sl h a = a := begin unfold Sl, have h2 : ¬a ∉ A, intro h_1, contradiction, rw dif_neg h2 end theorem Sl.symm {a b : point} (h : line (l a b)) (p : point) : Sl h p = Sl h.symm p := begin cases em (p ∈ l a b), rw ten3b h h_1, suffices : p ∈ l b a, rw ten3b h.symm this, simpa [six17 a b] using h_1, apply unique_of_exists_unique (ten2 h h_1), exact ten3a h h_1, have h_2 : p ∉ l b a, rwa six17, have h2 := ten3a h.symm h_2, rwa six17 a b end theorem ten3c {A : set point} (h : line A) {a : point} : a ∉ A → Sl h a ∉ A := begin intro h1, have h2 := ten3a h h1, cases em (a = Sl h a), rwa ←h_1, intro h3, apply h1, have h4 := ten1 a (Sl h a), suffices : A = l (Sl h a) (mid a (Sl h a)), rw this, left, exact h4.1.symm, apply six18 h, intro h_2, apply h_1, rw ←h_2 at h4, exact id_eqd h4.2.flip, exact h3, exact h2.1 end theorem ten3d {A : set point} (h : line A) (a : point) : Sl h a = S (mid a (Sl h a)) a := begin exact (mid_to_Sa _ _).symm end theorem ten3e {A : set point} (h : line A) (a : point) : mid a (Sl h a) ∈ A := begin cases em (a ∈ A), rw ten3b h h_1, simpa, exact (ten3a h h_1).1 end @[simp] theorem ten5 {A : set point} (h : line A) (a : point) : Sl h (Sl h a) = a := begin cases em (a ∈ A), have h1 := ten3b h h_1, rwa h1, have h1 := ten3a h h_1, have h2 : Sl h a ∉ A, exact ten3c h h_1, rw [mid.symm, six17] at h1, apply unique_of_exists_unique (ten2 h h2), exact ten3a h h2, exact h1 end theorem ten4 {A : set point} {h : line A} {p q : point} : Sl h p = q ↔ Sl h q = p := begin split; {intro h1, rw ←h1, simp} end theorem ten6 {A : set point} (h : line A) (p : point) : ∃! q, Sl h q = p := begin apply exists_unique.intro, exact ten5 h p, intros y hy, exact (ten4.1 hy).symm end theorem ten7 {A : set point} {h : line A} {p q : point} : Sl h p = Sl h q → p = q := begin intro h1, rw ←(ten4.1 h1), simp end theorem ten8 {A : set point} (h : line A) {a : point} : Sl h a = a ↔ a ∈ A := begin split, intro h1, by_contradiction h_1, apply h_1, have h2 := ten3a h h_1, rw h1 at *, simp at h2, exact h2.1, intro h1, exact ten3b h h1 end theorem ten9 {A : set point} (h : line A) {a : point} : a ∉ A → perp A (l a (mid a (Sl h a))) := begin intro h1, have h2 := ten3a h h1, suffices : l a (Sl h a) = l a (mid a (Sl h a)), rw ←this, exact h2.2, have h3 : a ≠ Sl h a, intro h_1, apply h1, exact (ten8 h).1 h_1.symm, have h4 := ten1 a (Sl h a), apply six18 (six14 h3), intro h_1, apply h3, rw ←h_1 at h4, exact id_eqd h4.2.symm, simp, right, left, exact h4.1.symm end theorem ten10 {A : set point} (h : line A) (p q : point) : eqd p q (Sl h p) (Sl h q) := begin rw [ten3d h p, ten3d h q], generalize h1 : mid p (Sl h p) = x, generalize h2 : mid q (Sl h q) = y, generalize h3 : mid x y = z, have h4 := mid_to_Sa x y, rw h3 at h4, have h5 := seven5 x p, have h6 := (seven14 z).1 h5, rw h4 at h6, have h7 := seven6 h6, have h8 : eqd q (S z p) (S y q) (S z (S x p)), rw h7, apply seven13, have h9 : R z x p, cases em (p ∈ A), rw (ten3b h h_1) at h1, simp at h1, subst p, simp, have h_2 : xperp x A (l p x), rw ←h1, exact eight15 (ten9 h h_1) (ten3e h p) (six17b p (mid p (Sl h p))), apply h_2.2.2.2.2, apply six27 h, exact ten3e h p, exact ten3e h q, rw [h1, h2, ←h3], exact (ten1 x y).1, simp, have h10 : R z y q, cases em (q ∈ A), rw (ten3b h h_1) at h2, simp at h2, subst q, simp, have h_2 : xperp y A (l q y), rw ←h2, exact eight15 (ten9 h h_1) (ten3e h q) (six17b q (mid q (Sl h q))), apply h_2.2.2.2.2, apply six27 h, exact ten3e h q, exact ten3e h p, rw [h2, h1, ←h3], exact (ten1 x y).1.symm, simp, unfold R at *, have h11 : afs (S z p) z p q (S z (S x p)) z (S x p) (S y q), repeat {split}, exact (seven5 z p).1.symm, exact (seven5 z (S x p)).1.symm, suffices : eqd (S z p) (S z z) (S z (S x p)) (S z z), simp at this, exact this, exact (seven16 z).1 h9.flip, exact h9, exact h8.flip, exact h10, cases em (S z p = z), have h12 : p = z, exact seven9 (eq.trans h_1 (seven11 z).symm), have h13 : (S x p) = z, rw ←h12 at *, exact id_eqd h9.symm.flip, exact h13.symm ▸ h12.symm ▸ h10, exact afive_seg h11 h_1 end theorem ten11a {A : set point} (h : line A) {a b c : point} : B a b c ↔ B (Sl h a) (Sl h b) (Sl h c) := begin split, intro h1, apply four6 h1, repeat {split}; exact ten10 h _ _, intro h1, rw ←ten5 h a, rw ←ten5 h b, rw ←ten5 h c, apply four6 h1, repeat {split}; exact ten10 h _ _ end theorem ten11b {A : set point} (h : line A) {a b c d : point} : eqd a b c d ↔ eqd (Sl h a) (Sl h b) (Sl h c) (Sl h d) := begin split, intro h1, exact (ten10 h a b).symm.trans (h1.trans (ten10 h c d)), intro h1, have h2 := (ten10 h (Sl h a) (Sl h b)).symm.trans (h1.trans (ten10 h (Sl h c) (Sl h d))), simpa using h2 end theorem ten12a {a b p : point} (h : line (l a b)) : R a b p → b = mid p (Sl h p) := begin intro h1, cases em (p ∈ l a b), cases eight9 h1 h_1, subst b, exfalso, exact six13a a h, subst p, suffices : Sl h b = b, rw this, simp, apply ten3b h (six17b a b), suffices : S b p = Sl h p, rw ←this, exact (mid_of_S b p).symm, apply eq.symm, apply unique_of_exists_unique (ten2 h h_1), exact ten3a h h_1, split, rw mid_of_S, simp, have h3 : p ≠ b, intro h_2, apply h_1, subst p, simp, suffices : l p (S b p) = l p b, rw this, suffices : xperp b (l a b) (l p b), constructor, exact this, apply eight13.2, split, exact h, split, exact six14 h3, split, simp, split, simp, existsi [a, p], split, simp, split, simp, split, exact six13 h, split, exact h3, exact h1, apply six18 _ h3, simp, right, left, exact (seven5 b p).1.symm, apply six14, intro h_2, apply h3, exact (seven10.1 h_2.symm) end theorem ten12b {a b c : point} (h : line (l a b)) : R a b c → c = (Sl h (S b c)) := begin intro h1, have h2 : b = mid c (Sl h c), exact ten12a h h1, suffices : S b c = Sl h c, rw this, simp, suffices : S (mid c (Sl h c)) c = Sl h c, rwa ←h2 at this, exact mid_to_Sa c (Sl h c) end theorem ten12c {a b c a' : point} : R a b c → R a' b c → eqd a b a' b → eqd a c a' c := begin intros h h1 h2, generalize h3 : mid a a' = z, have h4 : R b z a, unfold R, rw ←h3, rw mid_to_Sa, exact h2.flip, cases em (b = c), subst b, exact h2, cases em (b = z), subst z, have h5 := six14 (ne.symm h_1), have h6 : a' = Sl h5 a, suffices : a = S b a', rw this, exact ten12b h5 h1.symm, rw [h_2, mid.symm], exact (mid_to_Sa a' a).symm, have h7 : c = Sl h5 c, suffices : c ∈ l c b, exact (ten3b h5 this).symm, simp, rw h6, simpa [h7.symm] using (ten10 h5 a c), have h5 := six14 h_2, have h6 : a = (Sl h5 a'), rw [(mid_to_Sa a a').symm, h3], exact ten12b h5 h4, have h7 : b = Sl h5 b, suffices : b ∈ l b z, exact (ten3b h5 this).symm, simp, have h8 : eqd a c a (S b c), unfold R at h, exact h, cases em (a = a'), subst a', exact eqd.refl a c, have h9 : R z b c, unfold R, apply four17 h_3, rw ←h3, right, left, exact (ten1 a a').1.symm, exact h8, unfold R at h1, exact h1, have h10 : (S b c) = Sl h5 c, rw Sl.symm, rw ten4.1, apply eq.symm, exact ten12b _ h9, apply h8.trans, apply eqd.symm, rw [h6, h10], exact ten10 h5 a' c end theorem ten12 {a b c a' b' c' : point} : R a b c → R a' b' c' → eqd a b a' b' → eqd b c b' c' → eqd a c a' c' := begin intros h h1 h2 h3, generalize h4 : mid b b' = x, have h5 : b = S x b', rw [←h4, mid.symm], apply eq.symm, exact mid_to_Sa b' b, have h6 : cong a' b' c' (S x a') b (S x c'), rw h5, exact seven16a x, have h7 : R (S x a') b (S x c'), exact eight10 h1 h6, apply eqd.trans _ h6.2.2.symm, generalize h8 : mid c (S x c') = y, have h9 : R b y c, unfold R, rw ←h8, rw mid_to_Sa, exact h3.trans h6.2.1, cases em (b = y), subst y, have h10 : (S b (S x c')) = c, rw [h_1, mid.symm], exact mid_to_Sa (S x c') c, have h11 : cong (S x a') b (S x c') (S b (S x a')) b c, rw ←h10, suffices : cong (S x a') b (S x c') (S b (S x a')) (S b b) (S b (S x c')), simpa [this], exact seven16a b, apply eqd.trans _ h11.2.2.symm, apply ten12c h, exact eight10 h7 h11, exact h2.trans (h6.1.trans h11.1), have h10 := six14 h_1, have h11 : c = Sl h10 (S x c'), rw [←mid_to_Sa c (S x c'), h8], exact ten12b h10 h9, have h12 : b = Sl h10 b, suffices : b ∈ l b y, exact (ten3b h10 this).symm, simp, have h13 : cong (S x a') b (S x c') (Sl h10 (S x a')) (Sl h10 b) (Sl h10 (S x c')), repeat {split}; exact ten10 h10 _ _, rw [←h11, ←h12] at h13, apply eqd.trans _ h13.2.2.symm, exact ten12c h (eight10 h7 h13) (h2.trans (h6.1.trans h13.1)) end theorem ten14 {A : set point} (h : line A) {a : point} : a ∉ A → Bl a A (Sl h a) := begin intro h1, split, exact h, split, exact h1, split, exact ten3c h h1, constructor, split, exact (ten3a h h1).1, exact (ten1 a (Sl h a)).1 end theorem ten15 {A : set point} (h : line A) {a q : point} : a ∈ A → q ∉ A → ∃ p, perp A (l p a) ∧ side A p q := begin intros h1 h2, cases six22 h h1 with b hb, cases nine10 h h2 with c hc, rcases eight21 hb.1 c with ⟨p, t, ht⟩, existsi p, split, rw hb.2, exact ht.1, existsi c, split, split, exact h, split, intro h_1, apply eight14a ht.1, apply six18, rwa hb.2 at h, exact six13 (eight14e ht.1).2, rwa hb.2 at h_1, simp, split, exact hc.2.2.1, existsi t, split, rw hb.2, exact ht.2.1, exact ht.2.2.symm, exact hc end theorem ten16 {a b c p a' b' : point} : ¬col a b c → ¬col a' b' p → eqd a b a' b' → ∃! c', cong a b c a' b' c' ∧ side (l a' b') c' p := begin intros h h1 h2, apply exists_unique_of_exists_of_unique, cases eight18 (six14 (six26 h).1) h with x hx, cases four14 hx.1.1 h2 with x' hx', have h3 : col a' b' x', exact four13 hx.1.1 hx', cases ten15 (six14 (six26 h1).1) h3 h1 with q hq, have h4 : x ≠ c, intro h_1, subst x, exact h hx.1.1, cases six11 (six13 (eight14e hq.1).2) h4 with c' hc', constructor, have h5 : cong a b c a' b' c', split, exact h2, have h5 : xperp x (l a b) (l c x), exact eight15 hx.1.2 hx.1.1 (six17b c x), have h6 : xperp x' (l a' b') (l c' x'), suffices : perp (l a' b') (l c' x'), exact eight15 this h3 (six17b c' x'), suffices : l q x' = l c' x', rw this at hq, exact hq.1, apply six18 (eight14e hq.1).2, intro h_1, apply h4, subst c', exact id_eqd hc'.1.2.symm, exact (four11 (six4.1 hc'.1.1).1).2.2.2.2, simp, split, have h7 : R b x c, simp [h5.2.2.2.2], have h8 : R b' x' c', simp [h6.2.2.2.2], exact ten12 h7 h8 hx'.2.1 hc'.1.2.symm, have h7 : R a x c, simp [h5.2.2.2.2], have h8 : R a' x' c', simp [h6.2.2.2.2], exact ten12 h7 h8 hx'.2.2 hc'.1.2.symm, split, exact h5, apply side.trans _ hq.2, apply nine12 (six14 (six26 h1).1) h3 hc'.1.1, intro h_1, exact h (four13 h_1 h5.symm), intros c' c'' hc' hc'', have h3 := hc'.1.symm.trans hc''.1, have h4 := hc'.2.trans hc''.2.symm, have h5 := six14 (six26 h1).1, generalize h6 : Sl h5 c'' = c₁, have h7 : Bl c'' (l a' b') c₁, rw ←h6, exact ten14 h5 (nine11 h4).2.2, have h8 : Bl c' (l a' b') c₁, exact (nine8 h7).2 h4.symm, cases h8.2.2.2 with t ht, have h9 : cong a' b' c' a' b' c₁, apply h3.trans, have h_1 : a' = Sl h5 a', apply (ten3b h5 _).symm, simp, have h_2 : b' = Sl h5 b', apply (ten3b h5 _).symm, simp, have h_3 : cong a' b' c'' (Sl h5 a') (Sl h5 b') c₁, rw ←h6, repeat {split}; exact ten10 h5 _ _, simpa [h_2.symm, h_1.symm] using h_3, have h10 : c₁ = S t c', suffices : M c' t c₁, exact unique_of_exists_unique (seven4 t c') this (seven5 t c'), split, exact ht.2, exact four17 (six26 h1).1 ht.1 h9.2.2 h9.2.1, suffices : Sl h5 c' = c₁, exact ten7 (this.trans h6.symm), apply unique_of_exists_unique (ten2 h5 h8.2.1), exact ten3a h5 h8.2.1, split, rw [h10, mid_of_S], exact ht.1, existsi t, apply eight13.2, split, exact six14 (six26 h1).1, split, exact six14 (nine2 h8), split, exact ht.1, split, right, left, exact ht.2.symm, cases em (a' = t), have h_2 : b' ≠ t, intro h_2, exact (six26 h1).1 (h_1.trans h_2.symm), existsi [b', c'], split, simp, split, simp, split, exact h_2, split, intro h_3, subst h_3, exact h8.2.1 ht.1, unfold R, rw ←h10, exact h9.2.1, existsi [a', c'], split, simp, split, simp, split, exact h_1, split, intro h_1, subst t, exact h8.2.1 ht.1, unfold R, rw ←h10, exact h9.2.2 end -- Angles def eqa (a b c d e f : point) : Prop := a ≠ b ∧ c ≠ b ∧ d ≠ e ∧ f ≠ e ∧ ∃ a' c' d' f', B b a a' ∧ eqd a a' e d ∧ B b c c' ∧ eqd c c' e f ∧ B e d d' ∧ eqd d d' b a ∧ B e f f' ∧ eqd f f' b c ∧ eqd a' c' d' f' theorem eleven3a {a b c d e f : point} : eqa a b c d e f → ∃ a' c' d' f', sided b a' a ∧ sided b c' c ∧ sided e d' d ∧ sided e f' f ∧ cong a' b c' d' e f' := begin unfold eqa, intro h, rcases h.2.2.2.2 with ⟨a', c', d', f', h1⟩, existsi [a', c', d', f'], split, exact (six7 h1.1 h.1).symm, split, exact (six7 h1.2.2.1 h.2.1).symm, split, exact (six7 h1.2.2.2.2.1 h.2.2.1).symm, split, exact (six7 h1.2.2.2.2.2.2.1 h.2.2.2.1).symm, split, exact two5 (two11 h1.1.symm h1.2.2.2.2.1 (two4 h1.2.1) (two4 h1.2.2.2.2.2.1.symm)), split, exact two5 (two11 h1.2.2.1 h1.2.2.2.2.2.2.1.symm (two5 h1.2.2.2.2.2.2.2.1.symm) (two5 h1.2.2.2.1)), exact h1.2.2.2.2.2.2.2.2 end theorem eleven4a {a b c d e f : point} : (∃ a' c' d' f', sided b a' a ∧ sided b c' c ∧ sided e d' d ∧ sided e f' f ∧ cong a' b c' d' e f') → a ≠ b ∧ c ≠ b ∧ d ≠ e ∧ f ≠ e ∧ ∀ {a' c' d' f'}, sided b a' a → sided b c' c → sided e d' d → sided e f' f → eqd b a' e d' → eqd b c' e f' → eqd a' c' d' f' := begin intro h, rcases h with ⟨a', c', d', f', h1⟩, repeat {split}, exact h1.1.2.1, exact h1.2.1.2.1, exact h1.2.2.1.2.1, exact h1.2.2.2.1.2.1, intros a1 c1 d1 f1 h2 h3 h4 h5 h6 h7, have h8 : cong b a' a1 e d' d1, exact six10 (h1.1.trans h2.symm) (h1.2.2.1.trans h4.symm) h1.2.2.2.2.1.flip h6, have h9 : eqd a1 c' d1 f', suffices : fs b a' a1 c' e d' d1 f', exact four16 this h1.1.1.symm, repeat {split}, exact (four11 (six4.1 (h1.1.trans h2.symm)).1).2.1, exact h8.1, exact h8.2.1, exact h8.2.2, exact h1.2.2.2.2.2.1, exact h1.2.2.2.2.2.2, suffices : fs b c' c1 a1 e f' f1 d1, exact (four16 this h1.2.1.1.symm).flip, repeat {split}, exact (four11 (six4.1 (h1.2.1.trans h3.symm)).1).2.1, exact h1.2.2.2.2.2.1, exact (six10 (h1.2.1.trans h3.symm) (h1.2.2.2.1.trans h5.symm) h1.2.2.2.2.2.1 h7).2.1, exact h7, exact h6, exact h9.flip end theorem eleven2a {a b c d e f : point} : (a ≠ b ∧ c ≠ b ∧ d ≠ e ∧ f ≠ e ∧ ∀ {a' c' d' f'}, sided b a' a → sided b c' c → sided e d' d → sided e f' f → eqd b a' e d' → eqd b c' e f' → eqd a' c' d' f') → eqa a b c d e f := begin intro h, unfold eqa, split, exact h.1, split, exact h.2.1, split, exact h.2.2.1, split, exact h.2.2.2.1, cases seg_cons a e d b with a' ha', cases seg_cons c e f b with c' hc', cases seg_cons d b a e with d' hd', cases seg_cons f b c e with f' hf', existsi [a', c', d', f'], repeat {split}, exact ha'.1, exact ha'.2, exact hc'.1, exact hc'.2, exact hd'.1, exact hd'.2, exact hf'.1, exact hf'.2, apply h.2.2.2.2, exact (six7 ha'.1 h.1).symm, exact (six7 hc'.1 h.2.1).symm, exact (six7 hd'.1 h.2.2.1).symm, exact (six7 hf'.1 h.2.2.2.1).symm, exact two5 (two11 ha'.1 hd'.1.symm (two5 hd'.2.symm) (two5 ha'.2)), exact two5 (two11 hc'.1 hf'.1.symm (two5 hf'.2.symm) (two5 hc'.2)) end theorem eleven3 {a b c d e f : point} : eqa a b c d e f ↔ ∃ a' c' d' f', sided b a' a ∧ sided b c' c ∧ sided e d' d ∧ sided e f' f ∧ cong a' b c' d' e f' := ⟨λ h, eleven3a h, λ h, eleven2a (eleven4a h)⟩ theorem eleven4 {a b c d e f : point} : eqa a b c d e f ↔ a ≠ b ∧ c ≠ b ∧ d ≠ e ∧ f ≠ e ∧ ∀ {a' c' d' f'}, sided b a' a → sided b c' c → sided e d' d → sided e f' f → eqd b a' e d' → eqd b c' e f' → eqd a' c' d' f' := ⟨λ h, eleven4a (eleven3a h), λ h, eleven2a h⟩ lemma eleven5 {a b c d e f : point} : eqa a b c d e f ↔ ∃ d' f', sided e d' d ∧ sided e f' f ∧ cong a b c d' e f' := begin split, intro h, cases exists_of_exists_unique (six11 h.2.2.1 h.1.symm) with d' hd, cases exists_of_exists_unique (six11 h.2.2.2.1 h.2.1.symm) with f' hf, refine ⟨d', f', hd.1, hf.1, _⟩, exact ⟨hd.2.symm.flip, hf.2.symm, (eleven4.1 h).2.2.2.2 (six5 h.1) (six5 h.2.1) hd.1 hf.1 hd.2.symm hf.2.symm⟩, rintros ⟨d', f', h, h1, h2⟩, apply eleven3.2 ⟨a, c, d', f', _, _, h, h1, h2⟩, exact six5 (two7 h2.1.symm h.1), exact six5 (two7 h2.2.1.symm.flip h1.1) end theorem eqa.refl {a b c : point} : a ≠ b → c ≠ b → eqa a b c a b c := begin intros h h1, rw eleven3, existsi [a, c, a, c], simp [six5 h, six5 h1] end theorem eqa.symm {a b c d e f : point} : eqa a b c d e f → eqa d e f a b c := begin unfold eqa, rintros ⟨h, h1, h2, h3, a', c', d', f', h4, h5, h6, h7, h8, h9, h10, h11, h12⟩, simp [*, -exists_and_distrib_left], existsi [d', f', a', c'], simp [*, h12.symm] end theorem eqa.trans {a b c d e f p q r : point} : eqa a b c d e f → eqa d e f p q r → eqa a b c p q r := begin intros h g, have h1 := h, rw eleven3 at h1, rcases h1 with ⟨a', c', d', f', h1, h2, h3, h4, h5, h6, h7⟩, rw eleven4 at g, cases seg_cons a' p q b with a₁ ha, cases seg_cons c' r q b with c₁ hc, cases seg_cons d' p q e with d₁ hd, cases seg_cons f' r q e with f₁ hf, cases seg_cons p d' e q with p₁ hp, cases seg_cons r f' e q with r₁ hr, have h8 : eqd b a₁ e d₁, exact two11 ha.1 hd.1 h5.flip (ha.2.trans hd.2.symm), have h9 : eqd b c₁ e f₁, exact two11 hc.1 hf.1 h6 (hc.2.trans hf.2.symm), have h10 : eqd e d₁ q p₁, exact two5 (two11 hd.1 hp.1.symm hp.2.symm.flip hd.2), have h11 : eqd e f₁ q r₁, exact two5 (two11 hf.1 hr.1.symm hr.2.symm.flip hf.2), have h12 : sided b a₁ a, exact six7a ha.1 h1, have h13 : sided b c₁ c, exact six7a hc.1 h2, have h14 : sided e d₁ d, exact six7a hd.1 h3, have h15 : sided e f₁ f, exact six7a hf.1 h4, have h16 : sided q p₁ p, exact (six7 hp.1 g.2.2.1).symm, have h17 : sided q r₁ r, exact (six7 hr.1 g.2.2.2.1).symm, have h18 := g.2.2.2.2 h14 h15 h16 h17 h10 h11, rw eleven3, existsi [a₁, c₁, p₁, r₁], simp *, split, exact (h8.trans h10).flip, split, exact h9.trans h11, apply eqd.trans _ h18, rw eleven4 at h, exact h.2.2.2.2 h12 h13 h14 h15 h8 h9 end theorem eleven6 {a b c : point} : a ≠ b → c ≠ b → eqa a b c c b a := begin intros h h1, cases seg_cons a c b b with a' ha, cases seg_cons c a b b with c' hc, rw eleven3, existsi [a', c', c', a'], simp [(six7 ha.1 h).symm, (six7 hc.1 h1).symm], unfold cong, have h3 : eqd b a' c' b, exact two11 ha.1 hc.1.symm hc.2.symm.flip ha.2, split, exact two4 h3, split, exact two4 h3.symm, exact two5 (eqd.refl a' c') end theorem eleven7 {a b c d e f : point} : eqa a b c d e f → eqa c b a d e f := λ h, (eleven6 h.1 h.2.1).symm.trans h theorem eleven8 {a b c d e f : point} : eqa a b c d e f → eqa a b c f e d := λ h, h.trans (eleven6 h.2.2.1 h.2.2.2.1) theorem eqa.flip {a b c d e f : point} : eqa a b c d e f → eqa c b a f e d := λ h, eleven8 (eleven7 h) theorem eleven9 {a b c a' c' : point} : sided b a' a → sided b c' c → eqa a b c a' b c' := begin intros h h1, rw eleven3, existsi [a', c', a', c'], simp [h, h1, six5 h.1, six5 h1.1] end theorem eleven10 {a b c d e f a' c' d' f' : point} : eqa a b c d e f → sided b a' a → sided b c' c → sided e d' d → sided e f' f → eqa a' b c' d' e f' := begin intros h h1 h2 h3 h4, exact (eleven9 h1 h2).symm.trans (h.trans (eleven9 h3 h4)) end theorem eleven11 {a b c d e f : point} : a ≠ b → c ≠ b → cong a b c d e f → eqa a b c d e f := λ h h1 h2, eleven3.2 ⟨a, c, d, f, (six5 h), (six5 h1), (six5 (two7 h2.1 h)), (six5 (two7 h2.2.1.flip h1)), h2⟩ theorem eleven12 {a b c : point} (p : point): a ≠ b → c ≠ b → eqa a b c (S p a) (S p b) (S p c) := begin intros h h1, rw eleven3, existsi [a, c, (S p a), (S p c)], simp [six5 h, six5 h1, six5 (seven9a p h), six5 (seven9a p h1), seven16a p] end theorem eleven13 {a b c d e f a' d' : point} : eqa a b c d e f → a' ≠ b → B a b a' → d' ≠ e → B d e d' → eqa a' b c d' e f := begin intros h h1 h2 h3 h4, rw eleven3 at h, rcases h with ⟨a₁, c₁, d₁, f₁, h⟩, suffices : eqa (S b a₁) b c (S e d₁) e f, apply eleven10 this, split, exact h1, split, exact this.1, suffices : B a b (S b a₁), exact five2 h.1.2.1 h2 this, exact (six6 (seven5 b a₁).1.symm h.1).symm, exact six5 h.2.1.2.1, split, exact h3, split, exact this.2.2.1, suffices : B d e (S e d₁), exact five2 h.2.2.1.2.1 h4 this, exact (six6 (seven5 e d₁).1.symm h.2.2.1).symm, exact six5 h.2.2.2.1.2.1, rw eleven3, existsi [(S b a₁), c₁, (S e d₁), f₁], simp [six5 (seven12a h.1.1.symm).symm, h.2.1, six5 (seven12a h.2.2.1.1.symm).symm, h.2.2.2.1], split, exact (seven5 b a₁).2.symm.flip.trans (h.2.2.2.2.1.trans (seven5 e d₁).2.flip), split, exact h.2.2.2.2.2.1, suffices : afs a₁ b (S b a₁) c₁ d₁ e (S e d₁) f₁, exact afive_seg this h.1.1, repeat {split}, exact (seven5 b a₁).1, exact (seven5 e d₁).1, exact h.2.2.2.2.1, exact (seven5 b a₁).2.symm.trans (h.2.2.2.2.1.flip.trans (seven5 e d₁).2), exact h.2.2.2.2.2.2, exact h.2.2.2.2.2.1 end theorem eleven14 {a b c a' c' : point} : a ≠ b → c ≠ b → a' ≠ b → c' ≠ b → B a b a' → B c b c' → eqa a b c a' b c' := begin intros h h1 h2 h3 h4 h5, apply (eleven12 b h h1).trans, simp, suffices : sided b a' (S b a) ∧ sided b c' (S b c), exact eleven9 this.1 this.2, split, apply six3.2, split, exact h2, split, exact (seven12a h.symm).symm, existsi a, split, exact h, split, exact h4.symm, exact (seven5 b a).1.symm, apply six3.2, split, exact h3, split, exact (seven12a h1.symm).symm, existsi c, split, exact h1, split, exact h5.symm, exact (seven5 b c).1.symm end theorem eleven15a {a b c d e p : point} : ¬col a b c → ¬col d e p → ∃ f, eqa a b c d e f ∧ side (l e d) f p := begin intros h h1, cases exists_of_exists_unique (six11 (six26 h1).1 (six26 h).1.symm) with d' hd, have h2 : ¬col d' e p, intro h_1, have h_2 := (six4.1 hd.1).1, exact (four10 h1).2.2.1 (five4 hd.1.1.symm (four11 h_1).2.1 (four11 h_2).2.1), cases ten16 h h2 hd.2.symm.flip with f hf, dsimp at hf, existsi f, split, rw eleven3, existsi [a, c, d', f], simp [six5 (six26 h).1, six5 (six26 h).2.1.symm, hd.1, hf.1.1], apply six5, intro h_1, subst f, exact (six26 h).2.1 (id_eqd hf.1.1.2.1), have h3 : l e d = l d' e, exact six18 (six14 (six26 h1).1.symm) hd.1.1 (four11 (six4.1 hd.1).1).2.2.1 (six17a e d), rw h3, exact hf.1.2 end theorem eleven15b {a b c d e p : point} : ¬col a b c → ¬col d e p → ∀ {f1 f2}, eqa a b c d e f1 → side (l e d) f1 p → eqa a b c d e f2 → side (l e d) f2 p → sided e f1 f2 := begin intros h h1 f1 f2 h2 h3 h4 h5, cases exists_of_exists_unique (six11 (six26 h1).1 (six26 h).1.symm) with d' hd, have h6 : ¬col d' e p, intro h_1, have h_2 := (six4.1 hd.1).1, exact (four10 h1).2.2.1 (five4 hd.1.1.symm (four11 h_1).2.1 (four11 h_2).2.1), cases ten16 h h6 hd.2.symm.flip with f hf, dsimp at hf, have h7 : f1 ≠ e, intro h_1, subst f1, exact (nine11 h3).2.1 (six17a e d), have h8 : f2 ≠ e, intro h_1, subst f2, exact (nine11 h5).2.1 (six17a e d), cases exists_of_exists_unique (six11 h7 (six26 h).2.1) with f₁ h9, cases exists_of_exists_unique (six11 h8 (six26 h).2.1) with f₂ h10, have h11 : cong a b c d' e f₁, split, exact hf.1.1.1, split, exact h9.2.symm, suffices : eqa a b c d' e f₁, apply (eleven4.1 this).2.2.2.2 (six5 (six26 h).1) (six5 (six26 h).2.1.symm) (six5 hd.1.1) (six5 h9.1.1), exact hf.1.1.1.flip, exact h9.2.symm, exact h2.trans (eleven9 hd.1 h9.1), have h12 : cong a b c d' e f₂, split, exact hf.1.1.1, split, exact h10.2.symm, suffices : eqa a b c d' e f₂, apply (eleven4.1 this).2.2.2.2 (six5 (six26 h).1) (six5 (six26 h).2.1.symm) (six5 hd.1.1) (six5 h10.1.1), exact hf.1.1.1.flip, exact h10.2.symm, exact h4.trans (eleven9 hd.1 h10.1), have h13 : l e d = l d' e, exact six18 (six14 (six26 h1).1.symm) hd.1.1 (four11 (six4.1 hd.1).1).2.2.1 (six17a e d), have h14 : side (l d' e) f₁ p, rw h13 at *, exact (nine19a h3.symm (six17b d' e) h9.1.symm).symm, have h15 : side (l d' e) f₂ p, rw h13 at *, exact (nine19a h5.symm (six17b d' e) h10.1.symm).symm, have h16 : f₁ = f, apply hf.2, split, exact h11, exact h14, subst f₁, have h16 : f₂ = f, apply hf.2, split, exact h12, exact h15, subst f₂, exact h9.1.symm.trans h10.1 end theorem eleven15c {a b c x : point} : eqa a b c a b x → side (l a b) c x → sided b c x := begin intros h h1, have h2 : ¬col a b c, exact (nine11 h1).2.1, apply eleven15b h2 h2 (eqa.refl (six26 h2).1 (six26 h2).2.1.symm) (side.refla (four10 h2).2.1) h, rwa six17, exact h1.symm end theorem eleven16 {a b c a' b' c' : point} : a ≠ b → c ≠ b → a' ≠ b' → c' ≠ b' → R a b c → R a' b' c' → eqa a b c a' b' c' := begin intros h h1 h2 h3 h4 h5, cases exists_of_exists_unique (six11 h2 h.symm) with a₁ ha, cases exists_of_exists_unique (six11 h3 h1.symm) with c₁ hc, rw eleven3, existsi [a, c, a₁, c₁], simp [six5 h, six5 h1, ha.1, hc.1], refine ⟨ha.2.symm.flip, hc.2.symm, _⟩, apply ten12 h4, suffices : R a' b' c₁, apply eight3 this h2, exact (four11 (six4.1 ha.1).1).2.2.1, apply R.symm, apply eight3 h5.symm h3, exact (four11 (six4.1 hc.1).1).2.2.1, exact ha.2.symm.flip, exact hc.2.symm end theorem eleven17 {a b c a' b' c' : point} : R a b c → eqa a b c a' b' c' → R a' b' c' := begin intros h h1, rcases eleven5.1 h1 with ⟨a₁, c₁, ha, hc, h2⟩, apply eight3 _ ha.1 (four11 (six4.1 ha).1).2.1, exact (eight3 (eight10 h h2).symm hc.1 (four11 (six4.1 hc).1).2.1).symm end theorem eleven18 {a b c d : point} : B c b d → c ≠ b → d ≠ b → a ≠ b → (R a b c ↔ eqa a b c a b d) := begin intros h h1 h2 h3, split, intro h4, have h5 : R a b d, apply (eight3 h4.symm h1 _).symm, right, right, exact h.symm, exact eleven16 h3 h1 h3 h2 h4 h5, intro h4, rw eleven3 at h4, rcases h4 with ⟨a', c', a₁, d', h4⟩, have : a₁ = a', apply unique_of_exists_unique (six11 h3 h4.2.2.1.1.symm), split, exact h4.2.2.1, exact eqd.refl b a₁, split, exact h4.1, exact h4.2.2.2.2.1.flip, subst a₁, have : d' = (S b c'), apply unique_of_exists_unique (two12 b b c' c' h4.2.1.1), split, exact six8 h4.2.1 h4.2.2.2.1 h, exact h4.2.2.2.2.2.1.symm, split, exact (seven5 b c').1, exact (seven5 b c').2.symm, subst d', have h5 : R a' b c', unfold R, exact h4.2.2.2.2.2.2, exact eleven17 h5 (eleven9 h4.1.symm h4.2.1.symm) end theorem eleven19 {a b p q : point} : R b a p → R b a q → side (l a b) p q → sided a p q := begin intros h h1 h2, have h3 : ¬col b a p, exact (four10 (nine11 h2).2.1).2.1, have h4 : ¬col b a q, exact (four10 (nine11 h2).2.2).2.1, apply (eleven15b h3 h3), exact eqa.refl (six26 h3).1 (six26 h3).2.1.symm, exact side.refl (nine11 h2).1 (nine11 h2).2.1, exact eleven16 (six26 h3).1 (six26 h3).2.1.symm (six26 h4).1 (six26 h4).2.1.symm h h1, exact h2.symm end theorem eleven20 {a : point} {A P : set point} : line A → plane P → a ∈ A → A ⊆ P → ∃! B, B ⊆ P ∧ xperp a A B := begin intros h h1 h2 h3, cases six22 h h2 with b hb, cases (nine25 h1 (h3 h2) _ hb.1 ).2 with x hx, show b ∈ P, apply h3, rw hb.2, simp, rw hb.2 at *, have h4 : x ∉ l a b, apply nine28 (six14 hb.1), rwa hx at h1, cases ten15 h h2 h4 with c hc, have h5 : c ∈ P, rw hx, left, exact hc.2, apply exists_unique.intro (l c a), split, exact (nine25 h1 h5 (h3 h2) (six13 (eight14e hc.1).2)).1, exact eight15 hc.1 (six17a a b) (six17b c a), intros Y h6, have h7 : c ∉ l a b, intro h_1, apply eight14a hc.1, exact six18 (six14 hb.1) (six13 (eight14e hc.1).2) h_1 (six17a a b), have h8 : P = planeof a b c, apply nine26 h7 h1 _ _ h5, exact h3 (six17a a b), exact h3 (six17b a b), cases (six22 h6.2.2.1 h6.2.2.2.2.1) with y hy, have h9 : R b a c, exact (eight15 hc.1 (six17a a b) (six17b c a)).2.2.2.2 (six17b a b) (six17a c a), rw h8 at h6, have h10 : y ∈ Y, rw hy.2, simp, have h11 : R b a y, exact h6.2.2.2.2.2 (six17b a b) h10, rw hy.2 at *, cases (h6.1 h10), have h12 : sided a c y, exact eleven19 h9 h11 h_1.symm, exact six18 (six14 hy.1) (six13 (eight14e hc.1).2) (four11 (six4.1 h12).1).2.2.1 (six17a a y), cases h_1, exfalso, apply (eight14b h6.2), exact six18 h hy.1 (six17a a b) h_1, have h12 := six14 hb.1, have h13 : side (l a b) y (Sl h12 c), exact (nine8 h_1.symm).1 (ten14 h12 h7).symm, have h14 : side (l a b) y (S a c), have h_2 : S a c = Sl h12 c, have h_3 := ten12b h12.symm h9.flip, rw Sl.symm at h_3, simpa using h_3, rwa h_2, apply eq.symm, apply six18 (eight14e hc.1).2 hy.1 (six17b c a) (or.inl $ six6 (seven5 a c).1 (eleven19 h11 h9.flip h14).symm) end theorem eleven21a {a b c a' b' c' : point} (h : sided b a c) : eqa a b c a' b' c' ↔ sided b' a' c' := begin split, intro h1, rcases eleven5.1 h1 with ⟨a₁, c₁, ha, hc, h2⟩, suffices : sided b' a₁ c₁, exact ha.symm.trans (this.trans hc), apply six10a h ⟨h2.1.flip, _, h2.2.1⟩, exact (eleven4.1 h1).2.2.2.2 (six5 h1.1) (six5 h1.2.1) ha hc h2.1.flip h2.2.1, intro h1, cases exists_of_exists_unique (six11 h1.1 h.1.symm) with a₁ ha, apply eleven3.2 ⟨a, a, a₁, a₁, _ ⟩, simp [six5 h.1, h, ha.1, ha.1.trans h1], exact ⟨ha.2.symm.flip, ha.2.symm, two8 a a₁⟩ end theorem eleven21b {a b c a' b' c' : point} : B a b c → eqa a b c a' b' c' → B a' b' c' := begin intros h h1, rcases eleven5.1 h1 with ⟨a₁, c₁, ha, hc, h2⟩, exact six8 ha.symm hc.symm (four6 h h2) end theorem eleven21c {a b c a' b' c' : point} : a ≠ b → c ≠ b → a' ≠ b' → c' ≠ b' → B a b c → B a' b' c' → eqa a b c a' b' c' := begin intros h h1 h2 h3 h4 h5, cases exists_of_exists_unique (six11 h2 h.symm) with a₁ ha, cases exists_of_exists_unique (six11 h3 h1.symm) with c₁ hc, apply eleven3.2 ⟨a, c, a₁, c₁, (six5 h), (six5 h1), ha.1, hc.1, ha.2.symm.flip, hc.2.symm, _⟩, exact two11 h4 (six8 ha.1 hc.1 h5) ha.2.symm.flip hc.2.symm end theorem eleven21d {a b c a' b' c' : point} : col a b c → eqa a b c a' b' c' → col a' b' c' := begin intros h h1, cases six1 h, exact or.inl (eleven21b h_1 h1), exact (six4.1 ((eleven21a h_1).1 h1)).1 end end Euclidean_plane
6d70cf9179190ad7d9053a8b8106671be9919d41
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/bicategory/basic.lean
890c3299d03af00db5eaa89d58ddf99468ef9362
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
19,748
lean
/- Copyright (c) 2021 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import category_theory.isomorphism import tactic.slice /-! # Bicategories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define typeclass for bicategories. A bicategory `B` consists of * objects `a : B`, * 1-morphisms `f : a ⟶ b` between objects `a b : B`, and * 2-morphisms `η : f ⟶ g` beween 1-morphisms `f g : a ⟶ b` between objects `a b : B`. We use `u`, `v`, and `w` as the universe variables for objects, 1-morphisms, and 2-morphisms, respectively. A typeclass for bicategories extends `category_theory.category_struct` typeclass. This means that we have * a composition `f ≫ g : a ⟶ c` for each 1-morphisms `f : a ⟶ b` and `g : b ⟶ c`, and * a identity `𝟙 a : a ⟶ a` for each object `a : B`. For each object `a b : B`, the collection of 1-morphisms `a ⟶ b` has a category structure. The 2-morphisms in the bicategory are implemented as the morphisms in this family of categories. The composition of 1-morphisms is in fact a object part of a functor `(a ⟶ b) ⥤ (b ⟶ c) ⥤ (a ⟶ c)`. The definition of bicategories in this file does not require this functor directly. Instead, it requires the whiskering functions. For a 1-morphism `f : a ⟶ b` and a 2-morphism `η : g ⟶ h` between 1-morphisms `g h : b ⟶ c`, there is a 2-morphism `whisker_left f η : f ≫ g ⟶ f ≫ h`. Similarly, for a 2-morphism `η : f ⟶ g` between 1-morphisms `f g : a ⟶ b` and a 1-morphism `f : b ⟶ c`, there is a 2-morphism `whisker_right η h : f ≫ h ⟶ g ≫ h`. These satisfy the exchange law `whisker_left f θ ≫ whisker_right η i = whisker_right η h ≫ whisker_left g θ`, which is required as an axiom in the definition here. -/ namespace category_theory universes w v u open category iso /-- In a bicategory, we can compose the 1-morphisms `f : a ⟶ b` and `g : b ⟶ c` to obtain a 1-morphism `f ≫ g : a ⟶ c`. This composition does not need to be strictly associative, but there is a specified associator, `α_ f g h : (f ≫ g) ≫ h ≅ f ≫ (g ≫ h)`. There is an identity 1-morphism `𝟙 a : a ⟶ a`, with specified left and right unitor isomorphisms `λ_ f : 𝟙 a ≫ f ≅ f` and `ρ_ f : f ≫ 𝟙 a ≅ f`. These associators and unitors satisfy the pentagon and triangle equations. See https://ncatlab.org/nlab/show/bicategory. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters class bicategory (B : Type u) extends category_struct.{v} B := -- category structure on the collection of 1-morphisms: (hom_category : ∀ (a b : B), category.{w} (a ⟶ b) . tactic.apply_instance) -- left whiskering: (whisker_left {a b c : B} (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h) : f ≫ g ⟶ f ≫ h) (infixr ` ◁ `:81 := whisker_left) -- right whiskering: (whisker_right {a b c : B} {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c) : f ≫ h ⟶ g ≫ h) (infixl ` ▷ `:81 := whisker_right) -- associator: (associator {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) : (f ≫ g) ≫ h ≅ f ≫ (g ≫ h)) (notation `α_` := associator) -- left unitor: (left_unitor {a b : B} (f : a ⟶ b) : 𝟙 a ≫ f ≅ f) (notation `λ_` := left_unitor) -- right unitor: (right_unitor {a b : B} (f : a ⟶ b) : f ≫ 𝟙 b ≅ f) (notation `ρ_` := right_unitor) -- axioms for left whiskering: (whisker_left_id' : ∀ {a b c} (f : a ⟶ b) (g : b ⟶ c), f ◁ 𝟙 g = 𝟙 (f ≫ g) . obviously) (whisker_left_comp' : ∀ {a b c} (f : a ⟶ b) {g h i : b ⟶ c} (η : g ⟶ h) (θ : h ⟶ i), f ◁ (η ≫ θ) = f ◁ η ≫ f ◁ θ . obviously) (id_whisker_left' : ∀ {a b} {f g : a ⟶ b} (η : f ⟶ g), 𝟙 a ◁ η = (λ_ f).hom ≫ η ≫ (λ_ g).inv . obviously) (comp_whisker_left' : ∀ {a b c d} (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h'), (f ≫ g) ◁ η = (α_ f g h).hom ≫ f ◁ g ◁ η ≫ (α_ f g h').inv . obviously) -- axioms for right whiskering: (id_whisker_right' : ∀ {a b c} (f : a ⟶ b) (g : b ⟶ c), 𝟙 f ▷ g = 𝟙 (f ≫ g) . obviously) (comp_whisker_right' : ∀ {a b c} {f g h : a ⟶ b} (η : f ⟶ g) (θ : g ⟶ h) (i : b ⟶ c), (η ≫ θ) ▷ i = η ▷ i ≫ θ ▷ i . obviously) (whisker_right_id' : ∀ {a b} {f g : a ⟶ b} (η : f ⟶ g), η ▷ 𝟙 b = (ρ_ f).hom ≫ η ≫ (ρ_ g).inv . obviously) (whisker_right_comp' : ∀ {a b c d} {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d), η ▷ (g ≫ h) = (α_ f g h).inv ≫ η ▷ g ▷ h ≫ (α_ f' g h).hom . obviously) -- associativity of whiskerings: (whisker_assoc' : ∀ {a b c d} (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d), (f ◁ η) ▷ h = (α_ f g h).hom ≫ f ◁ (η ▷ h) ≫ (α_ f g' h).inv . obviously) -- exchange law of left and right whiskerings: (whisker_exchange' : ∀ {a b c} {f g : a ⟶ b} {h i : b ⟶ c} (η : f ⟶ g) (θ : h ⟶ i), f ◁ θ ≫ η ▷ i = η ▷ h ≫ g ◁ θ . obviously) -- pentagon identity: (pentagon' : ∀ {a b c d e} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e), (α_ f g h).hom ▷ i ≫ (α_ f (g ≫ h) i).hom ≫ f ◁ (α_ g h i).hom = (α_ (f ≫ g) h i).hom ≫ (α_ f g (h ≫ i)).hom . obviously) -- triangle identity: (triangle' : ∀ {a b c} (f : a ⟶ b) (g : b ⟶ c), (α_ f (𝟙 b) g).hom ≫ f ◁ (λ_ g).hom = (ρ_ f).hom ▷ g . obviously) -- The precedence of the whiskerings is higher than that of the composition `≫`. localized "infixr (name := bicategory.whisker_left) ` ◁ `:81 := bicategory.whisker_left" in bicategory localized "infixl (name := bicategory.whisker_right) ` ▷ `:81 := bicategory.whisker_right" in bicategory localized "notation (name := bicategory.associator) `α_` := bicategory.associator" in bicategory localized "notation (name := bicategory.left_unitor) `λ_` := bicategory.left_unitor" in bicategory localized "notation (name := bicategory.right_unitor) `ρ_` := bicategory.right_unitor" in bicategory namespace bicategory /-! ### Simp-normal form for 2-morphisms Rewriting involving associators and unitors could be very complicated. We try to ease this complexity by putting carefully chosen simp lemmas that rewrite any 2-morphisms into simp-normal form defined below. Rewriting into simp-normal form is also useful when applying (forthcoming) `coherence` tactic. The simp-normal form of 2-morphisms is defined to be an expression that has the minimal number of parentheses. More precisely, 1. it is a composition of 2-morphisms like `η₁ ≫ η₂ ≫ η₃ ≫ η₄ ≫ η₅` such that each `ηᵢ` is either a structural 2-morphisms (2-morphisms made up only of identities, associators, unitors) or non-structural 2-morphisms, and 2. each non-structural 2-morphism in the composition is of the form `f₁ ◁ f₂ ◁ f₃ ◁ η ▷ f₄ ▷ f₅`, where each `fᵢ` is a 1-morphism that is not the identity or a composite and `η` is a non-structural 2-morphisms that is also not the identity or a composite. Note that `f₁ ◁ f₂ ◁ f₃ ◁ η ▷ f₄ ▷ f₅` is actually `f₁ ◁ (f₂ ◁ (f₃ ◁ ((η ▷ f₄) ▷ f₅)))`. -/ restate_axiom whisker_left_id' restate_axiom whisker_left_comp' restate_axiom id_whisker_left' restate_axiom comp_whisker_left' restate_axiom id_whisker_right' restate_axiom comp_whisker_right' restate_axiom whisker_right_id' restate_axiom whisker_right_comp' restate_axiom whisker_assoc' restate_axiom whisker_exchange' restate_axiom pentagon' restate_axiom triangle' attribute [simp] pentagon triangle attribute [reassoc] whisker_left_comp id_whisker_left comp_whisker_left comp_whisker_right whisker_right_id whisker_right_comp whisker_assoc whisker_exchange pentagon triangle /- The following simp attributes are put in order to rewrite any 2-morphisms into normal forms. There are associators and unitors in the RHS in the several simp lemmas here (e.g. `id_whisker_left`), which at first glance look more complicated than the LHS, but they will be eventually reduced by the pentagon or the triangle identities, and more generally, (forthcoming) `coherence` tactic. -/ attribute [simp] whisker_left_id whisker_left_comp id_whisker_left comp_whisker_left id_whisker_right comp_whisker_right whisker_right_id whisker_right_comp whisker_assoc attribute [instance] hom_category variables {B : Type u} [bicategory.{w v} B] {a b c d e : B} @[simp, reassoc] lemma hom_inv_whisker_left (f : a ⟶ b) {g h : b ⟶ c} (η : g ≅ h) : f ◁ η.hom ≫ f ◁ η.inv = 𝟙 (f ≫ g) := by rw [←whisker_left_comp, hom_inv_id, whisker_left_id] @[simp, reassoc] lemma hom_inv_whisker_right {f g : a ⟶ b} (η : f ≅ g) (h : b ⟶ c) : η.hom ▷ h ≫ η.inv ▷ h = 𝟙 (f ≫ h) := by rw [←comp_whisker_right, hom_inv_id, id_whisker_right] @[simp, reassoc] lemma inv_hom_whisker_left (f : a ⟶ b) {g h : b ⟶ c} (η : g ≅ h) : f ◁ η.inv ≫ f ◁ η.hom = 𝟙 (f ≫ h) := by rw [←whisker_left_comp, inv_hom_id, whisker_left_id] @[simp, reassoc] lemma inv_hom_whisker_right {f g : a ⟶ b} (η : f ≅ g) (h : b ⟶ c) : η.inv ▷ h ≫ η.hom ▷ h = 𝟙 (g ≫ h) := by rw [←comp_whisker_right, inv_hom_id, id_whisker_right] /-- The left whiskering of a 2-isomorphism is a 2-isomorphism. -/ @[simps] def whisker_left_iso (f : a ⟶ b) {g h : b ⟶ c} (η : g ≅ h) : f ≫ g ≅ f ≫ h := { hom := f ◁ η.hom, inv := f ◁ η.inv } instance whisker_left_is_iso (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h) [is_iso η] : is_iso (f ◁ η) := is_iso.of_iso (whisker_left_iso f (as_iso η)) @[simp] lemma inv_whisker_left (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h) [is_iso η] : inv (f ◁ η) = f ◁ (inv η) := by { ext, simp only [←whisker_left_comp, whisker_left_id, is_iso.hom_inv_id] } /-- The right whiskering of a 2-isomorphism is a 2-isomorphism. -/ @[simps] def whisker_right_iso {f g : a ⟶ b} (η : f ≅ g) (h : b ⟶ c) : f ≫ h ≅ g ≫ h := { hom := η.hom ▷ h, inv := η.inv ▷ h } instance whisker_right_is_iso {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c) [is_iso η] : is_iso (η ▷ h) := is_iso.of_iso (whisker_right_iso (as_iso η) h) @[simp] lemma inv_whisker_right {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c) [is_iso η] : inv (η ▷ h) = (inv η) ▷ h := by { ext, simp only [←comp_whisker_right, id_whisker_right, is_iso.hom_inv_id] } @[simp, reassoc] lemma pentagon_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : f ◁ (α_ g h i).inv ≫ (α_ f (g ≫ h) i).inv ≫ (α_ f g h).inv ▷ i = (α_ f g (h ≫ i)).inv ≫ (α_ (f ≫ g) h i).inv := eq_of_inv_eq_inv (by simp) @[simp, reassoc] lemma pentagon_inv_inv_hom_hom_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : (α_ f (g ≫ h) i).inv ≫ (α_ f g h).inv ▷ i ≫ (α_ (f ≫ g) h i).hom = f ◁ (α_ g h i).hom ≫ (α_ f g (h ≫ i)).inv := by { rw [←cancel_epi (f ◁ (α_ g h i).inv), ←cancel_mono (α_ (f ≫ g) h i).inv], simp } @[simp, reassoc] lemma pentagon_inv_hom_hom_hom_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : (α_ (f ≫ g) h i).inv ≫ (α_ f g h).hom ▷ i ≫ (α_ f (g ≫ h) i).hom = (α_ f g (h ≫ i)).hom ≫ f ◁ (α_ g h i).inv := eq_of_inv_eq_inv (by simp) @[simp, reassoc] lemma pentagon_hom_inv_inv_inv_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : f ◁ (α_ g h i).hom ≫ (α_ f g (h ≫ i)).inv ≫ (α_ (f ≫ g) h i).inv = (α_ f (g ≫ h) i).inv ≫ (α_ f g h).inv ▷ i := by simp [←cancel_epi (f ◁ (α_ g h i).inv)] @[simp, reassoc] lemma pentagon_hom_hom_inv_hom_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : (α_ (f ≫ g) h i).hom ≫ (α_ f g (h ≫ i)).hom ≫ f ◁ (α_ g h i).inv = (α_ f g h).hom ▷ i ≫ (α_ f (g ≫ h) i).hom := eq_of_inv_eq_inv (by simp) @[simp, reassoc] lemma pentagon_hom_inv_inv_inv_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : (α_ f g (h ≫ i)).hom ≫ f ◁ (α_ g h i).inv ≫ (α_ f (g ≫ h) i).inv = (α_ (f ≫ g) h i).inv ≫ (α_ f g h).hom ▷ i := by { rw [←cancel_epi (α_ f g (h ≫ i)).inv, ←cancel_mono ((α_ f g h).inv ▷ i)], simp } @[simp, reassoc] lemma pentagon_hom_hom_inv_inv_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : (α_ f (g ≫ h) i).hom ≫ f ◁ (α_ g h i).hom ≫ (α_ f g (h ≫ i)).inv = (α_ f g h).inv ▷ i ≫ (α_ (f ≫ g) h i).hom := eq_of_inv_eq_inv (by simp) @[simp, reassoc] lemma pentagon_inv_hom_hom_hom_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : (α_ f g h).inv ▷ i ≫ (α_ (f ≫ g) h i).hom ≫ (α_ f g (h ≫ i)).hom = (α_ f (g ≫ h) i).hom ≫ f ◁ (α_ g h i).hom := by simp [←cancel_epi ((α_ f g h).hom ▷ i)] @[simp, reassoc] lemma pentagon_inv_inv_hom_inv_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) : (α_ f g (h ≫ i)).inv ≫ (α_ (f ≫ g) h i).inv ≫ (α_ f g h).hom ▷ i = f ◁ (α_ g h i).inv ≫ (α_ f (g ≫ h) i).inv := eq_of_inv_eq_inv (by simp) lemma triangle_assoc_comp_left (f : a ⟶ b) (g : b ⟶ c) : (α_ f (𝟙 b) g).hom ≫ f ◁ (λ_ g).hom = (ρ_ f).hom ▷ g := triangle f g @[simp, reassoc] lemma triangle_assoc_comp_right (f : a ⟶ b) (g : b ⟶ c) : (α_ f (𝟙 b) g).inv ≫ (ρ_ f).hom ▷ g = f ◁ (λ_ g).hom := by rw [←triangle, inv_hom_id_assoc] @[simp, reassoc] lemma triangle_assoc_comp_right_inv (f : a ⟶ b) (g : b ⟶ c) : (ρ_ f).inv ▷ g ≫ (α_ f (𝟙 b) g).hom = f ◁ (λ_ g).inv := by simp [←cancel_mono (f ◁ (λ_ g).hom)] @[simp, reassoc] lemma triangle_assoc_comp_left_inv (f : a ⟶ b) (g : b ⟶ c) : f ◁ (λ_ g).inv ≫ (α_ f (𝟙 b) g).inv = (ρ_ f).inv ▷ g := by simp [←cancel_mono ((ρ_ f).hom ▷ g)] @[reassoc] lemma associator_naturality_left {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d) : (η ▷ g) ▷ h ≫ (α_ f' g h).hom = (α_ f g h).hom ≫ η ▷ (g ≫ h) := by simp @[reassoc] lemma associator_inv_naturality_left {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d) : η ▷ (g ≫ h) ≫ (α_ f' g h).inv = (α_ f g h).inv ≫ (η ▷ g) ▷ h := by simp @[reassoc] lemma whisker_right_comp_symm {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d) : (η ▷ g) ▷ h = (α_ f g h).hom ≫ η ▷ (g ≫ h) ≫ (α_ f' g h).inv := by simp @[reassoc] lemma associator_naturality_middle (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d) : (f ◁ η) ▷ h ≫ (α_ f g' h).hom = (α_ f g h).hom ≫ f ◁ (η ▷ h) := by simp @[reassoc] lemma associator_inv_naturality_middle (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d) : f ◁ (η ▷ h) ≫ (α_ f g' h).inv = (α_ f g h).inv ≫ (f ◁ η) ▷ h := by simp @[reassoc] lemma whisker_assoc_symm (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d) : f ◁ (η ▷ h) = (α_ f g h).inv ≫ (f ◁ η) ▷ h ≫ (α_ f g' h).hom := by simp @[reassoc] lemma associator_naturality_right (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h') : (f ≫ g) ◁ η ≫ (α_ f g h').hom = (α_ f g h).hom ≫ f ◁ (g ◁ η) := by simp @[reassoc] lemma associator_inv_naturality_right (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h') : f ◁ (g ◁ η) ≫ (α_ f g h').inv = (α_ f g h).inv ≫ (f ≫ g) ◁ η := by simp @[reassoc] lemma comp_whisker_left_symm (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h') : f ◁ (g ◁ η) = (α_ f g h).inv ≫ (f ≫ g) ◁ η ≫ (α_ f g h').hom := by simp @[reassoc] lemma left_unitor_naturality {f g : a ⟶ b} (η : f ⟶ g) : 𝟙 a ◁ η ≫ (λ_ g).hom = (λ_ f).hom ≫ η := by simp @[reassoc] lemma left_unitor_inv_naturality {f g : a ⟶ b} (η : f ⟶ g) : η ≫ (λ_ g).inv = (λ_ f).inv ≫ 𝟙 a ◁ η := by simp lemma id_whisker_left_symm {f g : a ⟶ b} (η : f ⟶ g) : η = (λ_ f).inv ≫ 𝟙 a ◁ η ≫ (λ_ g).hom := by simp @[reassoc] lemma right_unitor_naturality {f g : a ⟶ b} (η : f ⟶ g) : η ▷ 𝟙 b ≫ (ρ_ g).hom = (ρ_ f).hom ≫ η := by simp @[reassoc] lemma right_unitor_inv_naturality {f g : a ⟶ b} (η : f ⟶ g) : η ≫ (ρ_ g).inv = (ρ_ f).inv ≫ η ▷ 𝟙 b := by simp lemma whisker_right_id_symm {f g : a ⟶ b} (η : f ⟶ g) : η = (ρ_ f).inv ≫ η ▷ 𝟙 b ≫ (ρ_ g).hom := by simp lemma whisker_left_iff {f g : a ⟶ b} (η θ : f ⟶ g) : (𝟙 a ◁ η = 𝟙 a ◁ θ) ↔ (η = θ) := by simp lemma whisker_right_iff {f g : a ⟶ b} (η θ : f ⟶ g) : (η ▷ 𝟙 b = θ ▷ 𝟙 b) ↔ (η = θ) := by simp /-- We state it as a simp lemma, which is regarded as an involved version of `id_whisker_right f g : 𝟙 f ▷ g = 𝟙 (f ≫ g)`. -/ @[reassoc, simp] lemma left_unitor_whisker_right (f : a ⟶ b) (g : b ⟶ c) : (λ_ f).hom ▷ g = (α_ (𝟙 a) f g).hom ≫ (λ_ (f ≫ g)).hom := by rw [←whisker_left_iff, whisker_left_comp, ←cancel_epi (α_ _ _ _).hom, ←cancel_epi ((α_ _ _ _).hom ▷ _), pentagon_assoc, triangle, ←associator_naturality_middle, ←comp_whisker_right_assoc, triangle, associator_naturality_left]; apply_instance @[reassoc, simp] lemma left_unitor_inv_whisker_right (f : a ⟶ b) (g : b ⟶ c) : (λ_ f).inv ▷ g = (λ_ (f ≫ g)).inv ≫ (α_ (𝟙 a) f g).inv := eq_of_inv_eq_inv (by simp) @[reassoc, simp] lemma whisker_left_right_unitor (f : a ⟶ b) (g : b ⟶ c) : f ◁ (ρ_ g).hom = (α_ f g (𝟙 c)).inv ≫ (ρ_ (f ≫ g)).hom := by rw [←whisker_right_iff, comp_whisker_right, ←cancel_epi (α_ _ _ _).inv, ←cancel_epi (f ◁ (α_ _ _ _).inv), pentagon_inv_assoc, triangle_assoc_comp_right, ←associator_inv_naturality_middle, ←whisker_left_comp_assoc, triangle_assoc_comp_right, associator_inv_naturality_right]; apply_instance @[reassoc, simp] lemma whisker_left_right_unitor_inv (f : a ⟶ b) (g : b ⟶ c) : f ◁ (ρ_ g).inv = (ρ_ (f ≫ g)).inv ≫ (α_ f g (𝟙 c)).hom := eq_of_inv_eq_inv (by simp) /- It is not so obvious whether `left_unitor_whisker_right` or `left_unitor_comp` should be a simp lemma. Our choice is the former. One reason is that the latter yields the following loop: [id_whisker_left] : 𝟙 a ◁ (ρ_ f).hom ==> (λ_ (f ≫ 𝟙 b)).hom ≫ (ρ_ f).hom ≫ (λ_ f).inv [left_unitor_comp] : (λ_ (f ≫ 𝟙 b)).hom ==> (α_ (𝟙 a) f (𝟙 b)).inv ≫ (λ_ f).hom ▷ 𝟙 b [whisker_right_id] : (λ_ f).hom ▷ 𝟙 b ==> (ρ_ (𝟙 a ≫ f)).hom ≫ (λ_ f).hom ≫ (ρ_ f).inv [right_unitor_comp] : (ρ_ (𝟙 a ≫ f)).hom ==> (α_ (𝟙 a) f (𝟙 b)).hom ≫ 𝟙 a ◁ (ρ_ f).hom -/ @[reassoc] lemma left_unitor_comp (f : a ⟶ b) (g : b ⟶ c) : (λ_ (f ≫ g)).hom = (α_ (𝟙 a) f g).inv ≫ (λ_ f).hom ▷ g := by simp @[reassoc] lemma left_unitor_comp_inv (f : a ⟶ b) (g : b ⟶ c) : (λ_ (f ≫ g)).inv = (λ_ f).inv ▷ g ≫ (α_ (𝟙 a) f g).hom := by simp @[reassoc] lemma right_unitor_comp (f : a ⟶ b) (g : b ⟶ c) : (ρ_ (f ≫ g)).hom = (α_ f g (𝟙 c)).hom ≫ f ◁ (ρ_ g).hom := by simp @[reassoc] lemma right_unitor_comp_inv (f : a ⟶ b) (g : b ⟶ c) : (ρ_ (f ≫ g)).inv = f ◁ (ρ_ g).inv ≫ (α_ f g (𝟙 c)).inv := by simp @[simp] lemma unitors_equal : (λ_ (𝟙 a)).hom = (ρ_ (𝟙 a)).hom := by rw [←whisker_left_iff, ←cancel_epi (α_ _ _ _).hom, ←cancel_mono (ρ_ _).hom, triangle, ←right_unitor_comp, right_unitor_naturality]; apply_instance @[simp] lemma unitors_inv_equal : (λ_ (𝟙 a)).inv = (ρ_ (𝟙 a)).inv := by simp [iso.inv_eq_inv] end bicategory end category_theory
562b7d1ab11df8e2a7dfb483270e9185bfd931eb
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Data/Lsp/Diagnostics.lean
b1086d572aef3e0a2ac795fb798ea0f63d79061a
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,081
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic import Lean.Data.Lsp.Utf16 import Lean.Message /-! Definitions and functionality for emitting diagnostic information such as errors, warnings and #command outputs from the LSP server. -/ namespace Lean namespace Lsp open Json inductive DiagnosticSeverity | error | warning | information | hint instance DiagnosticSeverity.hasFromJson : HasFromJson DiagnosticSeverity := ⟨fun j => match j.getNat? with | some 1 => DiagnosticSeverity.error | some 2 => DiagnosticSeverity.warning | some 3 => DiagnosticSeverity.information | some 4 => DiagnosticSeverity.hint | _ => none⟩ instance DiagnosticSeverity.hasToJson : HasToJson DiagnosticSeverity := ⟨fun o => match o with | DiagnosticSeverity.error => (1 : Nat) | DiagnosticSeverity.warning => (2 : Nat) | DiagnosticSeverity.information => (3 : Nat) | DiagnosticSeverity.hint => (4 : Nat)⟩ inductive DiagnosticCode | int (i : Int) | string (s : String) instance DiagnosticCode.hasFromJson : HasFromJson DiagnosticCode := ⟨fun j => match j with | num (i : Int) => DiagnosticCode.int i | str s => DiagnosticCode.string s | _ => none⟩ instance DiagnosticCode.hasToJson : HasToJson DiagnosticCode := ⟨fun o => match o with | DiagnosticCode.int i => i | DiagnosticCode.string s => s⟩ inductive DiagnosticTag | unnecessary | deprecated instance DiagnosticTag.hasFromJson : HasFromJson DiagnosticTag := ⟨fun j => match j.getNat? with | some 1 => DiagnosticTag.unnecessary | some 2 => DiagnosticTag.deprecated | _ => none⟩ instance DiagnosticTag.hasToJson : HasToJson DiagnosticTag := ⟨fun o => match o with | DiagnosticTag.unnecessary => (1 : Nat) | DiagnosticTag.deprecated => (2 : Nat)⟩ structure DiagnosticRelatedInformation := (location : Location) (message : String) instance DiagnosticRelatedInformation.hasFromJson : HasFromJson DiagnosticRelatedInformation := ⟨fun j => do location ← j.getObjValAs? Location "location"; message ← j.getObjValAs? String "message"; pure ⟨location, message⟩⟩ instance DiagnosticRelatedInformation.hasToJson : HasToJson DiagnosticRelatedInformation := ⟨fun o => mkObj [ ⟨"location", toJson o.location⟩, ⟨"message", o.message⟩]⟩ structure Diagnostic := (range : Range) (severity? : Option DiagnosticSeverity := none) (code? : Option DiagnosticCode := none) (source? : Option String := none) (message : String) (tags? : Option (Array DiagnosticTag) := none) (relatedInformation? : Option (Array DiagnosticRelatedInformation) := none) instance Diagnostic.hasFromJson : HasFromJson Diagnostic := ⟨fun j => do range ← j.getObjValAs? Range "range"; let severity? := j.getObjValAs? DiagnosticSeverity "severity"; let code? := j.getObjValAs? DiagnosticCode "code"; let source? := j.getObjValAs? String "source"; message ← j.getObjValAs? String "message"; let tags? := j.getObjValAs? (Array DiagnosticTag) "tags"; let relatedInformation? := j.getObjValAs? (Array DiagnosticRelatedInformation) "relatedInformation"; pure ⟨range, severity?, code?, source?, message, tags?, relatedInformation?⟩⟩ instance Diagnostic.hasToJson : HasToJson Diagnostic := ⟨fun o => mkObj $ opt "severity" o.severity? ++ opt "code" o.code? ++ opt "source" o.source? ++ opt "tags" o.tags? ++ opt "relatedInformation" o.relatedInformation? ++ [ ⟨"range", toJson o.range⟩, ⟨"message", o.message⟩]⟩ structure PublishDiagnosticsParams := (uri : DocumentUri) (version? : Option Int := none) (diagnostics: Array Diagnostic) instance PublishDiagnosticsParams.hasFromJson : HasFromJson PublishDiagnosticsParams := ⟨fun j => do uri ← j.getObjValAs? DocumentUri "uri"; let version? := j.getObjValAs? Int "version"; diagnostics ← j.getObjValAs? (Array Diagnostic) "diagnostics"; pure ⟨uri, version?, diagnostics⟩⟩ instance PublishDiagnosticsParams.hasToJson : HasToJson PublishDiagnosticsParams := ⟨fun o => mkObj $ opt "version" o.version? ++ [ ⟨"uri", toJson o.uri⟩, ⟨"diagnostics", toJson o.diagnostics⟩]⟩ /-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/ def msgToDiagnostic (text : FileMap) (m : Message) : Diagnostic := let low : Lsp.Position := text.leanPosToLspPos m.pos; let high : Lsp.Position := match m.endPos with | some endPos => text.leanPosToLspPos endPos | none => low; let range : Range := ⟨low, high⟩; let severity := match m.severity with | MessageSeverity.information => DiagnosticSeverity.information | MessageSeverity.warning => DiagnosticSeverity.warning | MessageSeverity.error => DiagnosticSeverity.error; let source := "Lean 4 server"; let message := toString (format m.data); { range := range, severity? := severity, source? := source, message := message, } end Lsp end Lean
3b519c09ebaf57e2090c29c9506ed476a1ec8af3
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/omin/def_choice/choice5.lean
ba7724fdf9d9d9b1dcf3cdd97bec55533cb765b2
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
5,973
lean
import o_minimal.sheaf.yoneda import .choice3 import .choice4 open o_minimal universe u variables {R : Type u} [OQM R] variables {S : struc R} [o_minimal_add S] -- We need Y and R to live in the same universe to apply `def_graph`. -- Is this really necessary? -- jmc: ↑ is now obsolete variables {Y : Type*} [has_coordinates R Y] [is_definable S Y] local notation `½` := (1/2 : ℚ) lemma definable_choice_1 {s : set (Y × R)} (ds : def_set S s) (h : prod.fst '' s = set.univ) : ∃ g : Y → R, def_fun S g ∧ ∀ y, (y, g y) ∈ s := begin have ne : ∀ y, set.nonempty {r | (y, r) ∈ s}, { intro y, change ∃ r, (y, r) ∈ s, { have : y ∈ prod.fst '' s := by { rw h, trivial }, obtain ⟨⟨y', x⟩, h, rfl⟩ := this, exact ⟨x, h⟩ } }, refine ⟨λ y, (chosen_one {r | (y, r) ∈ s}), _, _⟩, { unfold def_fun, letI : definable_sheaf S Y := definable_sheaf.rep, letI : definable_rep S Y := ⟨λ _ _, iff.rfl⟩, rw ←definable_iff_def_set, begin [defin] intro p, app, app, exact definable_sheaf.eq, swap, { app, exact definable.snd.definable _, var }, { app, exact definable_chosen_one.definable _, intro r, app, app, exact definable.mem.definable _, app, app, exact definable.prod_mk.definable _, app, exact definable.fst.definable _, var, var, exact (definable_iff_def_set.mpr ds).definable _ } end }, { intro y, let X := {r | (y, r) ∈ s}, have nX : X.nonempty := ne y, have tX : tame X, { apply tame_of_def S, refine def_fun.preimage _ ds, exact def_fun.prod' def_fun_const def_fun.id }, apply chosen_one_mem nX tX } end . variables {X X₁ X₂ : Type*} [definable_sheaf S X] [definable_sheaf S X₁] [definable_sheaf S X₂] def fibre_1 (s : set (X × R)) : X → set R := λ x, {r | (x, r) ∈ s} lemma definable_fibre_1 {s : set (X × R)} (ds : definable S s) : definable S (fibre_1 s) := begin [defin] intro x, intro r, app, app, exact definable.mem.definable _, app, app, exact definable.prod_mk.definable _, var, var, exact ds.definable _ end lemma definable_of_forall_definable_eq (f g : X₁ → X₂) (hf : definable S f) (H : ∀ x : X₁, definable S x → f x = g x) : definable S g := begin constructor, intros K L φ hφ, convert hf.definable K L φ hφ using 1, ext1, dsimp [function.uncurry], rw [H], rw ← definable_yoneda at hφ, begin [defin] app, exact definable.snd.definable _, app, exact hφ.definable _, exact def_fun_const end end lemma definable_chosen_one' : definable S (chosen_one' : set R → R) := begin refine definable_of_forall_definable_eq chosen_one _ definable_chosen_one _, intros s hs, unfold chosen_one chosen_one', rw dif_pos, apply tame_of_def S, rwa definable_iff_def_set at hs end noncomputable def chosen_n' : Π {n : ℕ}, set (finvec n R) → finvec n R | 0 s := fin_zero_elim | (n+1) s := let t : set (finvec n R) := finvec.init '' s, a : finvec n R := chosen_n' t, X : set R := {r | a.snoc r ∈ s} in a.snoc (chosen_one' X) lemma chosen_n'_mem : ∀ {n : ℕ} {s : set (finvec n R)} (hs : s.nonempty), chosen_n' s ∈ s | 0 s hs := by { obtain ⟨x, hx⟩ := hs, convert hx } | (n+1) s hs := let t : set (finvec n R) := finvec.init '' s, a : finvec n R := chosen_n' t, X : set R := {r | a.snoc r ∈ s} in begin have ht : t.nonempty, by { rwa set.nonempty_image_iff }, have hat : a ∈ t := chosen_n'_mem ht, have hX : X.nonempty, { obtain ⟨v, hv, H⟩ := hat, rw [← finvec.init_snoc_last v, H] at hv, exact ⟨v.last, hv⟩ }, have := chosen_one'_mem hX, rwa [chosen_n'] end instance (n : ℕ) : definable_sheaf S (finvec n R) := definable_sheaf.rep instance (n : ℕ) : definable_rep S (finvec n R) := ⟨λ _ _, iff.rfl⟩ lemma definable_chosen_n' : ∀ (n : ℕ), definable S (chosen_n' : set (finvec n R) → finvec n R) | 0 := begin [defin] intro s, exact (show definable_sheaf.definable (λ (i : ↥Γ), fin_zero_elim), by exact def_fun_const) end | (n+1) := begin show (definable S (λ s, chosen_n' s)), conv { congr, funext, rw [chosen_n'] }, dsimp [set_of], begin [defin] intro s, app, app, exact sorry, app, exact (definable_chosen_n' n).definable _, app, app, exact sorry, exact sorry, var, app, exact definable_chosen_one'.definable _, intro r, app, app, exact definable.mem.definable _, app, app, exact sorry, app, exact (definable_chosen_n' n).definable _, app, app, exact sorry, exact sorry, var, var, var, end end noncomputable def chosen_1 (s : set (X × R)) : X → R := chosen_one' ∘ (fibre_1 s) lemma chosen_1_mem (s : set (X × R)) (h : prod.fst '' s = set.univ) (x : X) : (x, chosen_1 s x) ∈ s := begin suffices ne : ∀ x, set.nonempty {r | (x, r) ∈ s}, by exact chosen_one'_mem (ne x), intro x, change ∃ r, (x, r) ∈ s, obtain ⟨⟨x', x⟩, h, rfl⟩ : x ∈ prod.fst '' s := by { rw h, trivial }, exact ⟨x, h⟩ end lemma definable_chosen_1 {s : set (X × R)} (ds : definable S s) : definable S (chosen_1 s) := begin [defin] intro x, app, exact definable_chosen_one'.definable _, app, exact (definable_fibre_1 ds).definable _, var end lemma definable_choice_1' {s : set (X × R)} (ds : definable S s) (h : prod.fst '' s = set.univ) : ∃ g : X → R, definable S g ∧ ∀ x, (x, g x) ∈ s := ⟨chosen_1 s, definable_chosen_1 ds, chosen_1_mem s h⟩ -- new proof of `definable_choice_1` using `definable_rep` instead of `is_definable` example {Y : Type*} [has_coordinates R Y] [definable_rep S Y] {s : set (Y × R)} (ds : def_set S s) (h : prod.fst '' s = set.univ) : ∃ g : Y → R, def_fun S g ∧ ∀ y, (y, g y) ∈ s := begin refine ⟨chosen_1 s, _, chosen_1_mem s h⟩, rw ← definable_iff_def_set at ds, rw ← definable_iff_def_fun, exact definable_chosen_1 ds end
d94d6a2ef2eca8713d9b3e6c9ef4a93221b2e68a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/metric_separated.lean
8e6bbf6f41d6ccd533fe2eaaac8b3907399a5b89
[ "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
4,449
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.emetric_space /-! # Metric separated pairs of sets In this file we define the predicate `is_metric_separated`. We say that two sets in an (extended) metric space are *metric separated* if the (extended) distance between `x ∈ s` and `y ∈ t` is bounded from below by a positive constant. This notion is useful, e.g., to define metric outer measures. -/ open emetric set noncomputable theory /-- Two sets in an (extended) metric space are called *metric separated* if the (extended) distance between `x ∈ s` and `y ∈ t` is bounded from below by a positive constant. -/ def is_metric_separated {X : Type*} [emetric_space X] (s t : set X) := ∃ r ≠ 0, ∀ (x ∈ s) (y ∈ t), r ≤ edist x y namespace is_metric_separated variables {X : Type*} [emetric_space X] {s t : set X} {x y : X} @[symm] lemma symm (h : is_metric_separated s t) : is_metric_separated t s := let ⟨r, r0, hr⟩ := h in ⟨r, r0, λ y hy x hx, edist_comm x y ▸ hr x hx y hy⟩ lemma comm : is_metric_separated s t ↔ is_metric_separated t s := ⟨symm, symm⟩ @[simp] lemma empty_left (s : set X) : is_metric_separated ∅ s := ⟨1, ennreal.zero_lt_one.ne', λ x, false.elim⟩ @[simp] lemma empty_right (s : set X) : is_metric_separated s ∅ := (empty_left s).symm protected lemma disjoint (h : is_metric_separated s t) : disjoint s t := let ⟨r, r0, hr⟩ := h in set.disjoint_left.mpr $ λ x hx1 hx2, r0 $ by simpa using hr x hx1 x hx2 lemma subset_compl_right (h : is_metric_separated s t) : s ⊆ tᶜ := λ x hs ht, h.disjoint.le_bot ⟨hs, ht⟩ @[mono] lemma mono {s' t'} (hs : s ⊆ s') (ht : t ⊆ t') : is_metric_separated s' t' → is_metric_separated s t := λ ⟨r, r0, hr⟩, ⟨r, r0, λ x hx y hy, hr x (hs hx) y (ht hy)⟩ lemma mono_left {s'} (h' : is_metric_separated s' t) (hs : s ⊆ s') : is_metric_separated s t := h'.mono hs subset.rfl lemma mono_right {t'} (h' : is_metric_separated s t') (ht : t ⊆ t') : is_metric_separated s t := h'.mono subset.rfl ht lemma union_left {s'} (h : is_metric_separated s t) (h' : is_metric_separated s' t) : is_metric_separated (s ∪ s') t := begin rcases ⟨h, h'⟩ with ⟨⟨r, r0, hr⟩, ⟨r', r0', hr'⟩⟩, refine ⟨min r r', _, λ x hx y hy, hx.elim _ _⟩, { rw [← pos_iff_ne_zero] at r0 r0' ⊢, exact lt_min r0 r0' }, { exact λ hx, (min_le_left _ _).trans (hr _ hx _ hy) }, { exact λ hx, (min_le_right _ _).trans (hr' _ hx _ hy) } end @[simp] lemma union_left_iff {s'} : is_metric_separated (s ∪ s') t ↔ is_metric_separated s t ∧ is_metric_separated s' t := ⟨λ h, ⟨h.mono_left (subset_union_left _ _), h.mono_left (subset_union_right _ _)⟩, λ h, h.1.union_left h.2⟩ lemma union_right {t'} (h : is_metric_separated s t) (h' : is_metric_separated s t') : is_metric_separated s (t ∪ t') := (h.symm.union_left h'.symm).symm @[simp] lemma union_right_iff {t'} : is_metric_separated s (t ∪ t') ↔ is_metric_separated s t ∧ is_metric_separated s t' := comm.trans $ union_left_iff.trans $ and_congr comm comm lemma finite_Union_left_iff {ι : Type*} {I : set ι} (hI : I.finite) {s : ι → set X} {t : set X} : is_metric_separated (⋃ i ∈ I, s i) t ↔ ∀ i ∈ I, is_metric_separated (s i) t := begin refine finite.induction_on hI (by simp) (λ i I hi _ hI, _), rw [bUnion_insert, ball_insert_iff, union_left_iff, hI] end alias finite_Union_left_iff ↔ _ finite_Union_left lemma finite_Union_right_iff {ι : Type*} {I : set ι} (hI : I.finite) {s : set X} {t : ι → set X} : is_metric_separated s (⋃ i ∈ I, t i) ↔ ∀ i ∈ I, is_metric_separated s (t i) := by simpa only [@comm _ _ s] using finite_Union_left_iff hI @[simp] lemma finset_Union_left_iff {ι : Type*} {I : finset ι} {s : ι → set X} {t : set X} : is_metric_separated (⋃ i ∈ I, s i) t ↔ ∀ i ∈ I, is_metric_separated (s i) t := finite_Union_left_iff I.finite_to_set alias finset_Union_left_iff ↔ _ finset_Union_left @[simp] lemma finset_Union_right_iff {ι : Type*} {I : finset ι} {s : set X} {t : ι → set X} : is_metric_separated s (⋃ i ∈ I, t i) ↔ ∀ i ∈ I, is_metric_separated s (t i) := finite_Union_right_iff I.finite_to_set alias finset_Union_right_iff ↔ _ finset_Union_right end is_metric_separated
89bc1e7c8dcc1a0601dd36f917db60612d755d01
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/fintype/card.lean
c58cff507f48aec6aabf6b12842e313f5e6669f7
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
2,050
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Haitao Zhang Cardinality for finite types. -/ import .basic data.list data.finset.card open eq.ops nat function list finset namespace fintype attribute [reducible] definition card (A : Type) [finA : fintype A] := finset.card (@finset.univ A _) lemma card_eq_card_image_of_inj {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {B : Type} [finB : fintype B] [deceqB : decidable_eq B] {f : A → B} : injective f → finset.card (image f univ) = card A := assume Pinj, card_image_eq_of_inj_on (to_set_univ⁻¹ ▸ (iff.mp !set.injective_iff_inj_on_univ Pinj)) -- General version of the pigeonhole principle. See also data.less_than. lemma card_le_of_inj (A : Type) [finA : fintype A] [deceqA : decidable_eq A] (B : Type) [finB : fintype B] [deceqB : decidable_eq B] : (∃ f : A → B, injective f) → card A ≤ card B := assume Pex, obtain f Pinj, from Pex, have Pinj_on_univ : _, from iff.mp !set.injective_iff_inj_on_univ Pinj, have Pinj_ts : set.inj_on f (ts univ), from to_set_univ⁻¹ ▸ Pinj_on_univ, have Psub : (image f univ) ⊆ univ, from !subset_univ, finset.card_le_of_inj_on univ univ (exists.intro f (and.intro Pinj_ts Psub)) -- used to prove that inj ∧ eq card => surj lemma univ_of_card_eq_univ {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {s : finset A} : finset.card s = card A → s = univ := assume Pcardeq, ext (take a, have D : decidable (a ∈ s), from decidable_mem a s, begin apply iff.intro, intro ain, apply mem_univ, intro ain, cases D with Pin Pnin, exact Pin, have Pplus1 : finset.card (insert a s) = finset.card s + 1, from card_insert_of_not_mem Pnin, rewrite Pcardeq at Pplus1, have Ple : finset.card (insert a s) ≤ card A, begin apply card_le_card_of_subset, apply subset_univ end, rewrite Pplus1 at Ple, exact false.elim (not_succ_le_self Ple) end) end fintype
cc7aa415e4a20f0f1e5cad1d90b69366eee404f9
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/tactic/lint/simp.lean
ff570c793162a8f46acad68c2ed9749ff527ef13
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
9,352
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import tactic.lint.basic /-! # Linter for simplification lemmas This files defines several linters that prevent common mistakes when declaring simp lemmas: * `simp_nf` checks that the left-hand side of a simp lemma is not simplified by a different lemma. * `simp_var_head` checks that the head symbol of the left-hand side is not a variable. * `simp_comm` checks that commutativity lemmas are not marked as simplification lemmas. -/ open tactic expr /-- `simp_lhs_rhs ty` returns the left-hand and right-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs_rhs : expr → tactic (expr × expr) | ty := do ty ← whnf ty transparency.reducible, -- We only detect a fixed set of simp relations here. -- This is somewhat justified since for a custom simp relation R, -- the simp lemma `R a b` is implicitly converted to `R a b ↔ true` as well. match ty with | `(¬ %%lhs) := pure (lhs, `(false)) | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | (expr.pi n bi a b) := do l ← mk_local' n bi a, simp_lhs_rhs (b.instantiate_var l) | ty := pure (ty, `(true)) end /-- `simp_lhs ty` returns the left-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs (ty : expr): tactic expr := prod.fst <$> simp_lhs_rhs ty /-- `simp_is_conditional_core ty` returns `none` if `ty` is a conditional simp lemma, and `some lhs` otherwise. -/ private meta def simp_is_conditional_core : expr → tactic (option expr) | ty := do ty ← whnf ty transparency.semireducible, match ty with | `(¬ %%lhs) := pure lhs | `(%%lhs = _) := pure lhs | `(%%lhs ↔ _) := pure lhs | (expr.pi n bi a b) := do l ← mk_local' n bi a, some lhs ← simp_is_conditional_core (b.instantiate_var l) | pure none, if bi ≠ binder_info.inst_implicit ∧ ¬ (lhs.abstract_local l.local_uniq_name).has_var then pure none else pure lhs | ty := pure ty end /-- `simp_is_conditional ty` returns true iff the simp lemma with type `ty` is conditional. -/ private meta def simp_is_conditional (ty : expr) : tactic bool := option.is_none <$> simp_is_conditional_core ty private meta def heuristic_simp_lemma_extraction (prf : expr) : tactic (list name) := prf.list_constant.to_list.mfilter is_simp_lemma /-- Checks whether two expressions are equal for the simplifier. That is, they are reducibly-definitional equal, and they have the same head symbol. -/ meta def is_simp_eq (a b : expr) : tactic bool := if a.get_app_fn.const_name ≠ b.get_app_fn.const_name then pure ff else succeeds $ is_def_eq a b transparency.reducible /-- Reports declarations that are simp lemmas whose left-hand side is not in simp-normal form. -/ meta def simp_nf_linter (timeout := 200000) (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, [] ← get_eqn_lemmas_for ff d.to_name | pure none, try_for timeout $ retrieve $ do g ← mk_meta_var d.type, set_goals [g], unfreezing (intros *> skip), (lhs, rhs) ← target >>= simp_lhs_rhs, sls ← simp_lemmas.mk_default, let sls' := sls.erase [d.to_name], (lhs', prf1) ← decorate_error "simplify fails on left-hand side:" $ simplify sls [] lhs {fail_if_unchanged := ff}, prf1_lems ← heuristic_simp_lemma_extraction prf1, if d.to_name ∈ prf1_lems then pure none else do is_cond ← simp_is_conditional d.type, (rhs', prf2) ← decorate_error "simplify fails on right-hand side:" $ simplify sls [] rhs {fail_if_unchanged := ff}, lhs'_eq_rhs' ← is_simp_eq lhs' rhs', lhs_in_nf ← is_simp_eq lhs' lhs, if lhs'_eq_rhs' then do used_lemmas ← heuristic_simp_lemma_extraction (prf1 prf2), pure $ pure $ "simp can prove this:\n" ++ " by simp only " ++ to_string used_lemmas ++ "\n" ++ "One of the lemmas above could be a duplicate.\n" ++ "If that's not the case try reordering lemmas or adding @[priority].\n" else if ¬ lhs_in_nf then do lhs ← pp lhs, lhs' ← pp lhs', pure $ format.to_string $ to_fmt "Left-hand side simplifies from" ++ lhs.group.indent 2 ++ format.line ++ "to" ++ lhs'.group.indent 2 ++ format.line ++ "using " ++ (to_fmt prf1_lems).group.indent 2 ++ format.line ++ "Try to change the left-hand side to the simplified term!\n" else if ¬ is_cond ∧ lhs = lhs' then do pure "Left-hand side does not simplify.\nYou need to debug this yourself using `set_option trace.simplify.rewrite true`" else pure none /-- This note gives you some tips to debug any errors that the simp-normal form linter raises The reason that a lemma was considered faulty is because its left-hand side is not in simp-normal form. These lemmas are hence never used by the simplifier. This linter gives you a list of other simp lemmas, look at them! Here are some tips depending on the error raised by the linter: 1. 'the left-hand side reduces to XYZ': you should probably use XYZ as the left-hand side. 2. 'simp can prove this': This typically means that lemma is a duplicate, or is shadowed by another lemma: 2a. Always put more general lemmas after specific ones: @[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl @[simp] lemma add_zero : x + 0 = x := rfl And not the other way around! The simplifier always picks the last matching lemma. 2b. You can also use @[priority] instead of moving simp-lemmas around in the file. Tip: the default priority is 1000. Use `@[priority 1100]` instead of moving a lemma down, and `@[priority 900]` instead of moving a lemma up. 2c. Conditional simp lemmas are tried last, if they are shadowed just remove the simp attribute. 2d. If two lemmas are duplicates, the linter will complain about the first one. Try to fix the second one instead! (You can find it among the other simp lemmas the linter prints out!) 3. 'try_for tactic failed, timeout': This typically means that there is a loop of simp lemmas. Try to apply squeeze_simp to the right-hand side (removing this lemma from the simp set) to see what lemmas might be causing the loop. Another trick is to `set_option trace.simplify.rewrite true` and then apply `try_for 10000 { simp }` to the right-hand side. You will see a periodic sequence of lemma applications in the trace message. -/ library_note "simp-normal form" /-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/ @[linter] meta def linter.simp_nf : linter := { test := simp_nf_linter, auto_decls := tt, no_errors_found := "All left-hand sides of simp lemmas are in simp-normal form", errors_found := "SOME SIMP LEMMAS ARE NOT IN SIMP-NORMAL FORM. see note [simp-normal form] for tips how to debug this. https://leanprover-community.github.io/mathlib_docs/notes.html#simp-normal%20form " } private meta def simp_var_head (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, lhs ← simp_lhs d.type, head_sym@(expr.local_const _ _ _ _) ← pure lhs.get_app_fn | pure none, head_sym ← pp head_sym, pure $ format.to_string $ "Left-hand side has variable as head symbol: " ++ head_sym /-- A linter for simp lemmas whose lhs has a variable as head symbol, and which hence never fire. -/ @[linter] meta def linter.simp_var_head : linter := { test := simp_var_head, auto_decls := tt, no_errors_found := "No left-hand sides of a simp lemma has a variable as head symbol", errors_found := "LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL.\n" ++ "Some simp lemmas have a variable as head symbol of the left-hand side" } private meta def simp_comm (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, (lhs, rhs) ← simp_lhs_rhs d.type, if lhs.get_app_fn.const_name ≠ rhs.get_app_fn.const_name then pure none else do (lhs', rhs') ← (prod.snd <$> mk_meta_pis d.type) >>= simp_lhs_rhs, tt ← succeeds $ unify rhs lhs' transparency.reducible | pure none, tt ← succeeds $ is_def_eq rhs lhs' transparency.reducible | pure none, -- ensure that the second application makes progress: ff ← succeeds $ unify lhs' rhs' transparency.reducible | pure none, pure $ "should not be marked simp" /-- A linter for commutativity lemmas that are marked simp. -/ @[linter] meta def linter.simp_comm : linter := { test := simp_comm, auto_decls := tt, no_errors_found := "No commutativity lemma is marked simp", errors_found := "COMMUTATIVITY LEMMA IS SIMP.\n" ++ "Some commutativity lemmas are simp lemmas" }
13dedab8137f63d83ef51956c19f2f099d3cff74
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/measure_theory/ae_measurable_sequence.lean
bdca277c779dca68926ad5bd1b7e00cb9d81f9df
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,366
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.measure_space /-! # Sequence of measurable functions associated to a sequence of a.e.-measurable functions We define here tools to prove statements about limits (infi, supr...) of sequences of `ae_measurable` functions. Given a sequence of a.e.-measurable functions `f : ι → α → β` with hypothesis `hf : ∀ i, ae_measurable (f i) μ`, and a pointwise property `p : α → (ι → β) → Prop` such that we have `hp : ∀ᵐ x ∂μ, p x (λ n, f n x)`, we define a sequence of measurable functions `ae_seq hf p` and a measurable set `ae_seq_set hf p`, such that * `μ (ae_seq_set hf p)ᶜ = 0` * `x ∈ ae_seq_set hf p → ∀ i : ι, ae_seq hf hp i x = f i x` * `x ∈ ae_seq_set hf p → p x (λ n, f n x)` -/ open measure_theory open_locale classical variables {α β γ ι : Type*} [measurable_space α] [measurable_space β] {f : ι → α → β} {μ : measure α} {p : α → (ι → β) → Prop} /-- If we have the additional hypothesis `∀ᵐ x ∂μ, p x (λ n, f n x)`, this is a measurable set whose complement has measure 0 such that for all `x ∈ ae_seq_set`, `f i x` is equal to `(hf i).mk (f i) x` for all `i` and we have the pointwise property `p x (λ n, f n x)`. -/ def ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : set α := (to_measurable μ {x | (∀ i, f i x = (hf i).mk (f i) x) ∧ p x (λ n, f n x)}ᶜ)ᶜ /-- A sequence of measurable functions that are equal to `f` and verify property `p` on the measurable set `ae_seq_set hf p`. -/ noncomputable def ae_seq (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : ι → α → β := λ i x, ite (x ∈ ae_seq_set hf p) ((hf i).mk (f i) x) (⟨f i x⟩ : nonempty β).some namespace ae_seq section mem_ae_seq_set lemma mk_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : (hf i).mk (f i) x = f i x := begin have h_ss : ae_seq_set hf p ⊆ {x | ∀ i, f i x = (hf i).mk (f i) x}, { rw [ae_seq_set, ←compl_compl {x | ∀ i, f i x = (hf i).mk (f i) x}, set.compl_subset_compl], refine set.subset.trans (set.compl_subset_compl.mpr (λ x h, _)) (subset_to_measurable _ _), exact h.1, }, exact (h_ss hx i).symm, end lemma ae_seq_eq_mk_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : ae_seq hf p i x = (hf i).mk (f i) x := by simp only [ae_seq, hx, if_true] lemma ae_seq_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : ae_seq hf p i x = f i x := by simp only [ae_seq_eq_mk_of_mem_ae_seq_set hf hx i, mk_eq_fun_of_mem_ae_seq_set hf hx i] lemma prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) : p x (λ n, ae_seq hf p n x) := begin simp only [ae_seq, hx, if_true], rw funext (λ n, mk_eq_fun_of_mem_ae_seq_set hf hx n), have h_ss : ae_seq_set hf p ⊆ {x | p x (λ n, f n x)}, { rw [←compl_compl {x | p x (λ n, f n x)}, ae_seq_set, set.compl_subset_compl], refine set.subset.trans (set.compl_subset_compl.mpr _) (subset_to_measurable _ _), exact λ x hx, hx.2, }, have hx' := set.mem_of_subset_of_mem h_ss hx, exact hx', end lemma fun_prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) : p x (λ n, f n x) := begin have h_eq : (λ n, f n x) = λ n, ae_seq hf p n x, from funext (λ n, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx n).symm), rw h_eq, exact prop_of_mem_ae_seq_set hf hx, end end mem_ae_seq_set lemma ae_seq_set_is_measurable {hf : ∀ i, ae_measurable (f i) μ} : is_measurable (ae_seq_set hf p) := (is_measurable_to_measurable _ _).compl lemma measurable (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) (i : ι) : measurable (ae_seq hf p i) := begin refine measurable.ite ae_seq_set_is_measurable (hf i).measurable_mk _, by_cases hα : nonempty α, { exact @measurable_const _ _ _ _ (⟨f i hα.some⟩ : nonempty β).some }, { exact measurable_of_not_nonempty hα _ } end lemma measure_compl_ae_seq_set_eq_zero [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : μ (ae_seq_set hf p)ᶜ = 0 := begin rw [ae_seq_set, compl_compl, measure_to_measurable], have hf_eq := λ i, (hf i).ae_eq_mk, simp_rw [filter.eventually_eq, ←ae_all_iff] at hf_eq, exact filter.eventually.and hf_eq hp, end lemma ae_seq_eq_mk_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : ∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = (hf i).mk (f i) a := begin have h_ss : ae_seq_set hf p ⊆ {a : α | ∀ i, ae_seq hf p i a = (hf i).mk (f i) a}, from λ x hx i, by simp only [ae_seq, hx, if_true], exact le_antisymm (le_trans (measure_mono (set.compl_subset_compl.mpr h_ss)) (le_of_eq (measure_compl_ae_seq_set_eq_zero hf hp))) (zero_le _), end lemma ae_seq_eq_fun_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : ∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = f i a := begin have h_ss : {a : α | ¬∀ (i : ι), ae_seq hf p i a = f i a} ⊆ (ae_seq_set hf p)ᶜ, from λ x, mt (λ hx i, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx i)), exact measure_mono_null h_ss (measure_compl_ae_seq_set_eq_zero hf hp), end lemma ae_seq_n_eq_fun_n_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) (n : ι) : ae_seq hf p n =ᵐ[μ] f n:= ae_all_iff.mp (ae_seq_eq_fun_ae hf hp) n lemma supr [complete_lattice β] [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : (⨆ n, ae_seq hf p n) =ᵐ[μ] ⨆ n, f n := begin simp_rw [filter.eventually_eq, ae_iff, supr_apply], have h_ss : ae_seq_set hf p ⊆ {a : α | (⨆ (i : ι), ae_seq hf p i a) = ⨆ (i : ι), f i a}, { intros x hx, congr, exact funext (λ i, ae_seq_eq_fun_of_mem_ae_seq_set hf hx i), }, exact measure_mono_null (set.compl_subset_compl.mpr h_ss) (measure_compl_ae_seq_set_eq_zero hf hp), end end ae_seq
58e23cb7cdb27af48823356eced82a554cef5e27
a5271082abc327bbe26fc4acdaa885da9582cefa
/src/prop.lean
572e07b2dad70aaacd44ff5687da5914888f6926
[ "Apache-2.0" ]
permissive
avigad/embed
9ee7d104609eeded173ca1e6e7a1925897b1652a
0e3612028d4039d29d06239ef03bc50576ca0f8b
refs/heads/master
1,584,548,951,613
1,527,883,346,000
1,527,883,346,000
134,967,973
0
0
null
null
null
null
UTF-8
Lean
false
false
7,778
lean
import .exp .print namespace prop variable {α : Type} class is_symb (α : Type) := (true : α) (false : α) (not : α) (and : α) (or : α) (imp : α) def true [is_symb α] := @exp.cst α (is_symb.true α) notation `⊤'` := true def false [is_symb α] := @exp.cst α (is_symb.false α) notation `⊥'` := false def not [is_symb α] (p : exp α) := exp.app (exp.cst (is_symb.not α)) p notation `¬'` p := not p def and [is_symb α] (p q : exp α) := exp.app (exp.app (exp.cst (is_symb.and α)) p) q notation p `∧'` q := and p q def or [is_symb α] (p q : exp α) := exp.app (exp.app (exp.cst (is_symb.or α)) p) q notation p `∨'` q := or p q def imp [is_symb α] (p q : exp α) := exp.app (exp.app (exp.cst (is_symb.imp α)) p) q notation p `→'` q := imp p q @[derive has_reflect] inductive symb : Type | atom : string → symb | true : symb | false : symb | not : symb | and : symb | or : symb | imp : symb instance : decidable_eq symb := by tactic.mk_dec_eq_instance instance : is_symb symb := { true := symb.true, false := symb.false, not := symb.not, and := symb.and, or := symb.or, imp := symb.imp } def A' (s : string) := @exp.cst symb (symb.atom s) inductive inf [is_symb α] : list (seq α) → seq α → Prop | id : ∀ Γ Δ p, inf [] (p::Γ ==> p::Δ) | truer : ∀ Γ Δ, inf [] (Γ ==> ⊤'::Δ) | falsel : ∀ Γ Δ, inf [] (⊥'::Γ ==> Δ) | andl : ∀ Γ Δ p q, inf [p::q::Γ ==> Δ] ((p ∧' q)::Γ ==> Δ) | andr : ∀ Γ Δ p q, inf [Γ ==> p::Δ, Γ ==> q::Δ] (Γ ==> (p ∧' q)::Δ) | orl : ∀ Γ Δ p q, inf [p::Γ ==> Δ, q::Γ ==> Δ] ((p ∨' q)::Γ ==> Δ) | orr : ∀ Γ Δ p q, inf [Γ ==> p::q::Δ] (Γ ==> (p ∨' q)::Δ) | impl : ∀ Γ Δ p q, inf [Γ ==> p::Δ, q::Γ ==> Δ] ((p →' q)::Γ ==> Δ) | impr : ∀ Γ Δ p q, inf [p::Γ ==> q::Δ] (Γ ==> (p →' q)::Δ) | wl : ∀ Γ Δ p, inf [Γ ==> Δ] (p::Γ ==> Δ) | wr : ∀ Γ Δ p, inf [Γ ==> Δ] (Γ ==> p::Δ) | cl : ∀ Γ Δ p, inf [p::p::Γ ==> Δ] (p::Γ ==> Δ) | cr : ∀ Γ Δ p, inf [Γ ==> p::p::Δ] (Γ ==> p::Δ) | pl : ∀ Γ Γ' Δ, Γ ~ Γ' → inf [Γ ==> Δ] (Γ' ==> Δ) | pr : ∀ Γ Δ Δ', Δ ~ Δ' → inf [Γ ==> Δ] (Γ ==> Δ') inductive thm [is_symb α] : (seq α) → Prop | inf : ∀ {s S}, inf S s → (∀ s' ∈ S, thm s') → thm s /- Derived rules -/ open list lemma thm.id [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (p::Γ ==> p::Δ) := begin intros Γ Δ p, apply thm.inf, apply inf.id, apply forall_mem_nil end lemma thm.truer [is_symb α] : ∀ (Γ Δ : list (exp α)), thm (Γ ==> ⊤'::Δ) := begin intros Γ Δ, apply thm.inf, apply inf.truer, apply forall_mem_nil end lemma thm.falsel [is_symb α] : ∀ (Γ Δ : list (exp α)), thm (⊥'::Γ ==> Δ) := begin intros Γ Δ, apply thm.inf, apply inf.falsel, apply forall_mem_nil end lemma thm.andl [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (p::q::Γ ==> Δ) → thm ((p ∧' q)::Γ ==> Δ) := begin intros Γ Δ p q h, apply thm.inf, apply inf.andl, rewrite forall_mem_singleton, apply h end lemma thm.andr [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (Γ ==> p::Δ) → thm (Γ ==> q::Δ) → thm (Γ ==> (p ∧' q)::Δ) := begin intros Γ Δ p q h1 h2, apply thm.inf, apply inf.andr, intros s hs, rewrite mem_cons_iff at hs, cases hs with hs hs, rewrite hs, apply h1, rewrite mem_singleton at hs, rewrite hs, apply h2 end lemma thm.orl [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (p::Γ ==> Δ) → thm (q::Γ ==> Δ) → thm ((p ∨' q)::Γ ==> Δ) := begin intros Γ Δ p q h1 h2, apply thm.inf, apply inf.orl, intros s hs, rewrite mem_cons_iff at hs, cases hs with hs hs, rewrite hs, apply h1, rewrite mem_singleton at hs, rewrite hs, apply h2 end lemma thm.orr [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (Γ ==> p::q::Δ) → thm (Γ ==> (p ∨' q)::Δ) := begin intros Γ Δ p q h, apply thm.inf, apply inf.orr, rewrite forall_mem_singleton, apply h end lemma thm.impl [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (Γ ==> p::Δ) → thm (q::Γ ==> Δ) → thm ((p →' q)::Γ ==> Δ) := begin intros Γ Δ p q h1 h2, apply thm.inf, apply inf.impl, intros s hs, rewrite mem_cons_iff at hs, cases hs with hs hs, rewrite hs, apply h1, rewrite mem_singleton at hs, rewrite hs, apply h2 end lemma thm.impr [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (p::Γ ==> q::Δ) → thm (Γ ==> (p →' q)::Δ) := begin intros Γ Δ p q h, apply thm.inf, apply inf.impr, rewrite forall_mem_singleton, apply h end lemma thm.wl [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (Γ ==> Δ) → thm (p::Γ ==> Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.wl, rewrite forall_mem_singleton, apply h end lemma thm.wr [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (Γ ==> Δ) → thm (Γ ==> p::Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.wr, rewrite forall_mem_singleton, apply h end lemma thm.cl [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (p::p::Γ ==> Δ) → thm (p::Γ ==> Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.cl, rewrite forall_mem_singleton, apply h end lemma thm.cr [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (Γ ==> p::p::Δ) → thm (Γ ==> p::Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.cr, rewrite forall_mem_singleton, apply h end lemma thm.rl [is_symb α] : ∀ n (Γ Δ : list (exp α)), thm (rotate n Γ ==> Δ) → thm (Γ ==> Δ) := begin intros n Γ Δ h, apply thm.inf, apply inf.pl (rotate n Γ), apply perm_rotate, intros s' hs', rewrite list.mem_singleton at hs', rewrite hs', apply h end lemma thm.rr [is_symb α] : ∀ n (Γ Δ : list (exp α)), thm (Γ ==> rotate n Δ) → thm (Γ ==> Δ) := begin intros n Γ Δ h, apply thm.inf, apply inf.pr _ (rotate n Δ), apply perm_rotate, intros s' hs', rewrite list.mem_singleton at hs', rewrite hs', apply h end /- Printing -/ open expr tactic meta def getsqt : tactic (list (exp symb) × list (exp symb)) := do `(thm (%%Γe ==> %%Δe)) ← tactic.target, Γ ← eval_expr (list (exp symb)) Γe, Δ ← eval_expr (list (exp symb)) Δe, return (Γ,Δ) def fml2str : exp symb → string | (exp.app (exp.cst s) p) := if s = (is_symb.not symb) then "¬" ++ fml2str p else "ERROR" | (exp.app (exp.app (exp.cst s) p) q) := if s = (is_symb.and symb) then "(" ++ fml2str p ++ " ∧ " ++ fml2str q ++ ")" else if s = (is_symb.or symb) then "(" ++ fml2str p ++ " ∨ " ++ fml2str q ++ ")" else if s = (is_symb.imp symb) then "(" ++ fml2str p ++ " → " ++ fml2str q ++ ")" else "ERROR" | (exp.cst s) := if s = is_symb.true symb then "⊤" else if s = is_symb.false symb then "⊥" else match s with | (symb.atom str) := str | _ := "ERROR" end | _ := "ERROR" meta def showgoal : tactic unit := (do (Γ,Δ) ← getsqt, trace (sqt2str fml2str Γ Δ)) <|> trace "No Goals" /- Examples (Hilbert System Axioms) -/ example : thm ([] ==> [A' "φ" →' A' "φ"]) := begin showgoal, apply thm.impr, apply thm.id, showgoal end example : thm ([] ==> [A' "φ" →' (A' "ψ" →' A' "φ")]) := begin showgoal, apply thm.impr, apply thm.impr, apply thm.rl 1, apply thm.id, showgoal end example : thm ([] ==> [(A' "φ" →' (A' "ψ" →' A' "χ")) →' ((A' "φ" →' A' "ψ") →' (A' "φ" →' A' "χ"))]) := begin showgoal, apply thm.impr, apply thm.impr, apply thm.impr, apply thm.rl 2, apply thm.impl, apply thm.rl 1, apply thm.id, apply thm.impl, apply thm.impl, apply thm.id, apply thm.id, apply thm.id, showgoal end end prop
af5fa40a92cd03899fba60c1a28809638266d5d2
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/measure_theory/function/continuous_map_dense.lean
15b69a5dc03822a7b562740fe2ef55db807e2f8a
[ "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
10,296
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import measure_theory.measure.regular import measure_theory.function.simple_func_dense import topology.urysohns_lemma /-! # Approximation in Lᵖ by continuous functions This file proves that bounded continuous functions are dense in `Lp E p μ`, for `1 ≤ p < ∞`, if the domain `α` of the functions is a normal topological space and the measure `μ` is weakly regular. The result is presented in several versions: * `measure_theory.Lp.bounded_continuous_function_dense`: The subgroup `measure_theory.Lp.bounded_continuous_function` of `Lp E p μ`, the additive subgroup of `Lp E p μ` consisting of equivalence classes containing a continuous representative, is dense in `Lp E p μ`. * `bounded_continuous_function.to_Lp_dense_range`: For finite-measure `μ`, the continuous linear map `bounded_continuous_function.to_Lp p μ 𝕜` from `α →ᵇ E` to `Lp E p μ` has dense range. * `continuous_map.to_Lp_dense_range`: For compact `α` and finite-measure `μ`, the continuous linear map `continuous_map.to_Lp p μ 𝕜` from `C(α, E)` to `Lp E p μ` has dense range. Note that for `p = ∞` this result is not true: the characteristic function of the set `[0, ∞)` in `ℝ` cannot be continuously approximated in `L∞`. The proof is in three steps. First, since simple functions are dense in `Lp`, it suffices to prove the result for a scalar multiple of a characteristic function of a measurable set `s`. Secondly, since the measure `μ` is weakly regular, the set `s` can be approximated above by an open set and below by a closed set. Finally, since the domain `α` is normal, we use Urysohn's lemma to find a continuous function interpolating between these two sets. ## Related results Are you looking for a result on "directional" approximation (above or below with respect to an order) of functions whose codomain is `ℝ≥0∞` or `ℝ`, by semicontinuous functions? See the Vitali-Carathéodory theorem, in the file `measure_theory.vitali_caratheodory`. -/ open_locale ennreal nnreal topological_space bounded_continuous_function open measure_theory topological_space continuous_map variables {α : Type*} [measurable_space α] [topological_space α] [normal_space α] [borel_space α] variables (E : Type*) [measurable_space E] [normed_group E] [borel_space E] [second_countable_topology E] variables {p : ℝ≥0∞} [_i : fact (1 ≤ p)] (hp : p ≠ ∞) (μ : measure α) include _i hp namespace measure_theory.Lp variables [normed_space ℝ E] /-- A function in `Lp` can be approximated in `Lp` by continuous functions. -/ lemma bounded_continuous_function_dense [μ.weakly_regular] : (bounded_continuous_function E p μ).topological_closure = ⊤ := begin have hp₀ : 0 < p := lt_of_lt_of_le ennreal.zero_lt_one _i.elim, have hp₀' : 0 ≤ 1 / p.to_real := div_nonneg zero_le_one ennreal.to_real_nonneg, have hp₀'' : 0 < p.to_real, { simpa [← ennreal.to_real_lt_to_real ennreal.zero_ne_top hp] using hp₀ }, -- It suffices to prove that scalar multiples of the indicator function of a finite-measure -- measurable set can be approximated by continuous functions suffices : ∀ (c : E) {s : set α} (hs : measurable_set s) (hμs : μ s < ⊤), (Lp.simple_func.indicator_const p hs hμs.ne c : Lp E p μ) ∈ (bounded_continuous_function E p μ).topological_closure, { rw add_subgroup.eq_top_iff', refine Lp.induction hp _ _ _ _, { exact this }, { exact λ f g hf hg hfg', add_subgroup.add_mem _ }, { exact add_subgroup.is_closed_topological_closure _ } }, -- Let `s` be a finite-measure measurable set, let's approximate `c` times its indicator function intros c s hs hsμ, refine mem_closure_iff_frequently.mpr _, rw metric.nhds_basis_closed_ball.frequently_iff, intros ε hε, -- A little bit of pre-emptive work, to find `η : ℝ≥0` which will be a margin small enough for -- our purposes obtain ⟨η, hη_pos, hη_le⟩ : ∃ η, 0 < η ∧ (↑(∥bit0 (∥c∥)∥₊ * (2 * η) ^ (1 / p.to_real)) : ℝ) ≤ ε, { have : filter.tendsto (λ x : ℝ≥0, ∥bit0 (∥c∥)∥₊ * (2 * x) ^ (1 / p.to_real)) (𝓝 0) (𝓝 0), { have : filter.tendsto (λ x : ℝ≥0, 2 * x) (𝓝 0) (𝓝 (2 * 0)) := filter.tendsto_id.const_mul 2, convert ((nnreal.continuous_at_rpow_const (or.inr hp₀')).tendsto.comp this).const_mul _, simp [hp₀''.ne'] }, let ε' : ℝ≥0 := ⟨ε, hε.le⟩, have hε' : 0 < ε' := by exact_mod_cast hε, obtain ⟨δ, hδ, hδε'⟩ := nnreal.nhds_zero_basis.eventually_iff.mp (eventually_le_of_tendsto_lt hε' this), obtain ⟨η, hη, hηδ⟩ := exists_between hδ, refine ⟨η, hη, _⟩, exact_mod_cast hδε' hηδ }, have hη_pos' : (0 : ℝ≥0∞) < ↑η := by exact_mod_cast hη_pos, -- Use the regularity of the measure to `η`-approximate `s` by an open superset and a closed -- subset obtain ⟨u, u_open, su, μu⟩ : ∃ u, is_open u ∧ s ⊆ u ∧ μ u < μ s + ↑η, { refine hs.exists_is_open_lt_of_lt _ _, simpa using (ennreal.add_lt_add_iff_left hsμ).2 hη_pos' }, obtain ⟨F, F_closed, Fs, μF⟩ : ∃ F, is_closed F ∧ F ⊆ s ∧ μ s < μ F + ↑η := hs.exists_lt_is_closed_of_lt_top_of_pos hsμ hη_pos', have : disjoint uᶜ F, { rw [set.disjoint_iff_inter_eq_empty, set.inter_comm, ← set.subset_compl_iff_disjoint], simpa using Fs.trans su }, have h_μ_sdiff : μ (u \ F) ≤ 2 * η, { have hFμ : μ F < ⊤ := (measure_mono Fs).trans_lt hsμ, refine ennreal.le_of_add_le_add_left hFμ _, have : μ u < μ F + ↑η + ↑η, { refine μu.trans _, rwa ennreal.add_lt_add_iff_right (ennreal.coe_lt_top : ↑η < ⊤) }, convert this.le using 1, { rw [add_comm, ← measure_union, set.diff_union_of_subset (Fs.trans su)], { exact disjoint_sdiff_self_left }, { exact (u_open.sdiff F_closed).measurable_set }, { exact F_closed.measurable_set } }, have : (2:ℝ≥0∞) * η = η + η := by simpa using add_mul (1:ℝ≥0∞) 1 η, rw this, abel }, -- Apply Urysohn's lemma to get a continuous approximation to the characteristic function of -- the set `s` obtain ⟨g, hgu, hgF, hg_range⟩ := exists_continuous_zero_one_of_closed u_open.is_closed_compl F_closed this, -- Multiply this by `c` to get a continuous approximation to the function `f`; the key point is -- that this is pointwise bounded by the indicator of the set `u \ F` have g_norm : ∀ x, ∥g x∥ = g x := λ x, by rw [real.norm_eq_abs, abs_of_nonneg (hg_range x).1], have gc_bd : ∀ x, ∥g x • c - s.indicator (λ x, c) x∥ ≤ ∥(u \ F).indicator (λ x, bit0 ∥c∥) x∥, { intros x, by_cases hu : x ∈ u, { rw ← set.diff_union_of_subset (Fs.trans su) at hu, cases hu with hFu hF, { refine (norm_sub_le _ _).trans _, refine (add_le_add_left (norm_indicator_le_norm_self (λ x, c) x) _).trans _, have h₀ : g x * ∥c∥ + ∥c∥ ≤ 2 * ∥c∥, { nlinarith [(hg_range x).1, (hg_range x).2, norm_nonneg c] }, have h₁ : (2:ℝ) * ∥c∥ = bit0 (∥c∥) := by simpa using add_mul (1:ℝ) 1 (∥c∥), simp [hFu, norm_smul, h₀, ← h₁, g_norm x] }, { simp [hgF hF, Fs hF] } }, { have : x ∉ s := λ h, hu (su h), simp [hgu hu, this] } }, -- The rest is basically just `ennreal`-arithmetic have gc_snorm : snorm ((λ x, g x • c) - s.indicator (λ x, c)) p μ ≤ (↑(∥bit0 (∥c∥)∥₊ * (2 * η) ^ (1 / p.to_real)) : ℝ≥0∞), { refine (snorm_mono_ae (filter.eventually_of_forall gc_bd)).trans _, rw snorm_indicator_const (u_open.sdiff F_closed).measurable_set hp₀.ne' hp, push_cast [← ennreal.coe_rpow_of_nonneg _ hp₀'], exact ennreal.mul_left_mono (ennreal.rpow_left_monotone_of_nonneg hp₀' h_μ_sdiff) }, have gc_cont : continuous (λ x, g x • c) := g.continuous.smul continuous_const, have gc_mem_ℒp : mem_ℒp (λ x, g x • c) p μ, { have : mem_ℒp ((λ x, g x • c) - s.indicator (λ x, c)) p μ := ⟨(gc_cont.ae_measurable μ).sub (measurable_const.indicator hs).ae_measurable, gc_snorm.trans_lt ennreal.coe_lt_top⟩, simpa using this.add (mem_ℒp_indicator_const p hs c (or.inr hsμ.ne)) }, refine ⟨gc_mem_ℒp.to_Lp _, _, _⟩, { rw mem_closed_ball_iff_norm, refine le_trans _ hη_le, rw [simple_func.coe_indicator_const, indicator_const_Lp, ← mem_ℒp.to_Lp_sub, Lp.norm_to_Lp], exact ennreal.to_real_le_coe_of_le_coe gc_snorm }, { rw [set_like.mem_coe, mem_bounded_continuous_function_iff], refine ⟨bounded_continuous_function.of_normed_group _ gc_cont (∥c∥) _, rfl⟩, intros x, have h₀ : g x * ∥c∥ ≤ ∥c∥, { nlinarith [(hg_range x).1, (hg_range x).2, norm_nonneg c] }, simp [norm_smul, g_norm x, h₀] }, end end measure_theory.Lp variables (𝕜 : Type*) [measurable_space 𝕜] [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_algebra ℝ 𝕜] [normed_space 𝕜 E] namespace bounded_continuous_function lemma to_Lp_dense_range [μ.weakly_regular] [finite_measure μ] : dense_range ⇑(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] Lp E p μ) := begin haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E, rw dense_range_iff_closure_range, suffices : (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ).range.to_add_subgroup.topological_closure = ⊤, { exact congr_arg coe this }, simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp], end end bounded_continuous_function namespace continuous_map lemma to_Lp_dense_range [compact_space α] [μ.weakly_regular] [finite_measure μ] : dense_range ⇑(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] Lp E p μ) := begin haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E, rw dense_range_iff_closure_range, suffices : (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ).range.to_add_subgroup.topological_closure = ⊤, { exact congr_arg coe this }, simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp] end end continuous_map
13b78b86ea803f44fe51a878f7c03b4a16d3c7f3
041929c569a4eeeafb4efdddab8a644f6df383c5
/src/mazes/gcd_maze/level85.lean
314be0f455b248d98dd330f82ff4564cfdd0f8b2
[]
no_license
kbuzzard/xena-maze-game
30ffbe956762dd6603e74efd823d375649e037c3
098454dd6acc4c06beccf52b6547bf4cd99cc581
refs/heads/master
1,670,840,300,174
1,598,554,198,000
1,598,554,198,000
290,856,036
4
0
null
null
null
null
UTF-8
Lean
false
false
656
lean
-- import the definition of the gcd maze import mazes.gcd_maze.definition import data.int.gcd open maze direction /- # Bezout's Theorem Example maze. You are in a maze of integers, all distinct. You can go north, south east or west. North adds 8 to your integer, South subtracts 8. East adds 5 to your integer, West subtracts 5 The exit is at 1, the gcd of 8 and 5. When you're at the exit, type `out`. Solver remark : there are infinitely many rooms. -/ /- Lemma : no-side-bar Can you prove this case of Bezout's Theorem? -/ example : can_escape 8 5 0 := begin iterate 2 {n}, iterate 3 {w}, out end -- #eval nat.xgcd 8 5 -- (2, -3) -- hide
9998e77584d9f050c066e0fde428e0259beca57c
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/analysis/topology.lean
4e1527dc374a3a290db3f4039e11ded5dbcdc713
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
8,441
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Computational realization of topological spaces (experimental). -/ import analysis.topology.topological_space data.analysis.filter open set open filter (hiding realizer) /-- A `ctop α σ` is a realization of a topology (basis) on `α`, represented by a type `σ` together with operations for the top element and the intersection operation. -/ structure ctop (α σ : Type*) := (f : σ → set α) (top : α → σ) (top_mem : ∀ x : α, x ∈ f (top x)) (inter : Π a b (x : α), x ∈ f a ∩ f b → σ) (inter_mem : ∀ a b x h, x ∈ f (inter a b x h)) (inter_sub : ∀ a b x h, f (inter a b x h) ⊆ f a ∩ f b) variables {α : Type*} {β : Type*} {σ : Type*} {τ : Type*} namespace ctop section variables (F : ctop α σ) instance : has_coe_to_fun (ctop α σ) := ⟨_, ctop.f⟩ @[simp] theorem coe_mk (f T h₁ I h₂ h₃ a) : (@ctop.mk α σ f T h₁ I h₂ h₃) a = f a := rfl /-- Map a ctop to an equivalent representation type. -/ def of_equiv (E : σ ≃ τ) : ctop α σ → ctop α τ | ⟨f, T, h₁, I, h₂, h₃⟩ := { f := λ a, f (E.symm a), top := λ x, E (T x), top_mem := λ x, by simpa using h₁ x, inter := λ a b x h, E (I (E.symm a) (E.symm b) x h), inter_mem := λ a b x h, by simpa using h₂ (E.symm a) (E.symm b) x h, inter_sub := λ a b x h, by simpa using h₃ (E.symm a) (E.symm b) x h } @[simp] theorem of_equiv_val (E : σ ≃ τ) (F : ctop α σ) (a : τ) : F.of_equiv E a = F (E.symm a) := by cases F; refl end instance to_topsp (F : ctop α σ) : topological_space α := topological_space.generate_from (set.range F.f) theorem to_topsp_is_topological_basis (F : ctop α σ) : @topological_space.is_topological_basis _ F.to_topsp (set.range F.f) := ⟨λ u ⟨a, e₁⟩ v ⟨b, e₂⟩, e₁ ▸ e₂ ▸ λ x h, ⟨_, ⟨_, rfl⟩, F.inter_mem a b x h, F.inter_sub a b x h⟩, eq_univ_iff_forall.2 $ λ x, ⟨_, ⟨_, rfl⟩, F.top_mem x⟩, rfl⟩ @[simp] theorem mem_nhds_to_topsp (F : ctop α σ) {s : set α} {a : α} : s ∈ (@nhds _ F.to_topsp a).sets ↔ ∃ b, a ∈ F b ∧ F b ⊆ s := (@topological_space.mem_nhds_of_is_topological_basis _ F.to_topsp _ _ _ F.to_topsp_is_topological_basis).trans $ ⟨λ ⟨_, ⟨x, rfl⟩, h⟩, ⟨x, h⟩, λ ⟨x, h⟩, ⟨_, ⟨x, rfl⟩, h⟩⟩ end ctop /-- A `ctop` realizer for the topological space `T` is a `ctop` which generates `T`. -/ structure ctop.realizer (α) [T : topological_space α] := (σ : Type*) (F : ctop α σ) (eq : F.to_topsp = T) open ctop protected def ctop.to_realizer (F : ctop α σ) : @ctop.realizer _ F.to_topsp := @ctop.realizer.mk _ F.to_topsp σ F rfl namespace ctop.realizer protected theorem is_basis [T : topological_space α] (F : realizer α) : topological_space.is_topological_basis (set.range F.F.f) := by have := to_topsp_is_topological_basis F.F; rwa F.eq at this protected theorem mem_nhds [T : topological_space α] (F : realizer α) {s : set α} {a : α} : s ∈ (nhds a).sets ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := by have := mem_nhds_to_topsp F.F; rwa F.eq at this theorem is_open_iff [topological_space α] (F : realizer α) {s : set α} : is_open s ↔ ∀ a ∈ s, ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := is_open_iff_mem_nhds.trans $ ball_congr $ λ a h, F.mem_nhds theorem is_closed_iff [topological_space α] (F : realizer α) {s : set α} : is_closed s ↔ ∀ a, (∀ b, a ∈ F.F b → ∃ z, z ∈ F.F b ∩ s) → a ∈ s := F.is_open_iff.trans $ forall_congr $ λ a, show (a ∉ s → (∃ (b : F.σ), a ∈ F.F b ∧ ∀ z ∈ F.F b, z ∉ s)) ↔ _, by haveI := classical.prop_decidable; rw [not_imp_comm]; simp [not_exists, not_and, not_forall, and_comm] theorem mem_interior_iff [topological_space α] (F : realizer α) {s : set α} {a : α} : a ∈ interior s ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := mem_interior_iff_mem_nhds.trans F.mem_nhds protected theorem is_open [topological_space α] (F : realizer α) (s : F.σ) : is_open (F.F s) := is_open_iff_nhds.2 $ λ a m, by simpa using F.mem_nhds.2 ⟨s, m, subset.refl _⟩ theorem ext' [T : topological_space α] {σ : Type*} {F : ctop α σ} (H : ∀ a s, s ∈ (nhds a).sets ↔ ∃ b, a ∈ F b ∧ F b ⊆ s) : F.to_topsp = T := topological_space_eq $ funext $ λ s, begin have : ∀ T s, @topological_space.is_open _ T s ↔ _ := @is_open_iff_mem_nhds α, rw [this, this], apply congr_arg (λ f : α → filter α, ∀ a ∈ s, s ∈ (f a).sets), funext a, apply filter_eq, apply set.ext, intro x, rw [mem_nhds_to_topsp, H] end theorem ext [T : topological_space α] {σ : Type*} {F : ctop α σ} (H₁ : ∀ a, is_open (F a)) (H₂ : ∀ a s, s ∈ (nhds a).sets → ∃ b, a ∈ F b ∧ F b ⊆ s) : F.to_topsp = T := ext' $ λ a s, ⟨H₂ a s, λ ⟨b, h₁, h₂⟩, mem_nhds_sets_iff.2 ⟨_, h₂, H₁ _, h₁⟩⟩ variable [topological_space α] protected def id : realizer α := ⟨{x:set α // is_open x}, { f := subtype.val, top := λ _, ⟨univ, is_open_univ⟩, top_mem := mem_univ, inter := λ ⟨x, h₁⟩ ⟨y, h₂⟩ a h₃, ⟨_, is_open_inter h₁ h₂⟩, inter_mem := λ ⟨x, h₁⟩ ⟨y, h₂⟩ a, id, inter_sub := λ ⟨x, h₁⟩ ⟨y, h₂⟩ a h₃, subset.refl _ }, ext subtype.property $ λ x s h, let ⟨t, h, o, m⟩ := mem_nhds_sets_iff.1 h in ⟨⟨t, o⟩, m, h⟩⟩ def of_equiv (F : realizer α) (E : F.σ ≃ τ) : realizer α := ⟨τ, F.F.of_equiv E, ext' (λ a s, F.mem_nhds.trans $ ⟨λ ⟨s, h⟩, ⟨E s, by simpa using h⟩, λ ⟨t, h⟩, ⟨E.symm t, by simpa using h⟩⟩)⟩ @[simp] theorem of_equiv_σ (F : realizer α) (E : F.σ ≃ τ) : (F.of_equiv E).σ = τ := rfl @[simp] theorem of_equiv_F (F : realizer α) (E : F.σ ≃ τ) (s : τ) : (F.of_equiv E).F s = F.F (E.symm s) := by delta of_equiv; simp protected def nhds (F : realizer α) (a : α) : (nhds a).realizer := ⟨{s : F.σ // a ∈ F.F s}, { f := λ s, F.F s.1, pt := ⟨_, F.F.top_mem a⟩, inf := λ ⟨x, h₁⟩ ⟨y, h₂⟩, ⟨_, F.F.inter_mem x y a ⟨h₁, h₂⟩⟩, inf_le_left := λ ⟨x, h₁⟩ ⟨y, h₂⟩ z h, (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).1, inf_le_right := λ ⟨x, h₁⟩ ⟨y, h₂⟩ z h, (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).2 }, filter_eq $ set.ext $ λ x, ⟨λ ⟨⟨s, as⟩, h⟩, mem_nhds_sets_iff.2 ⟨_, h, F.is_open _, as⟩, λ h, let ⟨s, h, as⟩ := F.mem_nhds.1 h in ⟨⟨s, h⟩, as⟩⟩⟩ @[simp] theorem nhds_σ (m : α → β) (F : realizer α) (a : α) : (F.nhds a).σ = {s : F.σ // a ∈ F.F s} := rfl @[simp] theorem nhds_F (m : α → β) (F : realizer α) (a : α) (s) : (F.nhds a).F s = F.F s.1 := rfl theorem tendsto_nhds_iff {m : β → α} {f : filter β} (F : f.realizer) (R : realizer α) {a : α} : tendsto m f (nhds a) ↔ ∀ t, a ∈ R.F t → ∃ s, ∀ x ∈ F.F s, m x ∈ R.F t := (F.tendsto_iff _ (R.nhds a)).trans subtype.forall end ctop.realizer structure locally_finite.realizer [topological_space α] (F : realizer α) (f : β → set α) := (bas : ∀ a, {s // a ∈ F.F s}) (sets : ∀ x:α, fintype {i | f i ∩ F.F (bas x) ≠ ∅}) theorem locally_finite.realizer.to_locally_finite [topological_space α] {F : realizer α} {f : β → set α} (R : locally_finite.realizer F f) : locally_finite f := λ a, ⟨_, F.mem_nhds.2 ⟨(R.bas a).1, (R.bas a).2, subset.refl _⟩, ⟨R.sets a⟩⟩ theorem locally_finite_iff_exists_realizer [topological_space α] (F : realizer α) {f : β → set α} : locally_finite f ↔ nonempty (locally_finite.realizer F f) := ⟨λ h, let ⟨g, h₁⟩ := classical.axiom_of_choice h, ⟨g₂, h₂⟩ := classical.axiom_of_choice (λ x, show ∃ (b : F.σ), x ∈ (F.F) b ∧ (F.F) b ⊆ g x, from let ⟨h, h'⟩ := h₁ x in F.mem_nhds.1 h) in ⟨⟨λ x, ⟨g₂ x, (h₂ x).1⟩, λ x, finite.fintype $ let ⟨h, h'⟩ := h₁ x in finite_subset h' $ λ i, subset_ne_empty (inter_subset_inter_right _ (h₂ x).2)⟩⟩, λ ⟨R⟩, R.to_locally_finite⟩ def compact.realizer [topological_space α] (R : realizer α) (s : set α) := ∀ {f : filter α} (F : f.realizer) (x : F.σ), f ≠ ⊥ → F.F x ⊆ s → {a // a∈s ∧ nhds a ⊓ f ≠ ⊥}
1b07f66d65fcb8a008485256731c23f8d060867d
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simp9.lean
d09fd4588b7fc8692928397d958fbdaac02ef54d
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
349
lean
variables a b c d e f : Nat rewrite_set simple add_rewrite Nat::mul_assoc Nat::mul_comm Nat::mul_left_comm Nat::add_assoc Nat::add_comm Nat::add_left_comm Nat::distributer Nat::distributel : simple (* local t = parse_lean("(a + b) * (c + d) * (e + f) * (a + b) * (c + d) * (e + f)") local t2, pr = simplify(t, "simple") print(t) *)
725265c9f632cffa9598818befa3e7a0a82afa3a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/overflow2.lean
b2cfb8046ac229eabc0cbb60a7e49e8181a0d6b2
[ "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
448
lean
def longArray (n : Nat := 50000) (xs : Array Char := #[]) : Array Char := match n with | 0 => xs | n+1 => longArray n (xs.push 'a') def OverflowFold {m : Type -> Type} [inst1: Monad m] (xs: Array Char) : StateT Nat m Nat := xs.foldlM (fun (len : Nat) (s : Char) => match s with | 'z' => panic "z" | _ => return len + 1) 0 def main : IO Unit := let x := (StateT.run (@OverflowFold Id _ longArray) 0).fst IO.println x
c2a586df3234af69a65e810cee44eb6c1530569d
fd71e7836e9a5d14548f6d3291653cbb6c608dbe
/src/test/slim_check/gen.lean
1c4d5e0287b56ee0b97bae953db5c9eb45501fb2
[]
no_license
cipher1024/slim_check
382c80a98aed105a97eeac84f590a06dca4d8c7d
5969b7f72e01fdd46f2502ed0cbf69c0699061d4
refs/heads/master
1,625,514,334,828
1,574,118,572,000
1,574,118,572,000
101,538,155
2
1
null
null
null
null
UTF-8
Lean
false
false
2,702
lean
import test.random import system.random import test.slim_check.liftable universes u v @[reducible] def gen (α : Type u) := reader_t (ulift ℕ) rand α -- namespace gen -- variables {α β γ : Type u} -- protected def pure (x : α) : gen α := -- λ _, pure x -- protected def bind (x : gen α) (f : α → gen β) : gen β -- | sz := do -- i ← x sz, -- f i sz -- instance : has_bind gen := -- ⟨ @gen.bind ⟩ -- instance : has_pure gen := -- ⟨ @gen.pure ⟩ -- lemma bind_assoc (x : gen α) (f : α → gen β) (g : β → gen γ) -- : x >>= f >>= g = x >>= (λ i, f i >>= g) := -- begin -- funext sz, -- simp [has_bind.bind], -- simp [gen.bind,monad.bind_assoc], -- end -- lemma pure_bind (x : α) (f : α → gen β) -- : pure x >>= f = f x := -- begin -- funext i, -- simp [has_bind.bind], -- simp [gen.bind,monad.pure_bind], -- refl -- end -- lemma id_map (x : gen α) -- : x >>= pure ∘ id = x := -- begin -- funext i, -- simp [has_bind.bind,function.comp,pure,has_pure.pure], -- simp [gen.bind,gen.pure], -- rw monad.bind_pure, -- exact α, -- end -- end gen -- instance : monad gen := -- { pure := @gen.pure -- , bind := @gen.bind -- , bind_assoc := @gen.bind_assoc -- , pure_bind := @gen.pure_bind -- , id_map := @gen.id_map } variable (α : Type u) section random variable [random α] def choose_any : gen α := ⟨ λ _, random.random α _ ⟩ variables {α} def choose (x y : α) (p : x ≤ y . check_range) : gen (x .. y) := ⟨ λ _, random.random_r _ x y p ⟩ end random open nat (hiding choose) def choose_nat (x y : ℕ) (p : x ≤ y . check_range) : gen (x .. y) := do ⟨z,h⟩ ← @choose (fin $ succ y) _ ⟨x,succ_le_succ p⟩ ⟨y,lt_succ_self _⟩ p, have h' : x ≤ z.val ∧ z.val ≤ y, by { simp [fin.le_def] at h, apply h }, return ⟨z.val,h'⟩ open nat namespace gen variable {α} instance : liftable gen.{u} gen.{v} := reader_t.liftable' (equiv.ulift.trans equiv.ulift.symm) set_option pp.universes true -- begin -- reader_t.liftable -- end end gen variable {α} def sized (cmd : ℕ → gen α) : gen α := ⟨ λ ⟨sz⟩, (cmd sz).run ⟨sz⟩ ⟩ def vector_of : ∀ (n : ℕ) (cmd : gen α), gen (vector α n) | 0 _ := return vector.nil | (succ n) cmd := vector.cons <$> cmd <*> vector_of n cmd def list_of (cmd : gen α) : gen (list α) := sized $ λ sz, do do ⟨ n ⟩ ← liftable.up' $ choose_nat 0 sz, v ← vector_of n.val cmd, return v.to_list open ulift def one_of (xs : list (gen α)) (pos : 0 < xs.length) : gen α := have _inst : random _ := random_fin_of_pos _ pos, do n ← liftable.up' $ @choose_any (fin xs.length) _inst, list.nth_le xs (down n).val (down n).is_lt
1f725f0fb1f56db9df9b0a9fbdb704ade6318b57
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/592.lean
3b8584da48e4c2a210b259cc4ecdfafc0d7cc6fe
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
135
lean
import data.nat open nat definition foo (a b : nat) := a * b example (a : nat) : foo a 0 = 0 := calc a * 0 = 0 : by rewrite mul_zero
667f3567cdd45184961d62601e310f467cd42f64
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/mathd-algebra-113.lean
d78204a5ce72b488de46dd6cddddea5b15ca4e9d
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
247
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic example (x : ℝ) : x^2 - 14 * x + 3 ≥ 7^2 - 14 * 7 + 3 := begin sorry end
92b8b2bd8c750c6b0baf9210ffe4f60bfed1b0e1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/shapes/kernels.lean
b2a193257f7732d13df32b94a9d0521695763807
[ "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
37,314
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.preserves.shapes.zero /-! # Kernels and cokernels In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is the equalizer of `f` and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.) The basic definitions are * `kernel : (X ⟶ Y) → C` * `kernel.ι : kernel f ⟶ X` * `kernel.condition : kernel.ι f ≫ f = 0` and * `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions) ## Main statements Besides the definition and lifts, we prove * `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism * `kernel.eq_zero_of_epi_kernel`: if `kernel.ι f` is an epimorphism, then `f = 0` * `kernel.of_mono`: the kernel of a monomorphism is the zero object * `kernel.lift_mono`: the lift of a monomorphism `k : W ⟶ X` such that `k ≫ f = 0` is still a monomorphism * `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero obect is a kernel map of any monomorphism * `kernel.ι_of_zero`: `kernel.ι (0 : X ⟶ Y)` is an isomorphism and the corresponding dual statements. ## Future work * TODO: connect this with existing working in the group theory and ring theory libraries. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v v₂ u u' u₂ open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables [has_zero_morphisms C] /-- A morphism `f` has a kernel if the functor `parallel_pair f 0` has a limit. -/ abbreviation has_kernel {X Y : C} (f : X ⟶ Y) : Prop := has_limit (parallel_pair f 0) /-- A morphism `f` has a cokernel if the functor `parallel_pair f 0` has a colimit. -/ abbreviation has_cokernel {X Y : C} (f : X ⟶ Y) : Prop := has_colimit (parallel_pair f 0) variables {X Y : C} (f : X ⟶ Y) section /-- A kernel fork is just a fork where the second morphism is a zero morphism. -/ abbreviation kernel_fork := fork f 0 variables {f} @[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ι s ≫ f = 0 := by erw [fork.condition, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.π.app one = 0 := by simp [fork.app_one_eq_ι_comp_right] /-- A morphism `ι` satisfying `ι ≫ f = 0` determines a kernel fork over `f`. -/ abbreviation kernel_fork.of_ι {Z : C} (ι : Z ⟶ X) (w : ι ≫ f = 0) : kernel_fork f := fork.of_ι ι $ by rw [w, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.ι_of_ι {X Y P : C} (f : X ⟶ Y) (ι : P ⟶ X) (w : ι ≫ f = 0) : fork.ι (kernel_fork.of_ι ι w) = ι := rfl section local attribute [tidy] tactic.case_bash /-- Every kernel fork `s` is isomorphic (actually, equal) to `fork.of_ι (fork.ι s) _`. -/ def iso_of_ι (s : fork f 0) : s ≅ fork.of_ι (fork.ι s) (fork.condition s) := cones.ext (iso.refl _) $ by tidy /-- If `ι = ι'`, then `fork.of_ι ι _` and `fork.of_ι ι' _` are isomorphic. -/ def of_ι_congr {P : C} {ι ι' : P ⟶ X} {w : ι ≫ f = 0} (h : ι = ι') : kernel_fork.of_ι ι w ≅ kernel_fork.of_ι ι' (by rw [←h, w]) := cones.ext (iso.refl _) $ by tidy /-- If `F` is an equivalence, then applying `F` to a diagram indexing a (co)kernel of `f` yields the diagram indexing the (co)kernel of `F.map f`. -/ def comp_nat_iso {D : Type u'} [category.{v} D] [has_zero_morphisms D] (F : C ⥤ D) [is_equivalence F] : parallel_pair f 0 ⋙ F ≅ parallel_pair (F.map f) 0 := nat_iso.of_components (λ j, match j with | zero := iso.refl _ | one := iso.refl _ end) $ by tidy end /-- If `s` is a limit kernel fork and `k : W ⟶ X` satisfies ``k ≫ f = 0`, then there is some `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def kernel_fork.is_limit.lift' {s : kernel_fork f} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ kernel_fork.of_ι _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a kernel fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : kernel_fork f) (lift : Π (s : kernel_fork f), s.X ⟶ t.X) (fac : ∀ (s : kernel_fork f), lift s ≫ t.ι = s.ι) (uniq : ∀ (s : kernel_fork f) (m : s.X ⟶ t.X) (w : m ≫ t.ι = s.ι), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, by { cases j, { exact fac s, }, { simp, }, }, uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.zero), } /-- This is a more convenient formulation to show that a `kernel_fork` constructed using `kernel_fork.of_ι` is a limit cone. -/ def kernel_fork.is_limit.of_ι {W : C} (g : W ⟶ X) (eq : g ≫ f = 0) (lift : Π {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), W' ⟶ W) (fac : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), lift g' eq' ≫ g = g') (uniq : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0) (m : W' ⟶ W) (w : m ≫ g = g'), m = lift g' eq') : is_limit (kernel_fork.of_ι g eq) := is_limit_aux _ (λ s, lift s.ι s.condition) (λ s, fac s.ι s.condition) (λ s, uniq s.ι s.condition) /-- Every kernel of `f` induces a kernel of `f ≫ g` if `g` is mono. -/ def is_kernel_comp_mono {c : kernel_fork f} (i : is_limit c) {Z} (g : Y ⟶ Z) [hg : mono g] {h : X ⟶ Z} (hh : h = f ≫ g) : is_limit (kernel_fork.of_ι c.ι (by simp [hh]) : kernel_fork h) := fork.is_limit.mk' _ $ λ s, let s' : kernel_fork f := fork.of_ι s.ι (by rw [←cancel_mono g]; simp [←hh, s.condition]) in let l := kernel_fork.is_limit.lift' i s'.ι s'.condition in ⟨l.1, l.2, λ m hm, by apply fork.is_limit.hom_ext i; rw fork.ι_of_ι at hm; rw hm; exact l.2.symm⟩ lemma is_kernel_comp_mono_lift {c : kernel_fork f} (i : is_limit c) {Z} (g : Y ⟶ Z) [hg : mono g] {h : X ⟶ Z} (hh : h = f ≫ g) (s : kernel_fork h) : (is_kernel_comp_mono i g hh).lift s = i.lift (fork.of_ι s.ι (by { rw [←cancel_mono g, category.assoc, ←hh], simp })) := rfl /-- Every kernel of `f ≫ g` is also a kernel of `f`, as long as `c.ι ≫ f` vanishes. -/ def is_kernel_of_comp {W : C} (g : Y ⟶ W) (h : X ⟶ W) {c : kernel_fork h} (i : is_limit c) (hf : c.ι ≫ f = 0) (hfg : f ≫ g = h) : is_limit (kernel_fork.of_ι c.ι hf) := fork.is_limit.mk _ (λ s, i.lift (kernel_fork.of_ι s.ι (by simp [← hfg]))) (λ s, by simp only [kernel_fork.ι_of_ι, fork.is_limit.lift_ι]) (λ s m h, by { apply fork.is_limit.hom_ext i, simpa using h }) end section variables [has_kernel f] /-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/ abbreviation kernel : C := equalizer f 0 /-- The map from `kernel f` into the source of `f`. -/ abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0 @[simp] lemma equalizer_as_kernel : equalizer.ι f 0 = kernel.ι f := rfl @[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 := kernel_fork.condition _ /-- The kernel built from `kernel.ι f` is limiting. -/ def kernel_is_kernel : is_limit (fork.of_ι (kernel.ι f) ((kernel.condition f).trans (comp_zero.symm))) := is_limit.of_iso_limit (limit.is_limit _) (fork.ext (iso.refl _) (by tidy)) /-- Given any morphism `k : W ⟶ X` satisfying `k ≫ f = 0`, `k` factors through `kernel.ι f` via `kernel.lift : W ⟶ kernel f`. -/ abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f := limit.lift (parallel_pair f 0) (kernel_fork.of_ι k h) @[simp, reassoc] lemma kernel.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : kernel.lift f k h ≫ kernel.ι f = k := limit.lift_π _ _ @[simp] lemma kernel.lift_zero {W : C} {h} : kernel.lift f (0 : W ⟶ X) h = 0 := by { ext, simp, } instance kernel.lift_mono {W : C} (k : W ⟶ X) (h : k ≫ f = 0) [mono k] : mono (kernel.lift f k h) := ⟨λ Z g g' w, begin replace w := w =≫ kernel.ι f, simp only [category.assoc, kernel.lift_ι] at w, exact (cancel_mono k).1 w, end⟩ /-- Any morphism `k : W ⟶ X` satisfying `k ≫ f = 0` induces a morphism `l : W ⟶ kernel f` such that `l ≫ kernel.ι f = k`. -/ def kernel.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ kernel f // l ≫ kernel.ι f = k} := ⟨kernel.lift f k h, kernel.lift_ι _ _ _⟩ /-- A commuting square induces a morphism of kernels. -/ abbreviation kernel.map {X' Y' : C} (f' : X' ⟶ Y') [has_kernel f'] (p : X ⟶ X') (q : Y ⟶ Y') (w : f ≫ q = p ≫ f') : kernel f ⟶ kernel f' := kernel.lift f' (kernel.ι f ≫ p) (by simp [←w]) /-- Given a commutative diagram X --f--> Y --g--> Z | | | | | | v v v X' -f'-> Y' -g'-> Z' with horizontal arrows composing to zero, then we obtain a commutative square X ---> kernel g | | | | kernel.map | | v v X' --> kernel g' -/ lemma kernel.lift_map {X Y Z X' Y' Z' : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel g] (w : f ≫ g = 0) (f' : X' ⟶ Y') (g' : Y' ⟶ Z') [has_kernel g'] (w' : f' ≫ g' = 0) (p : X ⟶ X') (q : Y ⟶ Y') (r : Z ⟶ Z') (h₁ : f ≫ q = p ≫ f') (h₂ : g ≫ r = q ≫ g') : kernel.lift g f w ≫ kernel.map g g' q r h₂ = p ≫ kernel.lift g' f' w' := by { ext, simp [h₁], } /-- A commuting square of isomorphisms induces an isomorphism of kernels. -/ @[simps] def kernel.map_iso {X' Y' : C} (f' : X' ⟶ Y') [has_kernel f'] (p : X ≅ X') (q : Y ≅ Y') (w : f ≫ q.hom = p.hom ≫ f') : kernel f ≅ kernel f' := { hom := kernel.map f f' p.hom q.hom w, inv := kernel.map f' f p.inv q.inv (by { refine (cancel_mono q.hom).1 _, simp [w], }), } /-- Every kernel of the zero morphism is an isomorphism -/ instance kernel.ι_zero_is_iso : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ lemma eq_zero_of_epi_kernel [epi (kernel.ι f)] : f = 0 := (cancel_epi (kernel.ι f)).1 (by simp) /-- The kernel of a zero morphism is isomorphic to the source. -/ def kernel_zero_iso_source : kernel (0 : X ⟶ Y) ≅ X := equalizer.iso_source_of_self 0 @[simp] lemma kernel_zero_iso_source_hom : kernel_zero_iso_source.hom = kernel.ι (0 : X ⟶ Y) := rfl @[simp] lemma kernel_zero_iso_source_inv : kernel_zero_iso_source.inv = kernel.lift (0 : X ⟶ Y) (𝟙 X) (by simp) := by { ext, simp [kernel_zero_iso_source], } /-- If two morphisms are known to be equal, then their kernels are isomorphic. -/ def kernel_iso_of_eq {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) : kernel f ≅ kernel g := has_limit.iso_of_nat_iso (by simp[h]) @[simp] lemma kernel_iso_of_eq_refl {h : f = f} : kernel_iso_of_eq h = iso.refl (kernel f) := by { ext, simp [kernel_iso_of_eq], } @[simp, reassoc] lemma kernel_iso_of_eq_hom_comp_ι {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) : (kernel_iso_of_eq h).hom ≫ kernel.ι _ = kernel.ι _ := by { unfreezingI { induction h, simp } } @[simp, reassoc] lemma kernel_iso_of_eq_inv_comp_ι {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) : (kernel_iso_of_eq h).inv ≫ kernel.ι _ = kernel.ι _ := by { unfreezingI { induction h, simp } } @[simp, reassoc] lemma lift_comp_kernel_iso_of_eq_hom {Z} {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) (e : Z ⟶ X) (he) : kernel.lift _ e he ≫ (kernel_iso_of_eq h).hom = kernel.lift _ e (by simp [← h, he]) := by { unfreezingI { induction h, simp } } @[simp, reassoc] lemma lift_comp_kernel_iso_of_eq_inv {Z} {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) (e : Z ⟶ X) (he) : kernel.lift _ e he ≫ (kernel_iso_of_eq h).inv = kernel.lift _ e (by simp [h, he]) := by { unfreezingI { induction h, simp } } @[simp] lemma kernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_kernel f] [has_kernel g] [has_kernel h] (w₁ : f = g) (w₂ : g = h) : kernel_iso_of_eq w₁ ≪≫ kernel_iso_of_eq w₂ = kernel_iso_of_eq (w₁.trans w₂) := by { unfreezingI { induction w₁, induction w₂, }, ext, simp [kernel_iso_of_eq], } variables {f} lemma kernel_not_epi_of_nonzero (w : f ≠ 0) : ¬epi (kernel.ι f) := λ I, by exactI w (eq_zero_of_epi_kernel f) lemma kernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (kernel.ι f)) → false := λ I, kernel_not_epi_of_nonzero w $ by { resetI, apply_instance } instance has_kernel_comp_mono {X Y Z : C} (f : X ⟶ Y) [has_kernel f] (g : Y ⟶ Z) [mono g] : has_kernel (f ≫ g) := ⟨⟨{ cone := _, is_limit := is_kernel_comp_mono (limit.is_limit _) g rfl }⟩⟩ /-- When `g` is a monomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `f`. -/ @[simps] def kernel_comp_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel f] [mono g] : kernel (f ≫ g) ≅ kernel f := { hom := kernel.lift _ (kernel.ι _) (by { rw [←cancel_mono g], simp, }), inv := kernel.lift _ (kernel.ι _) (by simp), } instance has_kernel_iso_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] [has_kernel g] : has_kernel (f ≫ g) := { exists_limit := ⟨{ cone := kernel_fork.of_ι (kernel.ι g ≫ inv f) (by simp), is_limit := is_limit_aux _ (λ s, kernel.lift _ (s.ι ≫ f) (by tidy)) (by tidy) (λ s m w, by { simp_rw [←w], ext, simp, }), }⟩ } /-- When `f` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `g`. -/ @[simps] def kernel_is_iso_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] [has_kernel g] : kernel (f ≫ g) ≅ kernel g := { hom := kernel.lift _ (kernel.ι _ ≫ f) (by simp), inv := kernel.lift _ (kernel.ι _ ≫ inv f) (by simp), } end section has_zero_object variables [has_zero_object C] open_locale zero_object /-- The morphism from the zero object determines a cone on a kernel diagram -/ def kernel.zero_kernel_fork : kernel_fork f := { X := 0, π := { app := λ j, 0 }} /-- The map from the zero object is a kernel of a monomorphism -/ def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_kernel_fork f) := fork.is_limit.mk _ (λ s, 0) (λ s, by { erw zero_comp, convert (zero_of_comp_mono f _).symm, exact kernel_fork.condition _ }) (λ _ _ _, zero_of_to_zero _) /-- The kernel of a monomorphism is isomorphic to the zero object -/ def kernel.of_mono [has_kernel f] [mono f] : kernel f ≅ 0 := functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso (limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f) /-- The kernel morphism of a monomorphism is a zero morphism -/ lemma kernel.ι_of_mono [has_kernel f] [mono f] : kernel.ι f = 0 := zero_of_source_iso_zero _ (kernel.of_mono f) /-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `0 : 0 ⟶ X` is a kernel of `f`. -/ def zero_kernel_of_cancel_zero {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X) (hgf : g ≫ f = 0), g = 0) : is_limit (kernel_fork.of_ι (0 : 0 ⟶ X) (show 0 ≫ f = 0, by simp)) := fork.is_limit.mk _ (λ s, 0) (λ s, by rw [hf _ _ (kernel_fork.condition s), zero_comp]) (λ s m h, by ext) end has_zero_object section transport /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then any kernel of `f` is a kernel of `l`.-/ def is_kernel.of_comp_iso {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) {s : kernel_fork f} (hs : is_limit s) : is_limit (kernel_fork.of_ι (fork.ι s) $ show fork.ι s ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := fork.is_limit.mk _ (λ s, hs.lift $ kernel_fork.of_ι (fork.ι s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply fork.is_limit.hom_ext hs, simpa using h }) /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then the kernel of `f` is a kernel of `l`.-/ def kernel.of_comp_iso [has_kernel f] {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) : is_limit (kernel_fork.of_ι (kernel.ι f) $ show kernel.ι f ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := is_kernel.of_comp_iso f l i h $ limit.is_limit _ /-- If `s` is any limit kernel cone over `f` and if `i` is an isomorphism such that `i.hom ≫ s.ι = l`, then `l` is a kernel of `f`. -/ def is_kernel.iso_kernel {Z : C} (l : Z ⟶ X) {s : kernel_fork f} (hs : is_limit s) (i : Z ≅ s.X) (h : i.hom ≫ fork.ι s = l) : is_limit (kernel_fork.of_ι l $ show l ≫ f = 0, by simp [←h]) := is_limit.of_iso_limit hs $ cones.ext i.symm $ λ j, by { cases j, { exact (iso.eq_inv_comp i).2 h }, { simp } } /-- If `i` is an isomorphism such that `i.hom ≫ kernel.ι f = l`, then `l` is a kernel of `f`. -/ def kernel.iso_kernel [has_kernel f] {Z : C} (l : Z ⟶ X) (i : Z ≅ kernel f) (h : i.hom ≫ kernel.ι f = l) : is_limit (kernel_fork.of_ι l $ by simp [←h]) := is_kernel.iso_kernel f l (limit.is_limit _) i h end transport section variables (X Y) /-- The kernel morphism of a zero morphism is an isomorphism -/ lemma kernel.ι_of_zero : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ end section /-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/ abbreviation cokernel_cofork := cofork f 0 variables {f} @[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ s.π = 0 := by rw [cofork.condition, zero_comp] @[simp] lemma cokernel_cofork.π_eq_zero (s : cokernel_cofork f) : s.ι.app zero = 0 := by simp [cofork.app_zero_eq_comp_π_right] /-- A morphism `π` satisfying `f ≫ π = 0` determines a cokernel cofork on `f`. -/ abbreviation cokernel_cofork.of_π {Z : C} (π : Y ⟶ Z) (w : f ≫ π = 0) : cokernel_cofork f := cofork.of_π π $ by rw [w, zero_comp] @[simp] lemma cokernel_cofork.π_of_π {X Y P : C} (f : X ⟶ Y) (π : Y ⟶ P) (w : f ≫ π = 0) : cofork.π (cokernel_cofork.of_π π w) = π := rfl /-- Every cokernel cofork `s` is isomorphic (actually, equal) to `cofork.of_π (cofork.π s) _`. -/ def iso_of_π (s : cofork f 0) : s ≅ cofork.of_π (cofork.π s) (cofork.condition s) := cocones.ext (iso.refl _) $ λ j, by cases j; tidy /-- If `π = π'`, then `cokernel_cofork.of_π π _` and `cokernel_cofork.of_π π' _` are isomorphic. -/ def of_π_congr {P : C} {π π' : Y ⟶ P} {w : f ≫ π = 0} (h : π = π') : cokernel_cofork.of_π π w ≅ cokernel_cofork.of_π π' (by rw [←h, w]) := cocones.ext (iso.refl _) $ λ j, by cases j; tidy /-- If `s` is a colimit cokernel cofork, then every `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cokernel_cofork.is_colimit.desc' {s : cokernel_cofork f} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cokernel_cofork.of_π _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a cokernel cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : cokernel_cofork f) (desc : Π (s : cokernel_cofork f), t.X ⟶ s.X) (fac : ∀ (s : cokernel_cofork f), t.π ≫ desc s = s.π) (uniq : ∀ (s : cokernel_cofork f) (m : t.X ⟶ s.X) (w : t.π ≫ m = s.π), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, by { cases j, { simp, }, { exact fac s, }, }, uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.one), } /-- This is a more convenient formulation to show that a `cokernel_cofork` constructed using `cokernel_cofork.of_π` is a limit cone. -/ def cokernel_cofork.is_colimit.of_π {Z : C} (g : Y ⟶ Z) (eq : f ≫ g = 0) (desc : Π {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), Z ⟶ Z') (fac : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), g ≫ desc g' eq' = g') (uniq : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0) (m : Z ⟶ Z') (w : g ≫ m = g'), m = desc g' eq') : is_colimit (cokernel_cofork.of_π g eq) := is_colimit_aux _ (λ s, desc s.π s.condition) (λ s, fac s.π s.condition) (λ s, uniq s.π s.condition) /-- Every cokernel of `f` induces a cokernel of `g ≫ f` if `g` is epi. -/ def is_cokernel_epi_comp {c : cokernel_cofork f} (i : is_colimit c) {W} (g : W ⟶ X) [hg : epi g] {h : W ⟶ Y} (hh : h = g ≫ f) : is_colimit (cokernel_cofork.of_π c.π (by rw [hh]; simp) : cokernel_cofork h) := cofork.is_colimit.mk' _ $ λ s, let s' : cokernel_cofork f := cofork.of_π s.π (by { apply hg.left_cancellation, rw [←category.assoc, ←hh, s.condition], simp }) in let l := cokernel_cofork.is_colimit.desc' i s'.π s'.condition in ⟨l.1, l.2, λ m hm, by apply cofork.is_colimit.hom_ext i; rw cofork.π_of_π at hm; rw hm; exact l.2.symm⟩ @[simp] lemma is_cokernel_epi_comp_desc {c : cokernel_cofork f} (i : is_colimit c) {W} (g : W ⟶ X) [hg : epi g] {h : W ⟶ Y} (hh : h = g ≫ f) (s : cokernel_cofork h) : (is_cokernel_epi_comp i g hh).desc s = i.desc (cofork.of_π s.π (by { rw [←cancel_epi g, ←category.assoc, ←hh], simp })) := rfl /-- Every cokernel of `g ≫ f` is also a cokernel of `f`, as long as `f ≫ c.π` vanishes. -/ def is_cokernel_of_comp {W : C} (g : W ⟶ X) (h : W ⟶ Y) {c : cokernel_cofork h} (i : is_colimit c) (hf : f ≫ c.π = 0) (hfg : g ≫ f = h) : is_colimit (cokernel_cofork.of_π c.π hf) := cofork.is_colimit.mk _ (λ s, i.desc (cokernel_cofork.of_π s.π (by simp [← hfg]))) (λ s, by simp only [cokernel_cofork.π_of_π, cofork.is_colimit.π_desc]) (λ s m h, by { apply cofork.is_colimit.hom_ext i, simpa using h }) end section variables [has_cokernel f] /-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/ abbreviation cokernel : C := coequalizer f 0 /-- The map from the target of `f` to `cokernel f`. -/ abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0 @[simp] lemma coequalizer_as_cokernel : coequalizer.π f 0 = cokernel.π f := rfl @[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 := cokernel_cofork.condition _ /-- The cokernel built from `cokernel.π f` is colimiting. -/ def cokernel_is_cokernel : is_colimit (cofork.of_π (cokernel.π f) ((cokernel.condition f).trans (zero_comp.symm))) := is_colimit.of_iso_colimit (colimit.is_colimit _) (cofork.ext (iso.refl _) (by tidy)) /-- Given any morphism `k : Y ⟶ W` such that `f ≫ k = 0`, `k` factors through `cokernel.π f` via `cokernel.desc : cokernel f ⟶ W`. -/ abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W := colimit.desc (parallel_pair f 0) (cokernel_cofork.of_π k h) @[simp, reassoc] lemma cokernel.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel.π f ≫ cokernel.desc f k h = k := colimit.ι_desc _ _ @[simp] lemma cokernel.desc_zero {W : C} {h} : cokernel.desc f (0 : Y ⟶ W) h = 0 := by { ext, simp, } instance cokernel.desc_epi {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) [epi k] : epi (cokernel.desc f k h) := ⟨λ Z g g' w, begin replace w := cokernel.π f ≫= w, simp only [cokernel.π_desc_assoc] at w, exact (cancel_epi k).1 w, end⟩ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : cokernel f ⟶ W` such that `cokernel.π f ≫ l = k`. -/ def cokernel.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : cokernel f ⟶ W // cokernel.π f ≫ l = k} := ⟨cokernel.desc f k h, cokernel.π_desc _ _ _⟩ /-- A commuting square induces a morphism of cokernels. -/ abbreviation cokernel.map {X' Y' : C} (f' : X' ⟶ Y') [has_cokernel f'] (p : X ⟶ X') (q : Y ⟶ Y') (w : f ≫ q = p ≫ f') : cokernel f ⟶ cokernel f' := cokernel.desc f (q ≫ cokernel.π f') (by simp [reassoc_of w]) /-- Given a commutative diagram X --f--> Y --g--> Z | | | | | | v v v X' -f'-> Y' -g'-> Z' with horizontal arrows composing to zero, then we obtain a commutative square cokernel f ---> Z | | | cokernel.map | | | v v cokernel f' --> Z' -/ lemma cokernel.map_desc {X Y Z X' Y' Z' : C} (f : X ⟶ Y) [has_cokernel f] (g : Y ⟶ Z) (w : f ≫ g = 0) (f' : X' ⟶ Y') [has_cokernel f'] (g' : Y' ⟶ Z') (w' : f' ≫ g' = 0) (p : X ⟶ X') (q : Y ⟶ Y') (r : Z ⟶ Z') (h₁ : f ≫ q = p ≫ f') (h₂ : g ≫ r = q ≫ g') : cokernel.map f f' p q h₁ ≫ cokernel.desc f' g' w' = cokernel.desc f g w ≫ r := by { ext, simp [h₂], } /-- A commuting square of isomorphisms induces an isomorphism of cokernels. -/ @[simps] def cokernel.map_iso {X' Y' : C} (f' : X' ⟶ Y') [has_cokernel f'] (p : X ≅ X') (q : Y ≅ Y') (w : f ≫ q.hom = p.hom ≫ f') : cokernel f ≅ cokernel f' := { hom := cokernel.map f f' p.hom q.hom w, inv := cokernel.map f' f p.inv q.inv (by { refine (cancel_mono q.hom).1 _, simp [w], }), } /-- The cokernel of the zero morphism is an isomorphism -/ instance cokernel.π_zero_is_iso : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ lemma eq_zero_of_mono_cokernel [mono (cokernel.π f)] : f = 0 := (cancel_mono (cokernel.π f)).1 (by simp) /-- The cokernel of a zero morphism is isomorphic to the target. -/ def cokernel_zero_iso_target : cokernel (0 : X ⟶ Y) ≅ Y := coequalizer.iso_target_of_self 0 @[simp] lemma cokernel_zero_iso_target_hom : cokernel_zero_iso_target.hom = cokernel.desc (0 : X ⟶ Y) (𝟙 Y) (by simp) := by { ext, simp [cokernel_zero_iso_target], } @[simp] lemma cokernel_zero_iso_target_inv : cokernel_zero_iso_target.inv = cokernel.π (0 : X ⟶ Y) := rfl /-- If two morphisms are known to be equal, then their cokernels are isomorphic. -/ def cokernel_iso_of_eq {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) : cokernel f ≅ cokernel g := has_colimit.iso_of_nat_iso (by simp[h]) @[simp] lemma cokernel_iso_of_eq_refl {h : f = f} : cokernel_iso_of_eq h = iso.refl (cokernel f) := by { ext, simp [cokernel_iso_of_eq], } @[simp, reassoc] lemma π_comp_cokernel_iso_of_eq_hom {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) : cokernel.π _ ≫ (cokernel_iso_of_eq h).hom = cokernel.π _ := by { unfreezingI { induction h, simp } } @[simp, reassoc] lemma π_comp_cokernel_iso_of_eq_inv {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) : cokernel.π _ ≫ (cokernel_iso_of_eq h).inv = cokernel.π _ := by { unfreezingI { induction h, simp } } @[simp, reassoc] lemma cokernel_iso_of_eq_hom_comp_desc {Z} {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) (e : Y ⟶ Z) (he) : (cokernel_iso_of_eq h).hom ≫ cokernel.desc _ e he = cokernel.desc _ e (by simp [h, he]) := by { unfreezingI { induction h, simp } } @[simp, reassoc] lemma cokernel_iso_of_eq_inv_comp_desc {Z} {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) (e : Y ⟶ Z) (he) : (cokernel_iso_of_eq h).inv ≫ cokernel.desc _ e he = cokernel.desc _ e (by simp [← h, he]) := by { unfreezingI { induction h, simp } } @[simp] lemma cokernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_cokernel f] [has_cokernel g] [has_cokernel h] (w₁ : f = g) (w₂ : g = h) : cokernel_iso_of_eq w₁ ≪≫ cokernel_iso_of_eq w₂ = cokernel_iso_of_eq (w₁.trans w₂) := by { unfreezingI { induction w₁, induction w₂, }, ext, simp [cokernel_iso_of_eq], } variables {f} lemma cokernel_not_mono_of_nonzero (w : f ≠ 0) : ¬mono (cokernel.π f) := λ I, by exactI w (eq_zero_of_mono_cokernel f) lemma cokernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (cokernel.π f)) → false := λ I, cokernel_not_mono_of_nonzero w $ by { resetI, apply_instance } -- TODO the remainder of this section has obvious generalizations to `has_coequalizer f g`. instance has_cokernel_comp_iso {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel f] [is_iso g] : has_cokernel (f ≫ g) := { exists_colimit := ⟨{ cocone := cokernel_cofork.of_π (inv g ≫ cokernel.π f) (by simp), is_colimit := is_colimit_aux _ (λ s, cokernel.desc _ (g ≫ s.π) (by { rw [←category.assoc, cokernel_cofork.condition], })) (by tidy) (λ s m w, by { simp_rw [←w], ext, simp, }), }⟩ } /-- When `g` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `f`. -/ @[simps] def cokernel_comp_is_iso {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel f] [is_iso g] : cokernel (f ≫ g) ≅ cokernel f := { hom := cokernel.desc _ (inv g ≫ cokernel.π f) (by simp), inv := cokernel.desc _ (g ≫ cokernel.π (f ≫ g)) (by rw [←category.assoc, cokernel.condition]), } instance has_cokernel_epi_comp {X Y : C} (f : X ⟶ Y) [has_cokernel f] {W} (g : W ⟶ X) [epi g] : has_cokernel (g ≫ f) := ⟨⟨{ cocone := _, is_colimit := is_cokernel_epi_comp (colimit.is_colimit _) g rfl }⟩⟩ /-- When `f` is an epimorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `g`. -/ @[simps] def cokernel_epi_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi f] [has_cokernel g] : cokernel (f ≫ g) ≅ cokernel g := { hom := cokernel.desc _ (cokernel.π g) (by simp), inv := cokernel.desc _ (cokernel.π (f ≫ g)) (by { rw [←cancel_epi f, ←category.assoc], simp, }), } end section has_zero_object variables [has_zero_object C] open_locale zero_object /-- The morphism to the zero object determines a cocone on a cokernel diagram -/ def cokernel.zero_cokernel_cofork : cokernel_cofork f := { X := 0, ι := { app := λ j, 0 } } /-- The morphism to the zero object is a cokernel of an epimorphism -/ def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cokernel_cofork f) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by { erw zero_comp, convert (zero_of_epi_comp f _).symm, exact cokernel_cofork.condition _ }) (λ _ _ _, zero_of_from_zero _) /-- The cokernel of an epimorphism is isomorphic to the zero object -/ def cokernel.of_epi [has_cokernel f] [epi f] : cokernel f ≅ 0 := functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso (colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f) /-- The cokernel morphism of an epimorphism is a zero morphism -/ lemma cokernel.π_of_epi [has_cokernel f] [epi f] : cokernel.π f = 0 := zero_of_target_iso_zero _ (cokernel.of_epi f) end has_zero_object section mono_factorisation variables {f} @[simp] lemma mono_factorisation.kernel_ι_comp [has_kernel f] (F : mono_factorisation f) : kernel.ι f ≫ F.e = 0 := by rw [← cancel_mono F.m, zero_comp, category.assoc, F.fac, kernel.condition] end mono_factorisation section has_image /-- The cokernel of the image inclusion of a morphism `f` is isomorphic to the cokernel of `f`. (This result requires that the factorisation through the image is an epimorphism. This holds in any category with equalizers.) -/ @[simps] def cokernel_image_ι {X Y : C} (f : X ⟶ Y) [has_image f] [has_cokernel (image.ι f)] [has_cokernel f] [epi (factor_thru_image f)] : cokernel (image.ι f) ≅ cokernel f := { hom := cokernel.desc _ (cokernel.π f) begin have w := cokernel.condition f, conv at w { to_lhs, congr, rw ←image.fac f, }, rw [←has_zero_morphisms.comp_zero (limits.factor_thru_image f), category.assoc, cancel_epi] at w, exact w, end, inv := cokernel.desc _ (cokernel.π _) begin conv { to_lhs, congr, rw ←image.fac f, }, rw [category.assoc, cokernel.condition, has_zero_morphisms.comp_zero], end, } end has_image section variables (X Y) /-- The cokernel of a zero morphism is an isomorphism -/ lemma cokernel.π_of_zero : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ end section has_zero_object variables [has_zero_object C] open_locale zero_object /-- The kernel of the cokernel of an epimorphism is an isomorphism -/ instance kernel.of_cokernel_of_epi [has_cokernel f] [has_kernel (cokernel.π f)] [epi f] : is_iso (kernel.ι (cokernel.π f)) := equalizer.ι_of_eq $ cokernel.π_of_epi f /-- The cokernel of the kernel of a monomorphism is an isomorphism -/ instance cokernel.of_kernel_of_mono [has_kernel f] [has_cokernel (kernel.ι f)] [mono f] : is_iso (cokernel.π (kernel.ι f)) := coequalizer.π_of_eq $ kernel.ι_of_mono f /-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `0 : Y ⟶ 0` is a cokernel of `f`. -/ def zero_cokernel_of_zero_cancel {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z) (hgf : f ≫ g = 0), g = 0) : is_colimit (cokernel_cofork.of_π (0 : Y ⟶ 0) (show f ≫ 0 = 0, by simp)) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by rw [hf _ _ (cokernel_cofork.condition s), comp_zero]) (λ s m h, by ext) end has_zero_object section transport /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then any cokernel of `f` is a cokernel of `l`. -/ def is_cokernel.of_iso_comp {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) {s : cokernel_cofork f} (hs : is_colimit s) : is_colimit (cokernel_cofork.of_π (cofork.π s) $ show l ≫ cofork.π s = 0, by simp [i.eq_inv_comp.2 h]) := cofork.is_colimit.mk _ (λ s, hs.desc $ cokernel_cofork.of_π (cofork.π s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply cofork.is_colimit.hom_ext hs, simpa using h }) /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then the cokernel of `f` is a cokernel of `l`. -/ def cokernel.of_iso_comp [has_cokernel f] {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) : is_colimit (cokernel_cofork.of_π (cokernel.π f) $ show l ≫ cokernel.π f = 0, by simp [i.eq_inv_comp.2 h]) := is_cokernel.of_iso_comp f l i h $ colimit.is_colimit _ /-- If `s` is any colimit cokernel cocone over `f` and `i` is an isomorphism such that `s.π ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def is_cokernel.cokernel_iso {Z : C} (l : Y ⟶ Z) {s : cokernel_cofork f} (hs : is_colimit s) (i : s.X ≅ Z) (h : cofork.π s ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ show f ≫ l = 0, by simp [←h]) := is_colimit.of_iso_colimit hs $ cocones.ext i $ λ j, by { cases j, { simp }, { exact h } } /-- If `i` is an isomorphism such that `cokernel.π f ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def cokernel.cokernel_iso [has_cokernel f] {Z : C} (l : Y ⟶ Z) (i : cokernel f ≅ Z) (h : cokernel.π f ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ by simp [←h]) := is_cokernel.cokernel_iso f l (colimit.is_colimit _) i h end transport section comparison variables {D : Type u₂} [category.{v₂} D] [has_zero_morphisms D] variables (G : C ⥤ D) [functor.preserves_zero_morphisms G] /-- The comparison morphism for the kernel of `f`. This is an isomorphism iff `G` preserves the kernel of `f`; see `category_theory/limits/preserves/shapes/kernels.lean` -/ def kernel_comparison [has_kernel f] [has_kernel (G.map f)] : G.obj (kernel f) ⟶ kernel (G.map f) := kernel.lift _ (G.map (kernel.ι f)) (by simp only [←G.map_comp, kernel.condition, functor.map_zero]) @[simp, reassoc] lemma kernel_comparison_comp_ι [has_kernel f] [has_kernel (G.map f)] : kernel_comparison f G ≫ kernel.ι (G.map f) = G.map (kernel.ι f) := kernel.lift_ι _ _ _ @[simp, reassoc] lemma map_lift_kernel_comparison [has_kernel f] [has_kernel (G.map f)] {Z : C} {h : Z ⟶ X} (w : h ≫ f = 0) : G.map (kernel.lift _ h w) ≫ kernel_comparison f G = kernel.lift _ (G.map h) (by simp only [←G.map_comp, w, functor.map_zero]) := by { ext, simp [← G.map_comp] } /-- The comparison morphism for the cokernel of `f`. -/ def cokernel_comparison [has_cokernel f] [has_cokernel (G.map f)] : cokernel (G.map f) ⟶ G.obj (cokernel f) := cokernel.desc _ (G.map (coequalizer.π _ _)) (by simp only [←G.map_comp, cokernel.condition, functor.map_zero]) @[simp, reassoc] lemma π_comp_cokernel_comparison [has_cokernel f] [has_cokernel (G.map f)] : cokernel.π (G.map f) ≫ cokernel_comparison f G = G.map (cokernel.π _) := cokernel.π_desc _ _ _ @[simp, reassoc] lemma cokernel_comparison_map_desc [has_cokernel f] [has_cokernel (G.map f)] {Z : C} {h : Y ⟶ Z} (w : f ≫ h = 0) : cokernel_comparison f G ≫ G.map (cokernel.desc _ h w) = cokernel.desc _ (G.map h) (by simp only [←G.map_comp, w, functor.map_zero]) := by { ext, simp [← G.map_comp] } end comparison end category_theory.limits namespace category_theory.limits variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] /-- `has_kernels` represents the existence of kernels for every morphism. -/ class has_kernels : Prop := (has_limit : Π {X Y : C} (f : X ⟶ Y), has_kernel f . tactic.apply_instance) /-- `has_cokernels` represents the existence of cokernels for every morphism. -/ class has_cokernels : Prop := (has_colimit : Π {X Y : C} (f : X ⟶ Y), has_cokernel f . tactic.apply_instance) attribute [instance, priority 100] has_kernels.has_limit has_cokernels.has_colimit @[priority 100] instance has_kernels_of_has_equalizers [has_equalizers C] : has_kernels C := {} @[priority 100] instance has_cokernels_of_has_coequalizers [has_coequalizers C] : has_cokernels C := {} end category_theory.limits
f23e152289793e914ec2f93a5ae8f8486ce4b9be
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/analysis/normed_space/dual.lean
676ad45e51ac31e32df65db96b4105f3f2725959
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,050
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.normed_space.hahn_banach /-! # The topological dual of a normed space In this file we define the topological dual of a normed space, and the bounded linear map from a normed space into its double dual. We also prove that, for base field `𝕜` with `[is_R_or_C 𝕜]`, this map is an isometry. Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory for `semi_normed_space` and we specialize to `normed_space` when needed. ## TODO Express the construction `inclusion_in_double_dual_isometry` as a `linear_isometry` (not difficult, just overlooked). ## Tags dual -/ noncomputable theory open_locale classical universes u v namespace normed_space section general variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] variables (E : Type*) [semi_normed_group E] [semi_normed_space 𝕜 E] variables (F : Type*) [normed_group F] [normed_space 𝕜 F] /-- The topological dual of a seminormed space `E`. -/ @[derive [inhabited, has_coe_to_fun, semi_normed_group, semi_normed_space 𝕜]] def dual := E →L[𝕜] 𝕜 instance : normed_group (dual 𝕜 F) := continuous_linear_map.to_normed_group instance : normed_space 𝕜 (dual 𝕜 F) := continuous_linear_map.to_normed_space /-- The inclusion of a normed space in its double (topological) dual, considered as a bounded linear map. -/ def inclusion_in_double_dual : E →L[𝕜] (dual 𝕜 (dual 𝕜 E)) := continuous_linear_map.apply 𝕜 𝕜 @[simp] lemma dual_def (x : E) (f : dual 𝕜 E) : inclusion_in_double_dual 𝕜 E x f = f x := rfl lemma inclusion_in_double_dual_norm_eq : ∥inclusion_in_double_dual 𝕜 E∥ = ∥(continuous_linear_map.id 𝕜 (dual 𝕜 E))∥ := continuous_linear_map.op_norm_flip _ lemma inclusion_in_double_dual_norm_le : ∥inclusion_in_double_dual 𝕜 E∥ ≤ 1 := by { rw inclusion_in_double_dual_norm_eq, exact continuous_linear_map.norm_id_le } lemma double_dual_bound (x : E) : ∥(inclusion_in_double_dual 𝕜 E) x∥ ≤ ∥x∥ := by simpa using continuous_linear_map.le_of_op_norm_le _ (inclusion_in_double_dual_norm_le 𝕜 E) x end general section bidual_isometry variables (𝕜 : Type v) [is_R_or_C 𝕜] {E : Type u} [normed_group E] [normed_space 𝕜 E] /-- If one controls the norm of every `f x`, then one controls the norm of `x`. Compare `continuous_linear_map.op_norm_le_bound`. -/ lemma norm_le_dual_bound (x : E) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ (f : dual 𝕜 E), ∥f x∥ ≤ M * ∥f∥) : ∥x∥ ≤ M := begin classical, by_cases h : x = 0, { simp only [h, hMp, norm_zero] }, { obtain ⟨f, hf⟩ : ∃ g : E →L[𝕜] 𝕜, _ := exists_dual_vector 𝕜 x h, calc ∥x∥ = ∥norm' 𝕜 x∥ : (norm_norm' _ _ _).symm ... = ∥f x∥ : by rw hf.2 ... ≤ M * ∥f∥ : hM f ... = M : by rw [hf.1, mul_one] } end lemma eq_zero_of_forall_dual_eq_zero {x : E} (h : ∀ f : dual 𝕜 E, f x = (0 : 𝕜)) : x = 0 := norm_eq_zero.mp (le_antisymm (norm_le_dual_bound 𝕜 x le_rfl (λ f, by simp [h f])) (norm_nonneg _)) lemma eq_zero_iff_forall_dual_eq_zero (x : E) : x = 0 ↔ ∀ g : dual 𝕜 E, g x = 0 := ⟨λ hx, by simp [hx], λ h, eq_zero_of_forall_dual_eq_zero 𝕜 h⟩ lemma eq_iff_forall_dual_eq {x y : E} : x = y ↔ ∀ g : dual 𝕜 E, g x = g y := begin rw [← sub_eq_zero, eq_zero_iff_forall_dual_eq_zero 𝕜 (x - y)], simp [sub_eq_zero], end /-- The inclusion of a normed space in its double dual is an isometry onto its image.-/ lemma inclusion_in_double_dual_isometry (x : E) : ∥inclusion_in_double_dual 𝕜 E x∥ = ∥x∥ := begin apply le_antisymm, { exact double_dual_bound 𝕜 E x }, { rw continuous_linear_map.norm_def, apply le_cInf continuous_linear_map.bounds_nonempty, rintros c ⟨hc1, hc2⟩, exact norm_le_dual_bound 𝕜 x hc1 hc2 }, end end bidual_isometry end normed_space
d070e4ebee635aaeaee3800534b71e59e9e144db
fe6a6bdd171ff04b1f2728c050ebe0262fb5f788
/compilador.lean
eb4625b6ddcc4cb67806dd22ec33e80f34aca001
[]
no_license
FeIipeVieira/LogicasFormaisSistemasNormativos
4a4cc9fe2fa70e7acdc1ff34b81783b6a26a2b6f
c63dd3b15a072779200a12eb6b88a60acf065d70
refs/heads/master
1,583,547,325,700
1,536,799,298,000
1,536,799,298,000
127,204,138
1
0
null
null
null
null
UTF-8
Lean
false
false
1,230
lean
open nat namespace hidden inductive Expr | ENat : ℕ → Expr | ESum : Expr → Expr → Expr | EEq : Expr → Expr → Expr open Expr #check EEq (ENat 1) (ENat 1) inductive RType | RNat : RType | RBool : RType open RType inductive Typ : Expr → RType → Prop | tnat : ∀ {n}, Typ (ENat n) RNat | tplus : ∀ {e1 e2}, Typ e1 RNat → Typ e2 RNat → Typ (ESum e1 e2) RNat | teq : ∀e1 {e2}, Typ e1 RNat → Typ e2 RNat → Typ (EEq e1 e2) RBool open Typ #check tnat --#check tplus (ENat 3) (ENat 3) (tnat 3) (tnat 3) --#check teq (ENat 3) (ENat 2) (tnat 3) (tnat 2) --#check tplus (ENat 3) (tnat 3) (tplus (ENat 3) (ENat 3) (tnat 3) (tnat 3)) #check @tplus (ENat 3) (ESum (ENat 3) (ENat 3)) (@tnat 3) (@tplus (ENat 3) (ENat 3) (@tnat 3) (@tnat 3)) --#check teq (ENat 3) (ENat 3) (tnat) (tnat) def Τ : RType → Type | RNat := ℕ | RBool := bool variable n : Τ RNat def n /-def eval {t} : Π (e : Expr), Typ e t → Τ t |(ENat n) (@tnat n) := n --|∀ n, (ENat n) (@tnat n) := n -/ def eval : ∀ (e : Expr) {t : RType}, Typ e t → Τ t | (ENat n) _ tnat := n | (ESum e1 e2) RNat (tplus p1 p2) := (eval e1 RNat p1) + (eval e2 RNat p2) end hidden
6d41f4f1eac25d3a0fa3ddd19b45e820557e315c
4fa161becb8ce7378a709f5992a594764699e268
/src/data/fintype/card.lean
318726f90aea77844eaf123788d59c0c9fa2c738
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
14,887
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.fintype.basic import data.nat.choose import tactic.ring /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [fintype ι] [decidable_eq ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_unique [unique β] (f : β → M) : (∏ x, f x) = f (default β) := by simp only [finset.prod_singleton, univ_unique] end end fintype open finset theorem fin.prod_univ_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∏ i, f i = f 0 * ∏ i : fin n, f i.succ := begin rw [fin.univ_succ, prod_insert, prod_image], { intros x _ y _ hxy, exact fin.succ.inj hxy }, { simpa using fin.succ_ne_zero } end @[simp, to_additive] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl theorem fin.sum_univ_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∑ i, f i = f 0 + ∑ i : fin n, f i.succ := by apply @fin.prod_univ_succ (multiplicative β) attribute [to_additive] fin.prod_univ_succ theorem fin.prod_univ_cast_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (fin.last n) := begin rw [fin.univ_cast_succ, prod_insert, prod_image, mul_comm], { intros x _ y _ hxy, exact fin.cast_succ_inj.mp hxy }, { simpa using fin.cast_succ_ne_last } end theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∑ i, f i = ∑ i : fin n, f i.cast_succ + f (fin.last n) := by apply @fin.prod_univ_cast_succ (multiplicative β) attribute [to_additive] fin.prod_univ_cast_succ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = ∑ a, fintype.card (β a) := card_sigma _ _ -- FIXME ouch, this should be in the main file. @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by simp [sum.fintype, fintype.of_equiv_card] @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = ∏ a, card (t a) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : ∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) @[to_additive] lemma finset.range_prod_eq_univ_prod [comm_monoid β] (n : ℕ) (f : ℕ → β) : ∏ k in range n, f k = ∏ k : fin n, f k := begin symmetry, refine prod_bij (λ k hk, k) _ _ _ _, { rintro ⟨k, hk⟩ _, simp * }, { rintro ⟨k, hk⟩ _, simp * }, { intros, rwa fin.eq_iff_veq }, { intros k hk, rw mem_range at hk, exact ⟨⟨k, hk⟩, mem_univ _, rfl⟩ } end /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : ∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : ∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/ @[to_additive] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : ∏ i : fin n, f i.val = ∏ i in finset.range n, f i := begin apply finset.prod_bij (λ (a : fin n) ha, a.val), { assume a ha, simp [a.2] }, { assume a ha, refl }, { assume a b ha hb H, exact (fin.ext_iff _ _).2 H }, { assume b hb, exact ⟨⟨b, list.mem_range.mp hb⟩, finset.mem_univ _, rfl⟩, } end @[to_additive] lemma finset.prod_equiv [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : ∏ i, f (e i) = ∏ i, f i := begin apply prod_bij (λ i hi, e i) (λ i hi, mem_univ _) _ (λ a b _ _ h, e.injective h), { assume b hb, rcases e.surjective b with ⟨a, ha⟩, exact ⟨a, mem_univ _, ha.symm⟩, }, { simp } end @[to_additive] lemma finset.prod_subtype {M : Type*} [comm_monoid M] {p : α → Prop} {F : fintype (subtype p)} {s : finset α} (h : ∀ x, x ∈ s ↔ p x) (f : α → M) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, begin rw ← prod_attach, resetI, subst p, congr, simp [finset.ext_iff] end @[to_additive] lemma finset.prod_fiberwise [fintype β] [decidable_eq β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := begin classical, have key : ∏ (b : β), ∏ a in s.filter (λ a, f a = b), g a = ∏ (a : α) in univ.bind (λ (b : β), s.filter (λ a, f a = b)), g a := (@prod_bind _ _ β g _ _ finset.univ (λ b : β, s.filter (λ a, f a = b)) _).symm, { simp only [key, filter_congr_decidable], apply finset.prod_congr, { ext, simp only [mem_bind, mem_filter, mem_univ, exists_prop_of_true, exists_eq_right'] }, { intros, refl } }, { intros x hx y hy H z hz, apply H, simp only [mem_filter, inf_eq_inter, mem_inter] at hz, rw [← hz.1.2, ← hz.2.2] } end @[to_additive] lemma fintype.prod_fiberwise [fintype α] [fintype β] [decidable_eq β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← finset.prod_equiv (equiv.sigma_preimage_equiv f) _, ← univ_sigma_univ, prod_sigma], refl end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := begin classical, let s : finset (α₁ ⊕ α₂) := univ.image sum.inr, rw [← prod_sdiff (subset_univ s), ← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inl, ← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inr], { congr, rw finset.ext_iff, rintro (a|a); { simp only [mem_image, exists_eq, mem_sdiff, mem_univ, exists_false, exists_prop_of_true, not_false_iff, and_self, not_true, and_false], } }, all_goals { intros, solve_by_elim [sum.inl.inj, sum.inr.inj], } end end namespace list lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i), { assume j, have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end -- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof. Copy-paste the -- proof instead... lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).sum = ∑ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw sum_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ singleton (⟨i, h⟩ : fin n), by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.sum_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i), { assume j, have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end attribute [to_additive] prod_take_of_fn @[to_additive] lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} : (of_fn f).prod = ∏ i, f i := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), j.val < n := λ j, j.2, simp [this] } end lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.2 | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∑ i : fin 1, (-1 : ℤ) ^ (i : ℕ) •ℤ [g].nth_le i i.2, rw [fin.sum_univ_succ], simp, end | (g :: h :: L) := calc g - h + L.alternating_sum = g - h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) •ℤ list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, sub_eq_add_neg, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
8dab9d7a92ee65b01faad3da89994d554d1676b1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/linear_combination.lean
306bfd6ea743995ab06927fbda113d01e4c0e2e3
[ "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,555
lean
/- Copyright (c) 2022 Abby J. Goldberg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abby J. Goldberg -/ import tactic.ring /-! # linear_combination Tactic In this file, the `linear_combination` tactic is created. This tactic, which works over `ring`s, attempts to simplify the target by creating a linear combination of a list of equalities and subtracting it from the target. This file also includes a definition for `linear_combination_config`. A `linear_combination_config` object can be passed into the tactic, allowing the user to specify a normalization tactic. ## Implementation Notes This tactic works by creating a weighted sum of the given equations with the given coefficients. Then, it subtracts the right side of the weighted sum from the left side so that the right side equals 0, and it does the same with the target. Afterwards, it sets the goal to be the equality between the lefthand side of the new goal and the lefthand side of the new weighted sum. Lastly, calls a normalization tactic on this target. ## References * <https://leanprover.zulipchat.com/#narrow/stream/239415-metaprogramming-.2F.20tactics/topic/Linear.20algebra.20tactic/near/213928196> -/ namespace linear_combo open tactic /-! ### Lemmas -/ lemma left_mul_both_sides {α} [h : has_mul α] {x y : α} (z : α) (h1 : x = y) : z * x = z * y := congr_arg (has_mul.mul z) h1 lemma sum_two_equations {α} [h : has_add α] {x1 y1 x2 y2 : α} (h1 : x1 = y1) (h2: x2 = y2) : x1 + x2 = y1 + y2 := congr (congr_arg has_add.add h1) h2 lemma left_minus_right {α} [h : add_group α] {x y : α} (h1 : x = y) : x - y = 0 := sub_eq_zero.mpr h1 lemma all_on_left_equiv {α} [h : add_group α] (x y : α) : (x = y) = (x - y = 0) := propext (⟨left_minus_right, sub_eq_zero.mp⟩) lemma replace_eq_expr {α} [h : has_zero α] {x y : α} (h1 : x = 0) (h2 : y = x) : y = 0 := by rwa h2 lemma eq_zero_of_sub_eq_zero {α} [add_group α] {x y : α} (h : y = 0) (h2 : x - y = 0) : x = 0 := by rwa [h, sub_zero] at h2 /-! ### Configuration -/ /-- A configuration object for `linear_combination`. `normalize` describes whether or not the normalization step should be used. `normalization_tactic` describes the tactic used for normalization when checking if the weighted sum is equivalent to the goal (when `normalize` is `tt`). -/ meta structure linear_combination_config : Type := (normalize : bool := tt) (normalization_tactic : tactic unit := `[ring_nf SOP]) /-! ### Part 1: Multiplying Equations by Constants and Adding Them Together -/ /-- Given that `lhs = rhs`, this tactic returns an `expr` proving that `coeff * lhs = coeff * rhs`. * Input: * `h_equality` : an `expr`, whose type should be an equality between terms of type `α`, where there is an instance of `has_mul α` * `coeff` : a `pexpr`, which should be a value of type `α` * Output: an `expr`, which proves that the result of multiplying both sides of `h_equality` by the `coeff` holds -/ meta def mul_equality_expr (h_equality : expr) (coeff : pexpr) : tactic expr := do `(%%lhs = %%rhs) ← infer_type h_equality, -- Mark the coefficient as having the same type as the sides of `h_equality` - -- this is necessary in order to use the left_mul_both_sides lemma left_type ← infer_type lhs, coeff_expr ← to_expr ``(%%coeff : %%left_type), mk_app ``left_mul_both_sides [coeff_expr, h_equality] /-- Given two hypotheses that `a = b` and `c = d`, this tactic returns an `expr` proving that `a + c = b + d`. * Input: * `h_equality1` : an `expr`, whose type should be an equality between terms of type `α`, where there is an instance of `has_add α` * `h_equality2` : an `expr`, whose type should be an equality between terms of type `α` * Output: an `expr`, which proves that the result of adding the two equalities holds -/ meta def sum_equalities (h_equality1 h_equality2 : expr) : tactic expr := mk_app ``sum_two_equations [h_equality1, h_equality2] /-- Given that `a = b` and `c = d`, along with a coefficient, this tactic returns an `expr` proving that `a + coeff * c = b + coeff * d`. * Input: * `h_equality1` : an `expr`, whose type should be an equality between terms of type `α`, where there are instances of `has_add α` and `has_mul α` * `h_equality2` : an `expr`, whose type should be an equality between terms of type `α` * `coeff_for_eq2` : a `pexpr`, which should be a value of type `α` * Output: an `expr`, which proves that the result of adding the first equality to the result of multiplying `coeff_for_eq2` by the second equality holds -/ meta def sum_two_hyps_one_mul_helper (h_equality1 h_equality2 : expr) (coeff_for_eq2 : pexpr) : tactic expr := mul_equality_expr h_equality2 coeff_for_eq2 >>= sum_equalities h_equality1 /-- Given that `l_sum1 = r_sum1`, `l_h1 = r_h1`, ..., `l_hn = r_hn`, and given coefficients `c_1`, ..., `c_n`, this tactic returns an `expr` proving that `l_sum1 + (c_1 * l_h1) + ... + (c_n * l_hn)` `= r_sum1 + (c_1 * r_h1) + ... + (c_n * r_hn)` * Input: * `expected_tp`: the type of the terms being compared in the target equality * an `option (tactic expr)` : `none`, if there is no sum to add to yet, or `some` containing the base summation equation * a `list name` : a list of names, referring to equalities in the local context * a `list pexpr` : a list of coefficients to be multiplied with the corresponding equalities in the list of names * Output: an `expr`, which proves that the weighted sum of the given equalities added to the base equation holds -/ meta def make_sum_of_hyps_helper (expected_tp : expr) : option (tactic expr) → list expr → list pexpr → tactic expr | none [] [] := to_expr ``(rfl : (0 : %%expected_tp) = 0) | (some tactic_hcombo) [] [] := do tactic_hcombo | none (h_equality :: h_eqs_names) (coeff :: coeffs) := do -- This is the first equality, and we do not have anything to add to it -- h_equality ← get_local h_equality_nam, `(@eq %%eqtp _ _) ← infer_type h_equality | fail!"{h_equality} is expected to be a proof of an equality", is_def_eq eqtp expected_tp <|> fail!("{h_equality} is an equality between terms of type {eqtp}, but is expected to be" ++ " between terms of type {expected_tp}"), make_sum_of_hyps_helper (some (mul_equality_expr h_equality coeff)) h_eqs_names coeffs | (some tactic_hcombo) (h_equality :: h_eqs_names) (coeff :: coeffs) := do -- h_equality ← get_local h_equality_nam, hcombo ← tactic_hcombo, -- We want to add this weighted equality to the current equality in -- the hypothesis make_sum_of_hyps_helper (some (sum_two_hyps_one_mul_helper hcombo h_equality coeff)) h_eqs_names coeffs | _ _ _ := do fail ("The length of the input list of equalities should be the " ++ "same as the length of the input list of coefficients") /-- Given a list of names referencing equalities and a list of pexprs representing coefficients, this tactic proves that a weighted sum of the equalities (where each equation is multiplied by the corresponding coefficient) holds. * Input: * `expected_tp`: the type of the terms being compared in the target equality * `h_eqs_names` : a list of names, referring to equalities in the local context * `coeffs` : a list of coefficients to be multiplied with the corresponding equalities in the list of names * Output: an `expr`, which proves that the weighted sum of the equalities holds -/ meta def make_sum_of_hyps (expected_tp : expr) (h_eqs_names : list expr) (coeffs : list pexpr) : tactic expr := make_sum_of_hyps_helper expected_tp none h_eqs_names coeffs /-! ### Part 2: Simplifying -/ /-- This tactic proves that the result of moving all the terms in an equality to the left side of the equals sign by subtracting the right side of the equation from the left side holds. In other words, given `lhs = rhs`, this tactic proves that `lhs - rhs = 0`. * Input: * `h_equality` : an `expr`, whose type should be an equality between terms of type `α`, where there is an instance of `add_group α` * Output: an `expr`, which proves that `lhs - rhs = 0`, where `lhs` and `rhs` are the left and right sides of `h_equality` respectively -/ meta def move_to_left_side (h_equality : expr) : tactic expr := mk_app ``left_minus_right [h_equality] /-- This tactic replaces the target with the result of moving all the terms in the target to the left side of the equals sign by subtracting the right side of the equation from the left side. In other words, when the target is lhs = rhs, this tactic proves that `lhs - rhs = 0` and replaces the target with this new equality. Note: The target must be an equality when this tactic is called, and the equality must have some type `α` on each side, where there is an instance of `add_group α`. * Input: N/A * Output: N/A -/ meta def move_target_to_left_side : tactic unit := do -- Move all the terms in the target equality to the left side target ← target, (targ_lhs, targ_rhs) ← match_eq target, target_left_eq ← to_expr ``(%%targ_lhs - %%targ_rhs = 0), mk_app ``all_on_left_equiv [targ_lhs, targ_rhs] >>= replace_target target_left_eq /-! ### Part 3: Matching the Linear Combination to the Target -/ /-- This tactic changes the goal to be that the lefthand side of the target minus the lefthand side of the given expression is equal to 0. For example, if `hsum_on_left` is `5*x - 5*y = 0`, and the target is `-5*y + 5*x = 0`, this tactic will change the target to be `-5*y + 5*x - (5*x - 5*y) = 0`. This tactic only should be used when the target's type is an equality whose right side is 0. * Input: * `hsum_on_left` : expr, whose type should be an equality with 0 on the right side of the equals sign * Output: N/A -/ meta def set_goal_to_hleft_sub_tleft (hsum_on_left : expr) : tactic unit := do to_expr ``(eq_zero_of_sub_eq_zero %%hsum_on_left) >>= apply, skip /-- This tactic attempts to prove the goal by normalizing the target if the `normalize` field of the given configuration is true. * Input: * `config` : a `linear_combination_config`, which determines the tactic used for normalization if normalization is done * Output: N/A -/ meta def normalize_if_desired (config : linear_combination_config) : tactic unit := when config.normalize config.normalization_tactic /-! ### Part 4: Completed Tactic -/ /-- This is a tactic that attempts to simplify the target by creating a linear combination of a list of equalities and subtracting it from the target. (If the `normalize` field of the configuration is set to ff, then the tactic will simply set the user up to prove their target using the linear combination instead of normalizing the subtraction.) Note: The left and right sides of all the equalities should have the same ring type, and the coefficients should also have this type. There must be instances of `has_mul` and `add_group` for this type. Also note that the target must involve at least one variable. * Input: * `h_eqs_names` : a list of names, referring to equations in the local context * `coeffs` : a list of coefficients to be multiplied with the corresponding equations in the list of names * `config` : a `linear_combination_config`, which determines the tactic used for normalization; by default, this value is the standard configuration for a `linear_combination_config` * Output: N/A -/ meta def linear_combination (h_eqs_names : list pexpr) (coeffs : list pexpr) (config : linear_combination_config := {}) : tactic unit := do `(@eq %%ext _ _) ← target | fail "linear_combination can only be used to prove equality goals", h_eqs ← h_eqs_names.mmap to_expr, hsum ← make_sum_of_hyps ext h_eqs coeffs, hsum_on_left ← move_to_left_side hsum, move_target_to_left_side, set_goal_to_hleft_sub_tleft hsum_on_left, normalize_if_desired config /-- `mk_mul [p₀, p₁, ..., pₙ]` produces the pexpr `p₀ * p₁ * ... * pₙ`. -/ meta def mk_mul : list pexpr → pexpr | [] := ``(1) | [e] := e | (e::es) := ``(%%e * %%(mk_mul es)) /-- `as_linear_combo neg ms e` is used to parse the argument to `linear_combination`. This argument is a sequence of literals `x`, `-x`, or `c*x` combined with `+` or `-`, given by the pexpr `e`. The `neg` and `ms` arguments are used recursively; called at the top level, its usage should be `as_linear_combo ff [] e`. -/ meta def as_linear_combo : bool → list pexpr → pexpr → list (pexpr × pexpr) | neg ms e := let (head, args) := pexpr.get_app_fn_args e in match head.get_frozen_name, args with | ``has_add.add, [e1, e2] := as_linear_combo neg ms e1 ++ as_linear_combo neg ms e2 | ``has_sub.sub, [e1, e2] := as_linear_combo neg ms e1 ++ as_linear_combo (bnot neg) ms e2 | ``has_mul.mul, [e1, e2] := as_linear_combo neg (e1::ms) e2 | ``has_div.div, [e1, e2] := as_linear_combo neg (``((%%e2)⁻¹)::ms) e1 | ``has_neg.neg, [e1] := as_linear_combo (bnot neg) ms e1 | _, _ := let m := mk_mul ms in [(e, if neg then ``(-%%m) else m)] end section interactive_mode setup_tactic_parser /-- `linear_combination` attempts to simplify the target by creating a linear combination of a list of equalities and subtracting it from the target. The tactic will create a linear combination by adding the equalities together from left to right, so the order of the input hypotheses does matter. If the `normalize` field of the configuration is set to false, then the tactic will simply set the user up to prove their target using the linear combination instead of normalizing the subtraction. Note: The left and right sides of all the equalities should have the same type, and the coefficients should also have this type. There must be instances of `has_mul` and `add_group` for this type. * Input: * `input` : the linear combination of proofs of equalities, given as a sum/difference of coefficients multiplied by expressions. The coefficients may be arbitrary pre-expressions; if a coefficient is an application of `+` or `-` it should be surrounded by parentheses. The expressions can be arbitrary proof terms proving equalities. Most commonly they are hypothesis names `h1, h2, ...`. If a coefficient is omitted, it is taken to be `1`. * `config` : a `linear_combination_config`, which determines the tactic used for normalization; by default, this value is the standard configuration for a linear_combination_config. In the standard configuration, `normalize` is set to tt (meaning this tactic is set to use normalization), and `normalization_tactic` is set to `ring_nf SOP`. Example Usage: ``` example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination 1*h1 - 2*h2 example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination h1 - 2*h2 example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := begin linear_combination -2*h2, /- Goal: x * y + x * 2 - 1 = 0 -/ end example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : -3*x - 3*y - 4*z = 2 := by linear_combination ha - hb - 2*hc example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := by linear_combination x*y*h1 + 2*h2 example (x y : ℤ) (h1 : x = -3) (h2 : y = 10) : 2*x = -6 := begin linear_combination 2*h1 with {normalize := ff}, simp, norm_cast end constants (qc : ℚ) (hqc : qc = 2*qc) example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by linear_combination 3 * h a b + hqc ``` -/ meta def _root_.tactic.interactive.linear_combination (input : parse (as_linear_combo ff [] <$> texpr)?) (_ : parse (tk "with")?) (config : linear_combination_config := {}) : tactic unit := let (h_eqs_names, coeffs) := list.unzip (input.get_or_else []) in linear_combination h_eqs_names coeffs config add_tactic_doc { name := "linear_combination", category := doc_category.tactic, decl_names := [`tactic.interactive.linear_combination], tags := ["arithmetic"] } end interactive_mode end linear_combo
1e99989b43b4983343801bc8fe1b75a91253803a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/quadratic_form/real.lean
757b98001d69a342a10b9162056e994addb1881e
[ "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
4,357
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Kexing Ying, Eric Wieser -/ import linear_algebra.quadratic_form.basic import analysis.special_functions.pow import data.real.sign /-! # Real quadratic forms Sylvester's law of inertia `equivalent_one_neg_one_weighted_sum_squared`: A real quadratic form is equivalent to a weighted sum of squares with the weights being ±1 or 0. When the real quadratic form is nondegerate we can take the weights to be ±1, as in `equivalent_one_zero_neg_one_weighted_sum_squared`. -/ namespace quadratic_form open_locale big_operators open real finset variables {ι : Type*} [fintype ι] /-- The isometry between a weighted sum of squares with weights `u` on the (non-zero) real numbers and the weighted sum of squares with weights `sign ∘ u`. -/ noncomputable def isometry_sign_weighted_sum_squares [decidable_eq ι] (w : ι → ℝ) : isometry (weighted_sum_squares ℝ w) (weighted_sum_squares ℝ (sign ∘ w)) := begin let u := λ i, if h : w i = 0 then (1 : ℝˣ) else units.mk0 (w i) h, have hu' : ∀ i : ι, (sign (u i) * u i) ^ - (1 / 2 : ℝ) ≠ 0, { intro i, refine (ne_of_lt (real.rpow_pos_of_pos (sign_mul_pos_of_ne_zero _ $ units.ne_zero _) _)).symm}, convert ((weighted_sum_squares ℝ w).isometry_basis_repr ((pi.basis_fun ℝ ι).units_smul (λ i, (is_unit_iff_ne_zero.2 $ hu' i).unit))), ext1 v, rw [basis_repr_apply, weighted_sum_squares_apply, weighted_sum_squares_apply], refine sum_congr rfl (λ j hj, _), have hsum : (∑ (i : ι), v i • ((is_unit_iff_ne_zero.2 $ hu' i).unit : ℝ) • (pi.basis_fun ℝ ι) i) j = v j • (sign (u j) * u j) ^ - (1 / 2 : ℝ), { rw [finset.sum_apply, sum_eq_single j, pi.basis_fun_apply, is_unit.unit_spec, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_same, smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_one], intros i _ hij, rw [pi.basis_fun_apply, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_noteq hij.symm, pi.zero_apply, smul_eq_mul, smul_eq_mul, mul_zero, mul_zero], intro hj', exact false.elim (hj' hj) }, simp_rw basis.units_smul_apply, erw [hsum], simp only [u, function.comp, smul_eq_mul], split_ifs, { simp only [h, zero_smul, zero_mul, sign_zero] }, have hwu : w j = u j, { simp only [u, dif_neg h, units.coe_mk0] }, simp only [hwu, units.coe_mk0], suffices : (u j : ℝ).sign * v j * v j = (sign (u j) * u j) ^ - (1 / 2 : ℝ) * (sign (u j) * u j) ^ - (1 / 2 : ℝ) * u j * v j * v j, { erw [← mul_assoc, this], ring }, rw [← real.rpow_add (sign_mul_pos_of_ne_zero _ $ units.ne_zero _), show - (1 / 2 : ℝ) + - (1 / 2) = -1, by ring, real.rpow_neg_one, mul_inv₀, inv_sign, mul_assoc (sign (u j)) (u j)⁻¹, inv_mul_cancel (units.ne_zero _), mul_one], apply_instance end /-- **Sylvester's law of inertia**: A nondegenerate real quadratic form is equivalent to a weighted sum of squares with the weights being ±1. -/ theorem equivalent_one_neg_one_weighted_sum_squared {M : Type*} [add_comm_group M] [module ℝ M] [finite_dimensional ℝ M] (Q : quadratic_form ℝ M) (hQ : (associated Q).nondegenerate) : ∃ w : fin (finite_dimensional.finrank ℝ M) → ℝ, (∀ i, w i = -1 ∨ w i = 1) ∧ equivalent Q (weighted_sum_squares ℝ w) := let ⟨w, ⟨hw₁⟩⟩ := Q.equivalent_weighted_sum_squares_units_of_nondegenerate' hQ in ⟨sign ∘ coe ∘ w, λ i, sign_apply_eq_of_ne_zero (w i) (w i).ne_zero, ⟨hw₁.trans (isometry_sign_weighted_sum_squares (coe ∘ w))⟩⟩ /-- **Sylvester's law of inertia**: A real quadratic form is equivalent to a weighted sum of squares with the weights being ±1 or 0. -/ theorem equivalent_one_zero_neg_one_weighted_sum_squared {M : Type*} [add_comm_group M] [module ℝ M] [finite_dimensional ℝ M] (Q : quadratic_form ℝ M) : ∃ w : fin (finite_dimensional.finrank ℝ M) → ℝ, (∀ i, w i = -1 ∨ w i = 0 ∨ w i = 1) ∧ equivalent Q (weighted_sum_squares ℝ w) := let ⟨w, ⟨hw₁⟩⟩ := Q.equivalent_weighted_sum_squares in ⟨sign ∘ coe ∘ w, λ i, sign_apply_eq (w i), ⟨hw₁.trans (isometry_sign_weighted_sum_squares w)⟩⟩ end quadratic_form
ad6c2b5c188713279a452888e51c1614bcd02245
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/monotonicity.lean
acac5cef47471a621b611dfb9da14368994c377d
[ "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
8,593
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity import tactic.norm_num import algebra.ordered_ring import measure_theory.lebesgue_measure import data.list.defs open list tactic tactic.interactive set example (h : 3 + 6 ≤ 4 + 5) : 1 + 3 + 2 + 6 ≤ 4 + 2 + 1 + 5 := begin ac_mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin ac_mono, mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin transitivity (1 + 3 + 2 - 5 : ℤ), { ac_mono }, { ac_mono }, end example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, norm_num end example (x y z a b : ℤ) (h : a ≤ (b : ℤ)) (h' : z ≤ y) : (1 + a + x) - y ≤ (1 + b + x) - z := begin transitivity (1 + a + x - z), { mono, }, { mono, mono, mono }, end example (x y z : ℤ) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin transitivity (1 + 3 + x - z), { mono }, { mono, mono, norm_num }, end example (x y z : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin ac_mono, mono* end @[simp] def list.le' {α : Type*} [has_le α] : list α → list α → Prop | (x::xs) (y::ys) := x ≤ y ∧ list.le' xs ys | [] [] := true | _ _ := false @[simp] instance list_has_le {α : Type*} [has_le α] : has_le (list α) := ⟨ list.le' ⟩ lemma list.le_refl {α : Type*} [preorder α] {xs : list α} : xs ≤ xs := begin induction xs with x xs, { trivial }, { simp [has_le.le,list.le], split, apply le_refl, apply xs_ih } end -- @[trans] lemma list.le_trans {α : Type*} [preorder α] {xs zs : list α} (ys : list α) (h : xs ≤ ys) (h' : ys ≤ zs) : xs ≤ zs := begin revert ys zs, induction xs with x xs ; intros ys zs h h' ; cases ys with y ys ; cases zs with z zs ; try { cases h ; cases h' ; done }, { apply list.le_refl }, { simp [has_le.le,list.le], split, apply le_trans h.left h'.left, apply xs_ih _ h.right h'.right, } end @[mono] lemma list_le_mono_left {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : xs ++ zs ≤ ys ++ zs := begin revert ys, induction xs with x xs ; intros ys h, { cases ys, apply list.le_refl, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, revert h, apply and.imp_right, apply xs_ih } end @[mono] lemma list_le_mono_right {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : zs ++ xs ≤ zs ++ ys := begin revert ys zs, induction xs with x xs ; intros ys zs h, { cases ys, { simp, apply list.le_refl }, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, suffices : list.le' ((zs ++ [x]) ++ xs) ((zs ++ [y]) ++ ys), { refine cast _ this, simp, }, apply list.le_trans (zs ++ [y] ++ xs), { apply list_le_mono_left, induction zs with z zs, { simp [has_le.le,list.le], apply h.left }, { simp [has_le.le,list.le], split, apply le_refl, apply zs_ih, } }, { apply xs_ih h.right, } } end lemma bar_bar' (h : [] ++ [3] ++ [2] ≤ [1] ++ [5] ++ [4]) : [] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end lemma bar_bar'' (h : [3] ++ [2] ++ [2] ≤ [5] ++ [4] ++ []) : [1] ++ ([3] ++ [2]) ++ [2] ≤ [1] ++ [5] ++ ([4] ++ []) := begin ac_mono, end lemma bar_bar (h : [3] ++ [2] ≤ [5] ++ [4]) : [1] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end def P (x : ℕ) := 7 ≤ x def Q (x : ℕ) := x ≤ 7 @[mono] lemma P_mono {x y : ℕ} (h : x ≤ y) : P x → P y := by { intro h', apply le_trans h' h } @[mono] lemma Q_mono {x y : ℕ} (h : y ≤ x) : Q x → Q y := by apply le_trans h example (x y z : ℕ) (h : x ≤ y) : P (x + z) → P (z + y) := begin ac_mono, ac_mono, end example (x y z : ℕ) (h : y ≤ x) : Q (x + z) → Q (z + y) := begin ac_mono, ac_mono, end example (x y z k m n : ℤ) (h₀ : z ≤ 0) (h₁ : y ≤ x) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : n + x + m ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono* : m + x + n ≤ y + n + m, transitivity ; [ skip , apply h₁ ], apply le_of_eq, ac_refl, end example (x y z k m n : ℤ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, success_if_fail { ac_mono }, admit }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono*, change 0 ≤ z, apply nat.zero_le, }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, change (m + x + n) * z ≤ z * (y + n + m), admit }, trivial, end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono^3, cc end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : z * (x + i + n + m) + k = z * (y + j + n + m) + k := begin congr, simp [h₁], end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono*, cc, end example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 1, end example {x y z : ℕ} : true := begin have : y + x ≤ y + z, { mono, guard_target' x ≤ z, admit }, trivial end example {x y z : ℕ} : true := begin suffices : x + y ≤ z + y, trivial, mono, guard_target' x ≤ z, admit, end example {x y z w : ℕ} : true := begin have : x + y ≤ z + w, { mono, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : ℕ} : true := begin have : x * y ≤ z * w, { mono with [0 ≤ z,0 ≤ y], { guard_target 0 ≤ z, admit }, { guard_target 0 ≤ y, admit }, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∧ y → z ∧ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∨ y → z ∨ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : ℤ} : true := begin suffices : x + y < w + z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, end example {x y z w : ℤ} : true := begin suffices : x * y < w * z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, { guard_target' 0 < y, admit }, { guard_target' 0 ≤ w, admit }, end open tactic example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 3 end example {α} [linear_order α] (a b c d e : α) : max a b ≤ e → b ≤ e := by { mono, apply le_max_right } example (a b c d e : Prop) (h : d → a) (h' : c → e) : (a ∧ b → c) ∨ d → (d ∧ b → e) ∨ a := begin mono, mono, mono, end example : ∫ x in Icc 0 1, real.exp x ≤ ∫ x in Icc 0 1, real.exp (x+1) := begin mono, { exact real.continuous_exp.integrable_on_compact is_compact_Icc }, { exact (real.continuous_exp.comp $ continuous_add_right 1).integrable_on_compact is_compact_Icc }, intro x, dsimp only, mono, linarith end
e7b9a74b57d8aaa48d12857dd753bac721f823f7
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/ring_theory/subring.lean
76edb142cc94ca664a7786e06a2a6aae73488471
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
8,255
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import deprecated.subgroup universes u v open group variables {R : Type u} [ring R] section prio set_option default_priority 100 -- see Note [default priority] /-- `S` is a subring: a set containing 1 and closed under multiplication, addition and and additive inverse. -/ class is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop. end prio instance subset.ring {S : set R} [is_subring S] : ring S := { left_distrib := λ x y z, subtype.eq $ left_distrib x.1 y.1 z.1, right_distrib := λ x y z, subtype.eq $ right_distrib x.1 y.1 z.1, .. subtype.add_comm_group, .. subtype.monoid } instance subtype.ring {S : set R} [is_subring S] : ring (subtype S) := subset.ring namespace ring_hom instance is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] : is_subring (f ⁻¹' s) := {} instance is_subring_image {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set R) [is_subring s] : is_subring (f '' s) := {} instance is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : is_subring (set.range f) := {} end ring_hom /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def ring_hom.cod_restrict {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } /-- Coersion `S → R` as a ring homormorphism-/ def is_subring.subtype (S : set R) [is_subring S] : S →+* R := ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ @[simp] lemma is_subring.coe_subtype {S : set R} [is_subring S] : ⇑(is_subring.subtype S) = coe := rfl variables {cR : Type u} [comm_ring cR] instance subset.comm_ring {S : set cR} [is_subring S] : comm_ring S := { mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1, .. subset.ring } instance subtype.comm_ring {S : set cR} [is_subring S] : comm_ring (subtype S) := subset.comm_ring instance subring.domain {D : Type*} [integral_domain D] (S : set D) [is_subring S] : integral_domain S := { zero_ne_one := mt subtype.ext_iff_val.1 zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨x, hx⟩ ⟨y, hy⟩, by { simp only [subtype.ext_iff_val, subtype.coe_mk], exact eq_zero_or_eq_zero_of_mul_eq_zero }, .. subset.comm_ring } instance is_subring.inter (S₁ S₂ : set R) [is_subring S₁] [is_subring S₂] : is_subring (S₁ ∩ S₂) := { } instance is_subring.Inter {ι : Sort*} (S : ι → set R) [h : ∀ y : ι, is_subring (S y)] : is_subring (set.Inter S) := { } lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set R) [∀ i, is_subring (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subring (⋃i, s i) := { to_is_add_subgroup := is_add_subgroup_Union_of_directed s directed, to_is_submonoid := is_submonoid_Union_of_directed s directed } namespace ring def closure (s : set R) := add_group.closure (monoid.closure s) variable {s : set R} local attribute [reducible] closure theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) : (∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) := add_group.in_closure.rec_on h (λ x hx, match x, monoid.exists_list_of_mem_closure hx with | _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩ end) ⟨[], list.forall_mem_nil _, rfl⟩ (λ b _ ih, match b, ih with | _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)), λ L2 h2, match L2, list.mem_map.1 h2 with | _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩ end, by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul]; exact list.rec_on L1 neg_zero.symm (λ hd tl ih, by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩ end) (λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with | _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩, by rw [list.map_append, list.sum_append]⟩ end) @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end instance : is_subring (closure s) := { one_mem := add_group.mem_closure is_submonoid.one_mem, mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb (λ b hb, add_group.in_closure.rec_on ha (λ a ha, add_group.subset_closure (is_submonoid.mul_mem ha hb)) ((zero_mul b).symm ▸ is_add_submonoid.zero_mem) (λ a ha hab, (neg_mul_eq_neg_mul a b) ▸ is_add_subgroup.neg_mem hab) (λ a c ha hc hab hcb, (add_mul a c b).symm ▸ is_add_submonoid.add_mem hab hcb)) ((mul_zero a).symm ▸ is_add_submonoid.zero_mem) (λ b hb hab, (neg_mul_eq_mul_neg a b) ▸ is_add_subgroup.neg_mem hab) (λ b c hb hc hab hac, (mul_add a b c).symm ▸ is_add_submonoid.add_mem hab hac), .. add_group.closure.is_add_subgroup _ } theorem mem_closure {a : R} : a ∈ s → a ∈ closure s := add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _ theorem subset_closure : s ⊆ closure s := λ _, mem_closure theorem closure_subset {t : set R} [is_subring t] : s ⊆ t → closure s ⊆ t := add_group.closure_subset ∘ monoid.closure_subset theorem closure_subset_iff (s t : set R) [is_subring t] : closure s ⊆ t ↔ s ⊆ t := (add_group.closure_subset_iff _ t).trans ⟨set.subset.trans monoid.subset_closure, monoid.closure_subset⟩ theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure lemma image_closure {S : Type*} [ring S] (f : R →+* S) (s : set R) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { rw [f.map_one], apply is_submonoid.one_mem }, { rw [f.map_neg, f.map_one], apply is_add_subgroup.neg_mem, apply is_submonoid.one_mem }, { rw [f.map_mul], apply is_submonoid.mul_mem; solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [f.map_add], apply is_add_submonoid.add_mem, assumption' }, end (closure_subset $ set.image_subset _ subset_closure) end ring
39901967c4b1863933ab884d147f08d5ac39eddf
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/universal/comparisons.lean
1f9a26fb1ce2bf9d31660131f501914b5ab55e1d
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
6,078
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 ..isomorphism import ..natural_transformation import ..examples.types.types import ..equivalence import .comma_categories import .universal open tqft.categories open tqft.categories.functor open tqft.categories.natural_transformation open tqft.categories.isomorphism open tqft.categories.equivalence open tqft.categories.examples.types open tqft.categories.universal namespace tqft.categories.universal -- This works fine; commented out for speed. -- definition Cones_agree { J C : Category } ( F: Functor J C ) : Isomorphism CategoryOfTypes (comma.Cones F).Obj (Cone F) := { -- morphism := λ C, { -- limit := C.1, -- maps := λ j : J.Obj, (C.2.2).components j, -- commutativity := λ ( j k : J.Obj ) ( f : J.Hom j k ), begin -- refine ( cast _ (eq.symm ((C.2.2).naturality f)) ), -- unfold_unfoldable, -- simp -- end -- }, -- inverse := λ C, ⟨ C.limit, ♯, { -- components := λ j, C.maps j, -- naturality := λ _ _ f, begin refine ( cast _ (eq.symm (C.commutativity f)) ), unfold_unfoldable, simp end -- } ⟩, -- witness_1 := begin -- -- PROJECT gross, but looks automatable. -- -- unfold_unfoldable, -- -- apply funext, -- -- intros, -- -- simp, -- -- fapply dependent_pair_equality, -- -- simp, -- -- reflexivity, -- -- induction x with x_1 x_23, -- -- induction x_23 with x_2 x_3, -- -- induction x_2, -- -- unfold_unfoldable_hypotheses, -- -- simp, -- -- fapply dependent_pair_equality, -- -- reflexivity, -- -- simp, -- -- apply natural_transformation.NaturalTransformations_componentwise_equal, -- -- intros, -- -- dsimp, -- -- reflexivity, -- end, -- witness_2 := begin -- unfold_unfoldable, -- apply funext, -- intros, -- simp, -- end -- } definition comma_Cone_to_Cone { J C : Category } { F : Functor J C } ( cone : (comma.Cones F).Obj ) : Cone F := { limit := cone.1, maps := λ j : J.Obj, (cone.2.2).components j, commutativity := λ ( j k : J.Obj ) ( f : J.Hom j k ), begin refine ( cast _ (eq.symm ((cone.2.2).naturality f)) ), unfold_unfoldable, simp end } definition comma_ConeMorphism_to_ConeMorphism { J C : Category } { F : Functor J C } { X Y : (comma.Cones F).Obj } ( f : (comma.Cones F).Hom X Y ) : ConeMorphism (comma_Cone_to_Cone X) (comma_Cone_to_Cone Y) := { morphism := f.val.1, commutativity := λ j : J.Obj, begin blast, induction X with X1 X23, induction X23 with X2 X3, induction X2, induction Y with Y1 Y23, induction Y23 with Y2 Y3, induction Y2, induction f with T p, induction T with T_1, dsimp, pose q := congr_arg (λ t : NaturalTransformation _ _, t.components j) p, simp at q, dsimp at q, unfold_unfoldable_hypotheses, rewrite q, blast end } definition Cone_to_comma_Cone { J C : Category } { F : Functor J C } ( cone : Cone F ) : (comma.Cones F).Obj := ⟨ cone.limit, ♯, { components := λ j, cone.maps j, naturality := λ _ _ f, begin refine ( cast _ (eq.symm (cone.commutativity f)) ), unfold_unfoldable, simp end } ⟩ definition ConeMorphism_to_comma_ConeMorphism { J C : Category } { F : Functor J C } { X Y : Cone F } ( f : ConeMorphism X Y ) : (comma.Cones F).Hom (Cone_to_comma_Cone X) (Cone_to_comma_Cone Y) := ⟨ (f.morphism, ♯), ♯ ⟩ definition comma_Cones_to_Cones { J C : Category } ( F : Functor J C ) : Functor (comma.Cones F) (Cones F) := { onObjects := comma_Cone_to_Cone, onMorphisms := λ _ _ f, comma_ConeMorphism_to_ConeMorphism f, identities := ♯, functoriality := ♯ } definition Cones_to_comma_Cones { J C : Category } ( F : Functor J C ) : Functor (Cones F) (comma.Cones F) := { onObjects := Cone_to_comma_Cone, onMorphisms := λ _ _ f, ConeMorphism_to_comma_ConeMorphism f, identities := ♯, functoriality := ♯ } lemma Equalizers_agree { C : Category } { α β : C.Obj } ( f g : C.Hom α β ) : @Isomorphism CategoryOfTypes (comma.Equalizer f g) (Equalizer f g) := { morphism := sorry, inverse := sorry, witness_1 := sorry, witness_2 := sorry } -- lemma Equalizers_are_unique -- { C : Category } -- { X Y : C.Obj } -- ( f g : C.Hom X Y ) -- : unique_up_to_isomorphism (Equalizer f g) Equalizer.equalizer -- := λ (E1 E2 : Equalizer f g), -- comma.InitialObjects_are_unique (Isomorphism.inverse (Equalizers_agree f g) E1) ((Equalizers_agree f g).inverse E2) end tqft.categories.universal
45b999c469081e6741afac6a1b981ca64362bd38
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/field_theory/finite/polynomial.lean
8871c3f7ec2ba3d44c6cefb1366d0f2f3e38a01b
[ "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
7,714
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 field_theory.finite.basic import field_theory.mv_polynomial import data.mv_polynomial.expand import linear_algebra.basic import linear_algebra.finite_dimensional /-! ## Polynomials over finite fields -/ namespace mv_polynomial variables {σ : Type*} /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `zmod n`. -/ lemma C_dvd_iff_zmod (n : ℕ) (φ : mv_polynomial σ ℤ) : C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 := C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _ section frobenius variables {p : ℕ} [fact p.prime] lemma frobenius_zmod (f : mv_polynomial σ (zmod p)) : frobenius _ p f = expand p f := begin apply induction_on f, { intro a, rw [expand_C, frobenius_def, ← C_pow, zmod.pow_card], }, { simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] }, { simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul], intros _ _ hf, rw [hf, frobenius_def], }, end lemma expand_zmod (f : mv_polynomial σ (zmod p)) : expand p f = f ^ p := (frobenius_zmod _).symm end frobenius end mv_polynomial namespace mv_polynomial noncomputable theory open_locale big_operators classical open set linear_map submodule variables {K : Type*} {σ : Type*} variables [field K] [fintype K] [fintype σ] def indicator (a : σ → K) : mv_polynomial σ K := ∏ n, (1 - (X n - C (a n))^(fintype.card K - 1)) lemma eval_indicator_apply_eq_one (a : σ → K) : eval a (indicator a) = 1 := have 0 < fintype.card K - 1, begin rw [← finite_field.card_units, fintype.card_pos_iff], exact ⟨1⟩ end, by simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub, is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] lemma eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) : eval a (indicator b) = 0 := have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h, begin rcases this with ⟨i, hi⟩, simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub, is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end lemma degrees_indicator (c : σ → K) : degrees (indicator c) ≤ ∑ s : σ, (fintype.card K - 1) • {s} := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X' _ end lemma indicator_mem_restrict_degree (c : σ → K) : indicator c ∈ restrict_degree σ K (fintype.card K - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), rw [← finset.univ.sum_hom (multiset.count n)], simp only [is_add_monoid_hom.map_nsmul (multiset.count n), multiset.singleton_eq_singleton, nsmul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_cons_self, multiset.count_zero, mul_one] } end section variables (K σ) def evalₗ : mv_polynomial σ K →ₗ[K] (σ → K) → K := ⟨ λp e, eval e p, assume p q, (by { ext x, rw ring_hom.map_add, refl, }), assume a p, funext $ assume e, by rw [smul_eq_C_mul, ring_hom.map_mul, eval_C]; refl ⟩ end lemma evalₗ_apply (p : mv_polynomial σ K) (e : σ → K) : evalₗ K σ p e = eval e p := rfl lemma map_restrict_dom_evalₗ : (restrict_degree σ K (fintype.card K - 1)).map (evalₗ K σ) = ⊤ := begin refine top_unique (set_like.le_def.2 $ assume e _, mem_map.2 _), refine ⟨∑ n : σ → K, e n • indicator n, _, _⟩, { exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @finset.sum_apply (σ → K) (λ_, K) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n _ _, { assume b _ h, rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { assume h, exact (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial open_locale classical open linear_map submodule universe u variables (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] @[derive [add_comm_group, module K, inhabited]] def R : Type u := restrict_degree σ K (fintype.card K - 1) noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance lemma dim_R : module.rank K (R σ K) = fintype.card (σ → K) := calc module.rank K (R σ K) = module.rank K (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} →₀ K) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card K - 1 }) ... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} : by rw [finsupp.dim_eq, dim_of_field, mul_one] ... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card K } : begin refine quotient.sound ⟨equiv.subtype_equiv finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, nat.le_sub_right_iff_add_le _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = cardinal.mk (σ → {n // n < fintype.card K}) : quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card K)⟩ ... = cardinal.mk (σ → fin (fintype.card K)) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩ ... = cardinal.mk (σ → K) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (fintype.equiv_fin K).symm⟩ ... = fintype.card (σ → K) : cardinal.fintype_card _ instance : finite_dimensional K (R σ K) := is_noetherian.iff_dim_lt_omega.mpr (by simpa only [dim_R] using cardinal.nat_lt_omega (fintype.card (σ → K))) lemma finrank_R : finite_dimensional.finrank K (R σ K) = fintype.card (σ → K) := finite_dimensional.finrank_eq_of_dim_eq (dim_R σ K) def evalᵢ : R σ K →ₗ[K] (σ → K) → K := ((evalₗ K σ).comp (restrict_degree σ K (fintype.card K - 1)).subtype) lemma range_evalᵢ : (evalᵢ σ K).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ : (evalᵢ σ K).ker = ⊥ := begin refine (ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank _).mpr (range_evalᵢ _ _), rw [finite_dimensional.finrank_fintype_fun_eq_card, finrank_R] end lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ K) (h : ∀v:σ → K, eval v p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) : p = 0 := let p' : R σ K := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ K).ker := by { rw [mem_ker], ext v, exact h v }, show p'.1 = (0 : R σ K).1, begin rw [ker_evalₗ, mem_bot] at this, rw [this] end end mv_polynomial
34257655b60f7d35e4c3489e2d26064ffa402f0d
63abd62053d479eae5abf4951554e1064a4c45b4
/src/linear_algebra/direct_sum_module.lean
e61309c37bfbbc56826d1b7980b81318df280fd0
[ "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
4,987
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of modules over commutative rings, indexed by a discrete type. -/ import algebra.direct_sum import linear_algebra.basic /-! # Direct sum of modules over commutative rings, indexed by a discrete type. This file provides constructors for finite direct sums of modules. It provides a construction of the direct sum using the universal property and proves its uniqueness. ## Implementation notes All of this file assumes that * `R` is a commutative ring, * `ι` is a discrete type, * `S` is a finite set in `ι`, * `M` is a family of `R` semimodules indexed over `ι`. -/ universes u v w u₁ variables (R : Type u) [semiring R] variables (ι : Type v) [dec_ι : decidable_eq ι] (M : ι → Type w) variables [Π i, add_comm_monoid (M i)] [Π i, semimodule R (M i)] include R namespace direct_sum open_locale direct_sum variables {R ι M} instance : semimodule R (⨁ i, M i) := dfinsupp.semimodule lemma smul_apply (b : R) (v : ⨁ i, M i) (i : ι) : (b • v) i = b • (v i) := dfinsupp.smul_apply _ _ _ include dec_ι variables R ι M /-- Create the direct sum given a family `M` of `R` semimodules indexed over `ι`. -/ def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.val) →ₗ[R] (⨁ i, M i) := dfinsupp.lmk M R /-- Inclusion of each component into the direct sum. -/ def lof : Π i : ι, M i →ₗ[R] (⨁ i, M i) := dfinsupp.lsingle M R variables {ι M} lemma single_eq_lof (i : ι) (b : M i) : dfinsupp.single i b = lof R ι M i b := rfl /-- Scalar multiplication commutes with direct sums. -/ theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x := (lmk R ι M s).map_smul c x /-- Scalar multiplication commutes with the inclusion of each component into the direct sum. -/ theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x := (lof R ι M i).map_smul c x variables {R} lemma support_smul [Π (i : ι) (x : M i), decidable (x ≠ 0)] (c : R) (v : ⨁ i, M i) : (c • v).support ⊆ v.support := dfinsupp.support_smul _ _ variables {N : Type u₁} [add_comm_monoid N] [semimodule R N] variables (φ : Π i, M i →ₗ[R] N) variables (R ι N φ) /-- The linear map constructed using the universal property of the coproduct. -/ def to_module : (⨁ i, M i) →ₗ[R] N := dfinsupp.lsum φ variables {ι N φ} /-- The map constructed using the universal property gives back the original maps when restricted to each component. -/ @[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x := to_add_monoid_of (λ i, (φ i).to_add_monoid_hom) i x variables (ψ : (⨁ i, M i) →ₗ[R] N) /-- Every linear map from a direct sum agrees with the one obtained by applying the universal property to each of its components. -/ theorem to_module.unique (f : ⨁ i, M i) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f := to_add_monoid.unique ψ.to_add_monoid_hom f variables {ψ} {ψ' : (⨁ i, M i) →ₗ[R] N} theorem to_module.ext (H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) (f : ⨁ i, M i) : ψ f = ψ' f := by rw dfinsupp.lhom_ext' R H /-- The inclusion of a subset of the direct summands into a larger subset of the direct summands, as a linear map. -/ def lset_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), M i) →ₗ (⨁ (i : T), M i) := to_module R _ _ $ λ i, lof R T (λ (i : subtype T), M i) ⟨i, H i.prop⟩ omit dec_ι /-- The natural linear equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ -- TODO: generalize this to arbitrary index type `ι` with `unique ι` protected def lid (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [semimodule R M] [unique ι] : (⨁ (_ : ι), M) ≃ₗ M := { .. direct_sum.id M ι, .. to_module R ι M (λ i, linear_map.id) } variables (ι M) /-- The projection map onto one component, as a linear map. -/ def component (i : ι) : (⨁ i, M i) →ₗ[R] M i := { to_fun := λ f, f i, map_add' := λ f g, dfinsupp.add_apply f g i, map_smul' := λ c f, dfinsupp.smul_apply c f i} variables {ι M} lemma apply_eq_component (f : ⨁ i, M i) (i : ι) : f i = component R ι M i f := rfl @[ext] lemma ext {f g : ⨁ i, M i} (h : ∀ i, component R ι M i f = component R ι M i g) : f = g := dfinsupp.ext h lemma ext_iff {f g : ⨁ i, M i} : f = g ↔ ∀ i, component R ι M i f = component R ι M i g := ⟨λ h _, by rw h, ext R⟩ include dec_ι @[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b := by rw [lof, dfinsupp.lsingle_apply, dfinsupp.single_apply, dif_pos rfl] @[simp] lemma component.lof_self (i : ι) (b : M i) : component R ι M i ((lof R ι M i) b) = b := lof_apply R i b lemma component.of (i j : ι) (b : M j) : component R ι M i ((lof R ι M j) b) = if h : j = i then eq.rec_on h b else 0 := dfinsupp.single_apply end direct_sum
87cc0f533e096f2abcba262baf696ad1a08abd63
76c77df8a58af24dbf1d75c7012076a42244d728
/tutorial_src/exercises/02_iff_if_and.lean
9dcad0803cb95c31a19146f5a40a56a2fb5cbac1
[]
no_license
kris-brown/theorem_proving_in_lean
7a7a584ba2c657a35335dc895d49d991c997a0c9
774460c21bf857daff158210741bd88d1c8323cd
refs/heads/master
1,668,278,123,743
1,593,445,161,000
1,593,445,161,000
265,748,924
0
1
null
null
null
null
UTF-8
Lean
false
false
14,975
lean
import data.real.basic /- In the previous file, we saw how to rewrite using equalities. The analogue operation with mathematical statements is rewriting using equivalences. This is also done using the `rw` tactic. Lean uses ↔ to denote equivalence instead of ⇔. In the following exercises we will use the lemma: sub_nonneg {x y : ℝ} : 0 ≤ y - x ↔ x ≤ y The curly braces around x and y instead of parentheses mean Lean will always try to figure out what x and y are from context, unless we really insist on telling it (we'll see how to insist much later). Let's not worry about that for now. In order to announce an intermediate statement we use: have my_name : my statement, This triggers the apparition of a new goal: proving the statement. After this is done, the statement becomes available under the name `my_name`. We can focus on the current goal by typing tactics between curly braces. -/ example {a b c : ℝ} (hab : a ≤ b) : c + a ≤ c + b := begin rw ← sub_nonneg, have key : (c + b) - (c + a) = b - a, -- Here we introduce an intermediate statement named key { ring, }, -- and prove it between curly braces rw key, -- we can now use the key statement rw sub_nonneg, exact hab, end /- Of course the previous lemma is already in the core library, named `add_le_add_left`, so we can use it below. Let's prove a variation (without invoking commutativity of addition since this would spoil our fun). -/ -- 0009 example {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c := begin have key : c + a ≤ c + b, {apply add_le_add_left hab}, rw add_comm c a at key, rw add_comm c b at key, exact key end /- Let's see how we could use this lemma. It is already in the core library, under the name `add_le_add_right`: add_le_add_right {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c This can be read as: "add_le_add_right is a function that will take as input real numbers a and b, an assumption `hab` claiming a ≤ b and a real number c, and will output a proof of a + c ≤ b + c". In addition, recall that curly braces around a b mean Lean will figure out those arguments unless we insist to help. This is because they can be deduced from the next argument `hab`. So it will be sufficient to feed `hab` and c to this function. -/ example {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by ring ... ≤ a + b : by exact add_le_add_right ha b, end /- In the second line of the above proof, we need to prove 0 + b ≤ a + b. The proof after the colon says: this is exactly lemma `add_le_add_right` applied to ha and b. Actually the `calc` block expects proof terms, and the `by` keyword is used to tell Lean we will use tactics to build such a proof term. But since the only tactic used in this block is `exact`, we can skip tactics entirely, and write: -/ example (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by rw zero_add b ... ≤ a + b : add_le_add_right ha b, end /- Let's do a variant. -/ -- 0010 example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin have key : a+0 ≤ a+b, {by apply add_le_add_left hb a}, rw (add_zero a) at key, exact key end /- The two preceding examples are in the core library : le_add_of_nonneg_left {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b le_add_of_nonneg_right {a b : ℝ} (hb : 0 ≤ b) : a ≤ a + b Again, there won't be any need to memorize those names, we will soon see how to get rid of such goals automatically. But we can already try to understand how their names are built: "le_add" describe the conclusion "less or equal than some addition" It comes first because we are focussed on proving stuff, and auto-completion works by looking at the beginning of words. "of" introduces assumptions. "nonneg" is Lean's abbreviation for non-negative. "left" or "right" disambiguates between the two variations. Let's use those lemmas by hand for now. -/ -- 0011 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin calc 0 ≤ b : by exact hb ... ≤ a + b : by apply le_add_of_nonneg_left ha end /- And let's combine with our earlier lemmas. -/ -- 0012 example (a b x y : ℝ) (hab : a ≤ b) (hcd : x ≤ y) : a + x ≤ b + y := begin calc a + x ≤ b + x : by exact add_le_add_right hab x ... ≤ b + y : by exact add_le_add_left hcd b end /- In the above examples, we prepared proofs of assumptions of our lemmas beforehand, so that we could feed them to the lemmas. This is called forward reasonning. The `calc` proofs also belong to this category. We can also announce the use of a lemma, and provide proofs after the fact, using the `apply` tactic. This is called backward reasonning because we get the conclusion first, and provide proofs later. Using `rw` on the goal (rather than on an assumption from the local context) is also backward reasonning. Let's do that using the lemma mul_nonneg' {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : 0 ≤ x*y -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, have key : b*c - a*c = (b - a)*c, { ring }, rw key, apply mul_nonneg', -- Here we don't provide proofs for the lemma's assumptions -- Now we need to provide the proofs. { rw sub_nonneg, exact hab }, { exact hc }, end /- Let's prove the same statement using only forward reasonning: announcing stuff, proving it by working with known facts, moving forward. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, by { rw ← sub_nonneg at hab, exact hab, }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg' hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rw h₂ at h₁, exact h₁, }, rw sub_nonneg at h₃, exact h₃, end /- One reason why the backward reasoning proof is shorter is because Lean can infer of lot of things by comparing the goal and the lemma statement. Indeed in the `apply mul_nonneg'` line, we didn't need to tell Lean that x = b - a and y = c in the lemma. It was infered by "unification" between the lemma statement and the goal. To be fair to the forward reasoning version, we should introduce a convenient variation on `rw`. The `rwa` tactic performs rewrite and then looks for an assumption matching the goal. We can use it to rewrite our latest proof as: -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, { rwa ← sub_nonneg at hab }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg' hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rwa h₂ at h₁, }, rwa sub_nonneg at h₃, end /- Let's now combine forward and backward reasonning, to get our most efficient proof of this statement. Note in particular how unification is used to know what to prove inside the parentheses in the `mul_nonneg'` arguments. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, calc 0 ≤ (b - a)*c : mul_nonneg' (by rwa sub_nonneg) hc ... = b*c - a*c : by ring, end /- Let's now practice all three styles using: mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b sub_nonpos {a b : α} : a - b ≤ 0 ↔ a ≤ b -/ /- First using mostly backward reasonning -/ -- 0013 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin rw ← sub_nonneg, have key : a*c - b*c = (a - b)*c, { ring }, rw key, apply mul_nonneg_of_nonpos_of_nonpos, {rwa [<-sub_nonpos] at hab,}, {exact hc} end /- Using forward reasonning -/ -- 0014 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin rw ← sub_nonneg, have key : a*c - b*c = (a - b)*c, { ring }, rw key, have h₁ : a - b ≤ 0, by rwa [<- sub_nonpos] at hab, exact mul_nonneg_of_nonpos_of_nonpos h₁ hc, end /-- Using a combination of both, with a `calc` block -/ -- 0015 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin sorry end /- Let's now move to proving implications. Lean denotes implications using a simple arrow →, the same it uses for functions (say denoting the type of functions from ℕ to ℕ by ℕ → ℕ). This is because it sees a proof of P ⇒ Q as a function turning a proof of P into a proof Q. Many of the examples that we already met are implications under the hood. For instance we proved le_add_of_nonneg_left (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b But this can be rephrased as le_add_of_nonneg_left (a b : ℝ) : 0 ≤ a → b ≤ a + b In order to prove P → Q, we use the tactic `intros`, followed by an assumption name. This creates an assumption with that name asserting that P holds, and turns the goal into Q. Let's check we can go from our old version of `le_add_of_nonneg_left` to the new one. -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := begin intros ha, exact le_add_of_nonneg_left ha, end /- Actually Lean doesn't make any difference between those two versions. It is also happy with -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := le_add_of_nonneg_left /- No tactic state is shown in the above line because we don't even need to enter tactic mode using `begin` or `by`. Let's practise using `intros`. -/ -- 0016 example (a b : ℝ): 0 ≤ b → a ≤ a + b := begin intros ha, exact le_add_of_nonneg_right ha end /- What about lemmas having more than one assumption? For instance: add_nonneg {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b A natural idea is to use the conjunction operator (logical AND), which Lean denotes by ∧. Assumptions built using this operator can be decomposed using the `cases` tactic, which is a very general assumption-decomposing tactic. -/ example {a b : ℝ} : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b := begin intros hyp, cases hyp with ha hb, exact add_nonneg ha hb, end /- Needing that intermediate line invoking `cases` shows this formulation is not what is used by Lean. It rather sees `add_nonneg` as two nested implications: if a is non-negative then if b is non-negative then a+b is non-negative. It reads funny, but it is much more convenient to use in practice. -/ example {a b : ℝ} : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := add_nonneg /- The above pattern is so common that implications are defined as right-associative operators, hence parentheses are not needed above. Let's prove that the naive conjunction version implies the funny Lean version. For this we need to know how to prove a conjunction. The `split` tactic creates two goals from a conjunction goal. It can also be used to create two implication goals from an equivalence goal. -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha hb, apply H, split, exact ha, exact hb, end /- Let's practice `cases` and `split`. In the next exercise, P, Q and R denote unspecified mathematical statements. -/ -- 0017 example (P Q R : Prop) : P ∧ Q → Q ∧ P := begin intro hpq, cases hpq with hp hq, split, exact hq, exact hp, end /- Of course using `split` only to be able to use `exact` twice in a row feels silly. One can also use the anonymous constructor syntax: ⟨ ⟩ Beware those are not parentheses but angle brackets. This is a generic way of providing compound objects to Lean when Lean already has a very clear idea of what it is waiting for. So we could have replaced the last three lines by: exact ⟨hQ, hP⟩ We can also combine the `intros` steps. We can now compress our earlier proof to: -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha hb, exact H ⟨ha, hb⟩, end /- The anonymous contructor trick actually also works in `intros` provided we use its recursive version `rintros`. So we can replace intro h, cases h with h₁ h₂ by rintros ⟨h₁, h₂⟩, Now redo the previous exercise using all those compressing techniques, in exactly two lines. -/ -- 0018 example (P Q R : Prop): P ∧ Q → Q ∧ P := begin rintros ⟨hp, hq⟩, exact ⟨hq, hp⟩ end /- We are ready to come back to the equivalence between the different formulations of lemmas having two assumptions. Remember the `split` tactic can be used to split an equivalence into two implications. -/ -- 0019 example (P Q R : Prop) : (P ∧ Q → R) ↔ (P → (Q → R)) := begin split, assume (hpqr : P ∧ Q → R) (hp : P) (hq : Q), show R, by {apply hpqr, exact ⟨hp,hq⟩}, assume (hpqr : P → (Q → R)) (hpq : P ∧ Q), show R, by {exact hpqr hpq.1 hpq.2} end /- If you used more than five lines in the above exercise then try to compress things (without simply removing line ends). One last compression technique: given a proof h of a conjunction P ∧ Q, one can get a proof of P using h.left and a proof of Q using h.right, without using cases. One can also use the more generic (but less legible) names h.1 and h.2. Similarly, given a proof h of P ↔ Q, one can get a proof of P → Q using h.mp and a proof of Q → P using h.mpr (or the generic h.1 and h.2 that are even less legible in this case). Before the final exercise in this file, let's make sure we'll be able to leave without learning 10 lemma names. The `linarith` tactic will prove any equality or inequality or contradiction that follows by linear combinations of assumptions from the context (with constant coefficients). -/ example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin linarith, end /- Now let's enjoy this for a while. -/ -- 0020 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin linarith end /- And let's combine with our earlier lemmas. -/ -- 0021 example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin linarith end /- Final exercise In the last exercise of this file, we will use the divisibility relation on ℕ, denoted by ∣ (beware this is a unicode divisibility bar, not the ASCII pipe character), and the gcd function. The definitions are the usual ones, but our goal is to avoid using these definitions and only use the following three lemmas: dvd_refl (a : ℕ) : a ∣ a dvd_antisymm {a b : ℕ} : a ∣ b → b ∣ a → a = b := dvd_gcd_iff {a b c : ℕ} : c ∣ gcd a b ↔ c ∣ a ∧ c ∣ b -/ -- All functions and lemmas below are about natural numbers. open nat -- 0022 example (a b : ℕ) : a ∣ b ↔ gcd a b = a := begin have hg : gcd a b ∣ gcd a b, from dvd_refl (gcd a b), rw dvd_gcd_iff at hg, cases hg with hg1 hg2, split, {assume hab : a ∣ b, have h2 : a ∣ gcd a b, from dvd_gcd_iff.mpr ⟨dvd_refl a, hab⟩, exact dvd_antisymm hg1 h2 }, {assume hgab : gcd a b = a, rw hgab at hg2, exact hg2, } end
5ceafae3b0d78304474d9be4caaaea1d99763cd4
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/ideal/operations.lean
df1f2889ee3b85aa69d611475030106efb938ff1
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
74,425
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.operations import algebra.algebra.tower import data.equiv.ring import data.nat.choose.sum import ring_theory.coprime.lemmas import ring_theory.ideal.quotient import ring_theory.non_zero_divisors /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators pointwise namespace submodule variables {R : Type u} {M : Type v} section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [module R M] open_locale pointwise instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, (r : R) • N⟩ /-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker variables {I J : ideal R} {N P : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left _ hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h @[simp] theorem annihilator_smul (N : submodule R M) : annihilator N • N = ⊥ := eq_bot_iff.2 (smul_le.2 (λ r, mem_annihilator.1)) @[simp] theorem annihilator_mul (I : ideal R) : annihilator I * I = ⊥ := annihilator_smul I @[simp] theorem mul_annihilator (I : ideal R) : I * annihilator I = ⊥ := by rw [mul_comm, annihilator_mul] variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) variables {M' : Type w} [add_comm_monoid M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] variables {N N₁ N₂ P P₁ P₂ : submodule R M} /-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/ def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) end comm_ring end submodule namespace ideal section mul_and_radical variables {R : Type u} {ι : Type*} [comm_semiring R] variables {I J K L : ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_range, linear_map.range_id] theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs lemma pow_mem_pow {x : R} (hx : x ∈ I) (n : ℕ) : x ^ n ∈ I ^ n := begin induction n with n ih, { simp only [pow_zero, ideal.one_eq_top], }, simpa only [pow_succ] using mul_mem_mul hx ih, end theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, J.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span, } lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton], } lemma span_singleton_pow (s : R) (n : ℕ): span {s} ^ n = (span {s ^ n} : ideal R) := begin induction n with n ih, { simp [set.singleton_one], }, simp only [pow_succ, ih, span_singleton_mul_span_singleton], end lemma mem_mul_span_singleton {x y : R} {I : ideal R} : x ∈ I * span {y} ↔ ∃ z ∈ I, z * y = x := submodule.mem_smul_span_singleton lemma mem_span_singleton_mul {x y : R} {I : ideal R} : x ∈ span {y} * I ↔ ∃ z ∈ I, y * z = x := by simp only [mul_comm, mem_mul_span_singleton] lemma le_span_singleton_mul_iff {x : R} {I J : ideal R} : I ≤ span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI := show (∀ {zI} (hzI : zI ∈ I), zI ∈ span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI, by simp only [mem_span_singleton_mul] lemma span_singleton_mul_le_iff {x : R} {I J : ideal R} : span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J := begin simp only [mul_le, mem_span_singleton_mul, mem_span_singleton], split, { intros h zI hzI, exact h x (dvd_refl x) zI hzI }, { rintros h _ ⟨z, rfl⟩ zI hzI, rw [mul_comm x z, mul_assoc], exact J.mul_mem_left _ (h zI hzI) }, end lemma span_singleton_mul_le_span_singleton_mul {x y : R} {I J : ideal R} : span {x} * I ≤ span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ := by simp only [span_singleton_mul_le_iff, mem_span_singleton_mul, eq_comm] lemma eq_span_singleton_mul {x : R} (I J : ideal R) : I = span {x} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ (∀ z ∈ J, x * z ∈ I)) := by simp only [le_antisymm_iff, le_span_singleton_mul_iff, span_singleton_mul_le_iff] lemma span_singleton_mul_eq_span_singleton_mul {x y : R} (I J : ideal R) : span {x} * I = span {y} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧ (∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ)) := by simp only [le_antisymm_iff, span_singleton_mul_le_span_singleton_mul, eq_comm] lemma prod_span {ι : Type*} (s : finset ι) (I : ι → set R) : (∏ i in s, ideal.span (I i)) = ideal.span (∏ i in s, I i) := submodule.prod_span s I lemma prod_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) : (∏ i in s, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := submodule.prod_span_singleton s I lemma finset_inf_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) (hI : set.pairwise ↑s (is_coprime on I)) : (s.inf $ λ i, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := begin ext x, simp only [submodule.mem_finset_inf, ideal.mem_span_singleton], exact ⟨finset.prod_dvd_of_coprime hI, λ h i hi, (finset.dvd_prod_of_mem _ hi).trans h⟩ end lemma infi_span_singleton {ι : Type*} [fintype ι] (I : ι → R) (hI : ∀ i j (hij : i ≠ j), is_coprime (I i) (I j)): (⨅ i, ideal.span ({I i} : set R)) = ideal.span {∏ i, I i} := begin rw [← finset.inf_univ_eq_infi, finset_inf_span_singleton], rwa [finset.coe_univ, set.pairwise_univ] end theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩ theorem multiset_prod_le_inf {s : multiset (ideal R)} : s.prod ≤ s.inf := begin classical, refine s.induction_on _ _, { rw [multiset.inf_zero], exact le_top }, intros a s ih, rw [multiset.prod_cons, multiset.inf_cons], exact le_trans mul_le_inf (inf_le_inf (le_refl _) ih) end theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f := multiset_prod_le_inf theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) @[simp] theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I @[simp] theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I @[simp] theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I @[simp] theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma mul_eq_bot {R : Type*} [comm_ring R] [is_domain R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ instance {R : Type*} [comm_ring R] [is_domain R] : no_zero_divisors (ideal R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 } /-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/ lemma prod_eq_bot {R : Type*} [comm_ring R] [is_domain R] {s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ := prod_zero_iff_exists_zero /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸ (add_tsub_assoc_of_le hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni) (λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ add_tsub_cancel_of_le hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) @[simp] theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J := ⟨λ h, le_trans le_radical h, λ h, radical_idem J ▸ radical_mono h⟩ theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm, (pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_nonempty_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm) (m.mul_mem_left _ hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr @[simp] lemma radical_bot_of_is_domain {R : Type u} [comm_ring R] [is_domain R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn)) instance : comm_semiring (ideal R) := submodule.comm_semiring variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : by { rw pow_succ, exact radical_mul _ _ } ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in (hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip, λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left) (le_trans $ le_trans mul_le_inf inf_le_right)⟩ theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h, λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩ theorem is_prime.multiset_prod_le {s : multiset (ideal R)} {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : s.prod ≤ P ↔ ∃ I ∈ s, I ≤ P := suffices s.prod ≤ P → ∃ I ∈ s, I ≤ P, from ⟨this, λ ⟨i, his, hip⟩, le_trans multiset_prod_le_inf $ le_trans (multiset.inf_le his) hip⟩, begin classical, obtain ⟨b, hb⟩ : ∃ b, b ∈ s := multiset.exists_mem_of_ne_zero hne, obtain ⟨t, rfl⟩ : ∃ t, s = b ::ₘ t, from ⟨s.erase b, (multiset.cons_erase hb).symm⟩, refine t.induction_on _ _, { simp only [exists_prop, ←multiset.singleton_eq_cons, multiset.prod_singleton, multiset.mem_singleton, exists_eq_left, imp_self] }, intros a s ih h, rw [multiset.cons_swap, multiset.prod_cons, hp.mul_le] at h, rw multiset.cons_swap, cases h, { exact ⟨a, multiset.mem_cons_self a _, h⟩ }, obtain ⟨I, hI, ih⟩ : ∃ I ∈ b ::ₘ s, I ≤ P := ih h, exact ⟨I, multiset.mem_cons_of_mem hI, ih⟩ end theorem is_prime.multiset_prod_map_le {s : multiset ι} (f : ι → ideal R) {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : (s.map f).prod ≤ P ↔ ∃ i ∈ s, f i ≤ P := begin rw hp.multiset_prod_le (mt multiset.map_eq_zero.mp hne), simp_rw [exists_prop, multiset.mem_map, exists_exists_and_eq_and], end theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hne : s.nonempty) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := hp.multiset_prod_map_le f (mt finset.val_eq_zero.mp hne.ne_empty) theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hsne: s.nonempty) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h, λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩ theorem subset_union {R : Type u} [comm_ring R] {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := ⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi, let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk, or.cases_on (h $ I.add_mem hri hsi) (λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk)) (λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)), λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K) (λ h, set.subset.trans h $ set.subset_union_right J K)⟩ theorem subset_union_prime' {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} {a b : ι} (hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} : (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i, from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_left _ _) (set.subset_union_left _ _)) $ λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_right _ _) (set.subset_union_left _ _)) $ λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $ set.subset_union_right _ _); exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩, begin generalize hn : s.card = n, intros h, unfreezingI { induction n with n ih generalizing a b s }, { clear hp, rw finset.card_eq_zero at hn, subst hn, rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h, simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] }, classical, replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := finset.card_eq_succ.1 hn, unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ }, replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp, by_cases Ht : ∃ j ∈ t, f j ≤ f i, { obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht, obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t, { exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ }, have hp' : ∀ k ∈ insert i u, is_prime (f k), { rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ }, have hiu : i ∉ u := mt finset.mem_insert_of_mem hit, have hn' : (insert i u).card = n, { rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] }, have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k), { rw finset.coe_insert at h ⊢, rw finset.coe_insert at h, simp only [set.bUnion_insert] at h ⊢, rw [← set.union_assoc ↑(f i)] at h, erw [set.union_eq_self_of_subset_right hfji] at h, exact h }, specialize @ih a b (insert i u) hp' hn' h', refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop], exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id }, by_cases Ha : f a ≤ f i, { have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_right_comm ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Ha] at h, exact h }, specialize @ih i b t hp.2 hn h', right, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ }, { exact or.inl ih }, { exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, by_cases Hb : f b ≤ f i, { have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Hb] at h, exact h }, specialize @ih a i t hp.2 hn h', rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inl ih }, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) }, { exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } }, by_cases Hi : I ≤ f i, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) }, have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i, { rcases t.eq_empty_or_nonempty with (rfl | hsne), { rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib], exact ⟨⟨Hi, Ha⟩, Hb⟩ }, simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib], exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ }, rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩, by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j, { specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { left, exact ih }, { right, left, exact ih }, { right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩, rw [finset.coe_insert, set.bUnion_insert] at h, have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs), rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht, { exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) }, { exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) }, { exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) }, { rw set.mem_bUnion_iff at ht, rcases ht with ⟨j, hjt, hj⟩, simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr, exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) } end /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/ theorem subset_union_prime {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i, from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $ show i ∈ (↑s : set ι), from his⟩, assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i), begin classical, tactic.unfreeze_local_instances, by_cases has : a ∈ s, { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩, by_cases hbt : b ∈ t, { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩, have hp' : ∀ i ∈ u, is_prime (f i), { intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert, ← set.union_assoc, subset_union_prime' hp', bex_def] at h, rwa [finset.exists_mem_insert, finset.exists_mem_insert] }, { have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } }, { by_cases hbs : b ∈ s, { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert }, cases s.eq_empty_or_nonempty with hse hsne, { subst hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h, have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem), exact absurd h this }, { cases hsne.bex with i his, obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } } end section dvd /-- If `I` divides `J`, then `I` contains `J`. In a Dedekind domain, to divide and contain are equivalent, see `ideal.dvd_iff_le`. -/ lemma le_of_dvd {I J : ideal R} : I ∣ J → J ≤ I | ⟨K, h⟩ := h.symm ▸ le_trans mul_le_inf inf_le_left lemma is_unit_iff {I : ideal R} : is_unit I ↔ I = ⊤ := is_unit_iff_dvd_one.trans ((@one_eq_top R _).symm ▸ ⟨λ h, eq_top_iff.mpr (ideal.le_of_dvd h), λ h, ⟨⊤, by rw [mul_top, h]⟩⟩) instance unique_units : unique (units (ideal R)) := { default := 1, uniq := λ u, units.ext (show (u : ideal R) = 1, by rw [is_unit_iff.mp u.is_unit, one_eq_top]) } end dvd end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} section semiring variables [semiring R] [semiring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} /-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than the image itself. -/ def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left _ hx }, .. I.to_add_submonoid.comap (f : R →+ S) } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem (f : R →+* S) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ lemma apply_coe_mem_map (f : R →+* S) (I : ideal R) (x : I) : f x ∈ I.map f := mem_map_of_mem f x.prop theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one]; exact (ne_top_iff_one _).1 hK instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, f.map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩ variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [semiring T] {I : ideal T} (f : R →+* S) (g : S →+* T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [semiring T] {I : ideal R} (f : R →+* S) (g : S →+* T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) lemma map_span (f : R →+* S) (s : set R) : map f (span s) = span (f '' s) := symm $ submodule.span_eq_of_le _ (λ y ⟨x, hy, x_eq⟩, x_eq ▸ mem_map_of_mem f (subset_span hy)) (map_le_iff_le_comap.2 $ span_le.2 $ set.image_subset_iff.1 subset_span) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.ne_top, λ x y h, H.mem_or_mem $ by rwa [mem_comap, ring_hom.map_mul] at h⟩ variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f).monotone_l.map_inf_le _ _ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f).monotone_u.le_map_sup _ _ section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem f $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem f hx.left)⟩ lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h end surjective section injective variables (hf : function.injective f) include hf lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective end semiring section ring variables [ring R] [ring S] (f : R →+* S) {I : ideal R} section surjective variables (hf : function.surjective f) include hf theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective {I : ideal R} (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective {K : ideal S} [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end end surjective /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/ @[simp] lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, map_map] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/ @[simp] lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) : (I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/ lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm := le_antisymm (le_comap_of_map_le (map_of_equiv I f).le) (le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le) section bijective variables (hf : function.bijective f) include hf /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map {I : ideal R} {K : ideal S} : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal {I : ideal R} (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) : (⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal := ⟨λ h, (@map_bot _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h, λ h, (@map_bot _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩ end ring section comm_ring variables [comm_ring R] [comm_ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := begin refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _, split, { rintros ⟨x, x_mem, x_eq⟩, simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem }, { intro x_mem, exact ⟨x, x_mem, rfl⟩ } end variables (I J K L) theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw f.map_mul; exact mul_mem_mul (mem_map_of_mem f hri) (mem_map_of_mem f hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← f.map_mul]; exact mem_map_of_mem f (mul_mem_mul hri hsj)) theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (f.map_pow r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩) @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem f hrni⟩ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) end comm_ring end map_and_comap section is_primary variables {R : Type u} [comm_semiring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary end ideal namespace ring_hom variables {R : Type u} {S : Type v} section semiring variables [semiring R] [semiring S] (f : R →+* S) /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = set.preimage f {0} := rfl lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f := by { rw [mem_ker, f.map_one], exact one_ne_zero } end semiring section ring variables [ring R] [semiring S] (f : R →+* S) lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by { rw [set_like.ext'_iff, ker_eq, set.ext_iff], exact f.injective_iff' } lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by { rw [← f.injective_iff, injective_iff_ker_eq_bot] } @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using f.injective end ring section comm_ring variables [comm_ring R] [comm_ring S] (f : R →+* S) /-- The induced map from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) / is surjective (`quotient_ker_equiv_of_surjective`). -/ def ker_lift (f : R →+* S) : f.ker.quotient →+* S := ideal.quotient.lift _ f $ λ r, f.mem_ker.mp @[simp] lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r := ideal.quotient.lift_mk _ _ _ /-- The induced map from the quotient by the kernel is injective. -/ lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) := assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), quotient.sound' $ show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self] variable {f} /-- The **first isomorphism theorem** for commutative rings, computable version. -/ def quotient_ker_equiv_of_right_inverse {g : S → R} (hf : function.right_inverse g f) : f.ker.quotient ≃+* S := { to_fun := ker_lift f, inv_fun := (ideal.quotient.mk f.ker) ∘ g, left_inv := begin rintro ⟨x⟩, apply ker_lift_injective, simp [hf (f x)], end, right_inv := hf, ..ker_lift f} @[simp] lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f) (x : f.ker.quotient) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl @[simp] lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f) (x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl /-- The **first isomorphism theorem** for commutative rings. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) : f.ker.quotient ≃+* S := quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) end comm_ring /-- The kernel of a homomorphism to a domain is a prime ideal. -/ lemma ker_is_prime [ring R] [ring S] [is_domain S] (f : R →+* S) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ /-- The kernel of a homomorphism to a field is a maximal ideal. -/ lemma ker_is_maximal_of_surjective {R K : Type*} [ring R] [field K] (f : R →+* K) (hf : function.surjective f) : f.ker.is_maximal := begin refine ideal.is_maximal_iff.mpr ⟨λ h1, @one_ne_zero K _ _ $ f.map_one ▸ f.mem_ker.mp h1, λ J x hJ hxf hxJ, _⟩, obtain ⟨y, hy⟩ := hf (f x)⁻¹, have H : 1 = y * x - (y * x - 1) := (sub_sub_cancel _ _).symm, rw H, refine J.sub_mem (J.mul_mem_left _ hxJ) (hJ _), rw f.mem_ker, simp only [hy, ring_hom.map_sub, ring_hom.map_one, ring_hom.map_mul, inv_mul_cancel (mt f.mem_ker.mpr hxf), sub_self], end end ring_hom namespace ideal variables {R : Type*} {S : Type*} section semiring variables [semiring R] [semiring S] lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) end semiring section ring variables [ring R] [ring S] lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem f (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem f _), have : ∀ I ∈ A, y ∈ map f I, by simpa using hy, rw [submodule.mem_Inf], intros J hJ, rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩, have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, ring_hom.map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← ring_hom.map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)), abel }, exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem f h) (λ h, hb ▸ mem_map_of_mem f h) } end theorem map_is_prime_of_equiv (f : R ≃+* S) {I : ideal R} [is_prime I] : is_prime (map (f : R →+* S) I) := map_is_prime_of_surjective f.surjective $ by simp end ring section comm_ring variables [comm_ring R] [comm_ring S] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma map_mk_eq_bot_of_le {I J : ideal R} (h : I ≤ J) : I.map (J^.quotient.mk) = ⊥ := by { rw [map_eq_bot_iff_le_ker, mk_ker], exact h } lemma ker_quotient_lift {S : Type v} [comm_ring S] {I : ideal R} (f : R →+* S) (H : I ≤ f.ker) : (ideal.quotient.lift I f H).ker = (f.ker).map I^.quotient.mk := begin ext x, split, { intro hx, obtain ⟨y, hy⟩ := quotient.mk_surjective x, rw [ring_hom.mem_ker, ← hy, ideal.quotient.lift_mk, ← ring_hom.mem_ker] at hx, rw [← hy, mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective], exact ⟨y, hx, rfl⟩ }, { intro hx, rw mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective at hx, obtain ⟨y, hy⟩ := hx, rw [ring_hom.mem_ker, ← hy.right, ideal.quotient.lift_mk, ← (ring_hom.mem_ker f)], exact hy.left }, end theorem map_eq_iff_sup_ker_eq_of_surjective {I J : ideal R} (f : R →+* S) (hf : function.surjective f) : map f I = map f J ↔ I ⊔ f.ker = J ⊔ f.ker := by rw [← (comap_injective_of_surjective f hf).eq_iff, comap_map_of_surjective f hf, comap_map_of_surjective f hf, ring_hom.ker_eq_comap_bot] theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal I.quotient).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ (quotient.mk I) quotient.mk_surjective ⊥ hI, λ hI, @bot_is_maximal _ (@field.to_division_ring _ (@quotient.field _ _ I hI)) ⟩ section quotient_algebra variables (R₁ R₂ : Type*) {A B : Type*} variables [comm_semiring R₁] [comm_semiring R₂] [comm_ring A] [comm_ring B] variables [algebra R₁ A] [algebra R₂ A] [algebra R₁ B] /-- The `R₁`-algebra structure on `A/I` for an `R₁`-algebra `A` -/ instance {I : ideal A} : algebra R₁ (ideal.quotient I) := { to_fun := λ x, ideal.quotient.mk I (algebra_map R₁ A x), smul := (•), smul_def' := λ r x, quotient.induction_on' x $ λ x, ((quotient.mk I).congr_arg $ algebra.smul_def _ _).trans (ring_hom.map_mul _ _ _), commutes' := λ _ _, mul_comm _ _, .. ring_hom.comp (ideal.quotient.mk I) (algebra_map R₁ A) } -- Lean can struggle to find this instance later if we don't provide this shortcut instance [has_scalar R₁ R₂] [is_scalar_tower R₁ R₂ A] (I : ideal A) : is_scalar_tower R₁ R₂ (ideal.quotient I) := by apply_instance /-- The canonical morphism `A →ₐ[R₁] I.quotient` as morphism of `R₁`-algebras, for `I` an ideal of `A`, where `A` is an `R₁`-algebra. -/ def quotient.mkₐ (I : ideal A) : A →ₐ[R₁] I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩ lemma quotient.alg_map_eq (I : ideal A) : algebra_map R₁ I.quotient = (algebra_map A I.quotient).comp (algebra_map R₁ A) := rfl lemma quotient.mkₐ_to_ring_hom (I : ideal A) : (quotient.mkₐ R₁ I).to_ring_hom = ideal.quotient.mk I := rfl @[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) : ⇑(quotient.mkₐ R₁ I) = ideal.quotient.mk I := rfl @[simp] lemma quotient.algebra_map_eq (I : ideal R) : algebra_map R I.quotient = I^.quotient.mk := rfl @[simp] lemma quotient.mk_comp_algebra_map (I : ideal A) : (quotient.mk I).comp (algebra_map R₁ A) = algebra_map R₁ I.quotient := rfl @[simp] lemma quotient.mk_algebra_map (I : ideal A) (x : R₁) : quotient.mk I (algebra_map R₁ A x) = algebra_map R₁ I.quotient x := rfl /-- The canonical morphism `A →ₐ[R₁] I.quotient` is surjective. -/ lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R₁ I) := surjective_quot_mk _ /-- The kernel of `A →ₐ[R₁] I.quotient` is `I`. -/ @[simp] lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R₁ I : A →+* I.quotient).ker = I := ideal.mk_ker variables {R₁} lemma ker_lift.map_smul (f : A →ₐ[R₁] B) (r : R₁) (x : f.to_ring_hom.ker.quotient) : f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x := begin obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R₁ _ x, rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk], exact f.map_smul _ _ end /-- The induced algebras morphism from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) / is surjective (`quotient_ker_alg_equiv_of_surjective`). -/ def ker_lift_alg (f : A →ₐ[R₁] B) : f.to_ring_hom.ker.quotient →ₐ[R₁] B := alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _) @[simp] lemma ker_lift_alg_mk (f : A →ₐ[R₁] B) (a : A) : ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl @[simp] lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R₁] B) : (ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl /-- The induced algebra morphism from the quotient by the kernel is injective. -/ lemma ker_lift_alg_injective (f : A →ₐ[R₁] B) : function.injective (ker_lift_alg f) := ring_hom.ker_lift_injective f /-- The **first isomorphism** theorem for algebras, computable version. -/ def quotient_ker_alg_equiv_of_right_inverse {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) : f.to_ring_hom.ker.quotient ≃ₐ[R₁] B := { ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x), ..ker_lift_alg f} @[simp] lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : f.to_ring_hom.ker.quotient) : quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl @[simp] lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : B) : (quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R₁ f.to_ring_hom.ker (g x) := rfl /-- The **first isomorphism theorem** for algebras. -/ noncomputable def quotient_ker_alg_equiv_of_surjective {f : A →ₐ[R₁] B} (hf : function.surjective f) : f.to_ring_hom.ker.quotient ≃ₐ[R₁] B := quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) /-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : I.quotient →+* J.quotient := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ @[simp] lemma quotient_map_algebra_map {J : ideal A} {I : ideal S} {f : A →+* S} {H : J ≤ I.comap f} {x : R₁} : quotient_map I f H (algebra_map R₁ J.quotient x) = quotient.mk I (f (algebra_map _ _ x)) := quotient.lift_mk J _ _ lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) : (quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f := ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk]) /-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/ @[simps] def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) : I.quotient ≃+* J.quotient := { inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}), left_inv := by {rintro ⟨r⟩, simp }, right_inv := by {rintro ⟨s⟩, simp }, ..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _}) } /-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/ lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (h : I.comap f ≤ J) : function.injective (quotient_map I f H) := begin refine (quotient_map I f H).injective_iff.2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha, exact (quotient.eq_zero_iff_mem).mpr (h ha), end /-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := quotient_map_injective' le_rfl lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (hf : function.surjective f) : function.surjective (quotient_map I f H) := λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩ /-- Commutativity of a square is preserved when taking quotients by an ideal. -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end /-- The algebra hom `A/I →+* B/J` induced by an algebra hom `f : A →ₐ[R₁] B` with `I ≤ f⁻¹(J)`. -/ def quotient_mapₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (hIJ : I ≤ J.comap f) : I.quotient →ₐ[R₁] J.quotient := { commutes' := λ r, by simp, ..quotient_map J ↑f hIJ } @[simp] lemma quotient_map_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) {x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R₁ J (f x) := rfl lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) : (quotient_mapₐ J f H).comp (quotient.mkₐ R₁ I) = (quotient.mkₐ R₁ J).comp f := alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply]) /-- The algebra equiv `A/I ≃ₐ[R] B/J` induced by an algebra equiv `f : A ≃ₐ[R] B`, where`J = f(I)`. -/ def quotient_equiv_alg (I : ideal A) (J : ideal B) (f : A ≃ₐ[R₁] B) (hIJ : J = I.map (f : A →+* B)) : I.quotient ≃ₐ[R₁] J.quotient := { commutes' := λ r, by simp, ..quotient_equiv I J (f : A ≃+* B) hIJ } @[priority 100] instance quotient_algebra {I : ideal A} [algebra R A] : algebra (I.comap (algebra_map R A)).quotient I.quotient := (quotient_map I (algebra_map R A) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective {I : ideal A} [algebra R A]: function.injective (algebra_map (I.comap (algebra_map R A)).quotient I.quotient) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end comm_ring end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_semiring R] [add_comm_monoid M] [module R M] -- TODO: show `[algebra R A] : algebra (ideal R) A` too instance module_submodule : module (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [ring A] [ring B] [ring C] variables (f : A →+* B) (f_inv : B → A) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (f_inv b), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact hf 1 end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [hf _], end, .. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ } @[simp] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a /-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`), * where `f : A →+* B` is has a right_inverse `f_inv` (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end ring_hom namespace double_quot open ideal variables {R : Type u} [comm_ring R] (I J : ideal R) /-- The obvious ring hom `R/I → R/(I ⊔ J)` -/ def quot_left_to_quot_sup : I.quotient →+* (I ⊔ J).quotient := ideal.quotient.factor I (I ⊔ J) le_sup_left /-- The kernel of `quot_left_to_quot_sup` -/ lemma ker_quot_left_to_quot_sup : (quot_left_to_quot_sup I J).ker = J.map (ideal.quotient.mk I) := by simp only [mk_ker, sup_idem, sup_comm, quot_left_to_quot_sup, quotient.factor, ker_quotient_lift, map_eq_iff_sup_ker_eq_of_surjective I^.quotient.mk quotient.mk_surjective, ← sup_assoc] /-- The ring homomorphism `(R/I)/J' -> R/(I ⊔ J)` induced by `quot_left_to_quot_sup` where `J'` is the image of `J` in `R/I`-/ def quot_quot_to_quot_sup : (J.map (ideal.quotient.mk I)).quotient →+* (I ⊔ J).quotient := ideal.quotient.lift (ideal.map (ideal.quotient.mk I) J) (quot_left_to_quot_sup I J) (ker_quot_left_to_quot_sup I J).symm.le /-- The composite of the maps `R → (R/I)` and `(R/I) → (R/I)/J'` -/ def quot_quot_mk : R →+* (J.map I^.quotient.mk).quotient := ((J.map I^.quotient.mk)^.quotient.mk).comp I^.quotient.mk /-- The kernel of `quot_quot_mk` -/ lemma ker_quot_quot_mk : (quot_quot_mk I J).ker = I ⊔ J := by rw [ring_hom.ker_eq_comap_bot, quot_quot_mk, ← comap_comap, ← ring_hom.ker, mk_ker, comap_map_of_surjective (ideal.quotient.mk I) (quotient.mk_surjective), ← ring_hom.ker, mk_ker, sup_comm] /-- The ring homomorphism `R/(I ⊔ J) → (R/I)/J' `induced by `quot_quot_mk` -/ def lift_sup_quot_quot_mk (I J : ideal R) : (I ⊔ J).quotient →+* (J.map (ideal.quotient.mk I)).quotient := ideal.quotient.lift (I ⊔ J) (quot_quot_mk I J) (ker_quot_quot_mk I J).symm.le /-- `quot_quot_to_quot_add` and `lift_sup_double_qot_mk` are inverse isomorphisms -/ def quot_quot_equiv_quot_sup : (J.map (ideal.quotient.mk I)).quotient ≃+* (I ⊔ J).quotient := ring_equiv.of_hom_inv (quot_quot_to_quot_sup I J) (lift_sup_quot_quot_mk I J) (by { ext z, refl }) (by { ext z, refl }) @[simp] lemma quot_quot_equiv_quot_sup_quot_quot_mk (x : R) : quot_quot_equiv_quot_sup I J (quot_quot_mk I J x) = ideal.quotient.mk (I ⊔ J) x := rfl @[simp] lemma quot_quot_equiv_quot_sup_symm_quot_quot_mk (x : R) : (quot_quot_equiv_quot_sup I J).symm (ideal.quotient.mk (I ⊔ J) x) = quot_quot_mk I J x := rfl /-- The obvious isomorphism `(R/I)/J' → (R/J)/I' ` -/ def quot_quot_equiv_comm : (J.map I^.quotient.mk).quotient ≃+* (I.map J^.quotient.mk).quotient := ((quot_quot_equiv_quot_sup I J).trans (quot_equiv_of_eq sup_comm)).trans (quot_quot_equiv_quot_sup J I).symm @[simp] lemma quot_quot_equiv_comm_quot_quot_mk (x : R) : quot_quot_equiv_comm I J (quot_quot_mk I J x) = quot_quot_mk J I x := rfl @[simp] lemma quot_quot_equiv_comm_comp_quot_quot_mk : ring_hom.comp ↑(quot_quot_equiv_comm I J) (quot_quot_mk I J) = quot_quot_mk J I := ring_hom.ext $ quot_quot_equiv_comm_quot_quot_mk I J @[simp] lemma quot_quot_equiv_comm_symm : (quot_quot_equiv_comm I J).symm = quot_quot_equiv_comm J I := rfl end double_quot
8c215116f3412f772fa1468a1570bd2da05139cc
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebraic_topology/simplicial_object.lean
560ed2b03e80b29a97a1efba8bb114c2e9ac8af5
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,220
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import algebraic_topology.simplex_category import category_theory.category.ulift import category_theory.limits.functor_category import category_theory.opposites import category_theory.adjunction.limits /-! # Simplicial objects in a category. A simplicial object in a category `C` is a `C`-valued presheaf on `simplex_category`. Use the notation `X _[n]` in the `simplicial` locale to obtain the `n`-th term of a simplicial object `X`, where `n` is a natural number. -/ open opposite open category_theory open category_theory.limits universes v u namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of simplicial objects valued in a category `C`. This is the category of contravariant functors from `simplex_category` to `C`. -/ @[derive category, nolint has_inhabited_instance] def simplicial_object := simplex_category.{v}ᵒᵖ ⥤ C namespace simplicial_object localized "notation X `_[`:1000 n `]` := (X : category_theory.simplicial_object _).obj (opposite.op (simplex_category.mk n))" in simplicial instance {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_limits C] : has_limits (simplicial_object C) := ⟨infer_instance⟩ instance {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_colimits C] : has_colimits (simplicial_object C) := ⟨infer_instance⟩ variables {C} (X : simplicial_object C) /-- Face maps for a simplicial object. -/ def δ {n} (i : fin (n+2)) : X _[n+1] ⟶ X _[n] := X.map (simplex_category.δ i).op /-- Degeneracy maps for a simplicial object. -/ def σ {n} (i : fin (n+1)) : X _[n] ⟶ X _[n+1] := X.map (simplex_category.σ i).op /-- Isomorphisms from identities in ℕ. -/ def eq_to_iso {n m : ℕ} (h : n = m) : X _[n] ≅ X _[m] := X.map_iso (eq_to_iso (by rw h)) @[simp] lemma eq_to_iso_refl {n : ℕ} (h : n = n) : X.eq_to_iso h = iso.refl _ := by { ext, simp [eq_to_iso], } /-- The generic case of the first simplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : X.δ j.succ ≫ X.δ i = X.δ i.cast_succ ≫ X.δ j := by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ H] } /-- The special case of the first simplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : X.δ i.cast_succ ≫ X.δ i = X.δ i.succ ≫ X.δ i := by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ_self] } /-- The second simplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : X.σ j.succ ≫ X.δ i.cast_succ = X.δ i ≫ X.σ j := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_le H] } /-- The first part of the third simplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : X.σ i ≫ X.δ i.cast_succ = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_self, op_id, X.map_id], end /-- The second part of the third simplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : X.σ i ≫ X.δ i.succ = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_succ, op_id, X.map_id], end /-- The fourth simplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : X.σ j.cast_succ ≫ X.δ i.succ = X.δ i ≫ X.σ j := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_gt H] } /-- The fifth simplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : X.σ j ≫ X.σ i.cast_succ = X.σ i ≫ X.σ j.succ := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.σ_comp_σ H] } variable (C) /-- Truncated simplicial objects. -/ @[derive category, nolint has_inhabited_instance] def truncated (n : ℕ) := (simplex_category.truncated.{v} n)ᵒᵖ ⥤ C variable {C} namespace truncated instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_limits C] : has_limits (simplicial_object.truncated C n) := ⟨infer_instance⟩ instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_colimits C] : has_colimits (simplicial_object.truncated C n) := ⟨infer_instance⟩ end truncated section skeleton /-- The skeleton functor from simplicial objects to truncated simplicial objects. -/ def sk (n : ℕ) : simplicial_object C ⥤ simplicial_object.truncated C n := (whiskering_left _ _ _).obj (simplex_category.truncated.inclusion).op end skeleton end simplicial_object end category_theory
76bfa7349ff56dfc3f9243248638820cbe215c3e
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/unification_hints1.lean
2ee01fab04c4de67839a4e8c25fcd346bab0a49d
[ "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
1,512
lean
-- open list nat namespace toy constants (A : Type) (f h : A → A) (x y z : A) attribute [irreducible] noncomputable definition g (x y : A) : A := f z #unify (g x y), (f z) @[unify] noncomputable definition toy_hint (x y : A) : unification_hint := { pattern := g x y ≟ f z, constraints := [] } #unify (g x y), (f z) print [unify] end toy namespace add constants (n : ℕ) attribute [irreducible] add #unify (n + 1), succ n @[unify] definition add_zero_hint (m n : ℕ) [has_add ℕ] [has_one ℕ] [has_zero ℕ] : unification_hint := { pattern := m + 1 ≟ succ n, constraints := [m ≟ n] } #unify (n + 1), (succ n) print [unify] end add namespace canonical inductive Canonical | mk : Π (carrier : Type*) (op : carrier → carrier), Canonical attribute [irreducible] definition Canonical.carrier (s : Canonical) : Type* := Canonical.rec_on s (λ c op, c) constants (A : Type) (f : A → A) (x : A) noncomputable definition A_canonical : Canonical := Canonical.mk A f #unify (Canonical.carrier A_canonical), A @[unify] noncomputable definition Canonical_hint (C : Canonical) : unification_hint := { pattern := C~>carrier ≟ A, constraints := [C ≟ A_canonical] } -- TODO(dhs): we mark carrier as irreducible and prove A_canonical explicitly to work around the fact that -- the default_type_context does not recognize the elaborator metavariables as metavariables, -- and so cannot perform the assignment. #unify (Canonical.carrier A_canonical), A print [unify] end canonical
9f6f077a488f169df058d2b91d42c1ca40e019ff
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/geometry/manifold/derivation_bundle.lean
b5843fffa74403d66ff4e2d96a8fbb75d4c00638
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,348
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.algebra.smooth_functions import ring_theory.derivation /-! # Derivation bundle In this file we define the derivations at a point of a manifold on the algebra of smooth fuctions. Moreover, we define the differential of a function in terms of derivations. The content of this file is not meant to be regarded as an alternative definition to the current tangent bundle but rather as a purely algebraic theory that provides a purely algebraic definition of the Lie algebra for a Lie group. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {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] (n : with_top ℕ) open_locale manifold -- the following two instances prevent poorly understood type class inference timeout problems instance smooth_functions_algebra : algebra 𝕜 C^∞⟮I, M; 𝕜⟯ := by apply_instance instance smooth_functions_tower : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯ := by apply_instance /-- Type synonym, introduced to put a different `has_scalar` action on `C^n⟮I, M; 𝕜⟯` which is defined as `f • r = f(x) * r`. -/ @[nolint unused_arguments] def pointed_smooth_map (x : M) := C^n⟮I, M; 𝕜⟯ localized "notation `C^` n `⟮` I `,` M `;` 𝕜 `⟯⟨` x `⟩` := pointed_smooth_map 𝕜 I M n x" in derivation variables {𝕜 M} namespace pointed_smooth_map instance {x : M} : has_coe_to_fun C^∞⟮I, M; 𝕜⟯⟨x⟩ (λ _, M → 𝕜) := times_cont_mdiff_map.has_coe_to_fun instance {x : M} : comm_ring C^∞⟮I, M; 𝕜⟯⟨x⟩ := smooth_map.comm_ring instance {x : M} : algebra 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ := smooth_map.algebra instance {x : M} : inhabited C^∞⟮I, M; 𝕜⟯⟨x⟩ := ⟨0⟩ instance {x : M} : algebra C^∞⟮I, M; 𝕜⟯⟨x⟩ C^∞⟮I, M; 𝕜⟯ := algebra.id C^∞⟮I, M; 𝕜⟯ instance {x : M} : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ C^∞⟮I, M; 𝕜⟯ := is_scalar_tower.right variable {I} /-- `smooth_map.eval_ring_hom` gives rise to an algebra structure of `C^∞⟮I, M; 𝕜⟯` on `𝕜`. -/ instance eval_algebra {x : M} : algebra C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 := (smooth_map.eval_ring_hom x : C^∞⟮I, M; 𝕜⟯⟨x⟩ →+* 𝕜).to_algebra /-- With the `eval_algebra` algebra structure evaluation is actually an algebra morphism. -/ def eval (x : M) : C^∞⟮I, M; 𝕜⟯ →ₐ[C^∞⟮I, M; 𝕜⟯⟨x⟩] 𝕜 := algebra.of_id C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 lemma smul_def (x : M) (f : C^∞⟮I, M; 𝕜⟯⟨x⟩) (k : 𝕜) : f • k = f x * k := rfl instance (x : M) : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 := { smul_assoc := λ k f h, by { simp only [smul_def, algebra.id.smul_eq_mul, smooth_map.coe_smul, pi.smul_apply, mul_assoc]} } end pointed_smooth_map open_locale derivation /-- The derivations at a point of a manifold. Some regard this as a possible definition of the tangent space -/ @[reducible] def point_derivation (x : M) := derivation 𝕜 (C^∞⟮I, M; 𝕜⟯⟨x⟩) 𝕜 section variables (I) {M} (X Y : derivation 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯) (f g : C^∞⟮I, M; 𝕜⟯) (r : 𝕜) /-- Evaluation at a point gives rise to a `C^∞⟮I, M; 𝕜⟯`-linear map between `C^∞⟮I, M; 𝕜⟯` and `𝕜`. -/ def smooth_function.eval_at (x : M) : C^∞⟮I, M; 𝕜⟯ →ₗ[C^∞⟮I, M; 𝕜⟯⟨x⟩] 𝕜 := (pointed_smooth_map.eval x).to_linear_map namespace derivation variable {I} /-- The evaluation at a point as a linear map. -/ def eval_at (x : M) : (derivation 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯) →ₗ[𝕜] point_derivation I x := (smooth_function.eval_at I x).comp_der lemma eval_at_apply (x : M) : eval_at x X f = (X f) x := rfl end derivation variables {I} {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'] /-- The heterogeneous differential as a linear map. Instead of taking a function as an argument this differential takes `h : f x = y`. It is particularly handy to deal with situations where the points on where it has to be evaluated are equal but not definitionally equal. -/ def hfdifferential {f : C^∞⟮I, M; I', M'⟯} {x : M} {y : M'} (h : f x = y) : point_derivation I x →ₗ[𝕜] point_derivation I' y := { to_fun := λ v, { to_linear_map := { to_fun := λ g, v (g.comp f), map_add' := λ g g', by rw [smooth_map.add_comp, derivation.map_add], map_smul' := λ k g, by simp only [smooth_map.smul_comp, derivation.map_smul, ring_hom.id_apply], }, leibniz' := λ g g', by simp only [derivation.leibniz, smooth_map.mul_comp, pointed_smooth_map.smul_def, times_cont_mdiff_map.comp_apply, h] }, map_smul' := λ k v, rfl, map_add' := λ v w, rfl } /-- The homogeneous differential as a linear map. -/ def fdifferential (f : C^∞⟮I, M; I', M'⟯) (x : M) : point_derivation I x →ₗ[𝕜] point_derivation I' (f x) := hfdifferential (rfl : f x = f x) /- Standard notation for the differential. The abbreviation is `MId`. -/ localized "notation `𝒅` := fdifferential" in manifold /- Standard notation for the differential. The abbreviation is `MId`. -/ localized "notation `𝒅ₕ` := hfdifferential" in manifold @[simp] lemma apply_fdifferential (f : C^∞⟮I, M; I', M'⟯) {x : M} (v : point_derivation I x) (g : C^∞⟮I', M'; 𝕜⟯) : 𝒅f x v g = v (g.comp f) := rfl @[simp] lemma apply_hfdifferential {f : C^∞⟮I, M; I', M'⟯} {x : M} {y : M'} (h : f x = y) (v : point_derivation I x) (g : C^∞⟮I', M'; 𝕜⟯) : 𝒅ₕh v g = 𝒅f x v g := rfl variables {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''] @[simp] lemma fdifferential_comp (g : C^∞⟮I', M'; I'', M''⟯) (f : C^∞⟮I, M; I', M'⟯) (x : M) : 𝒅(g.comp f) x = (𝒅g (f x)).comp (𝒅f x) := rfl end
72277466cd05b0098c650120d2a2c88e78141c75
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/metric_space/gluing.lean
b8a34dd235e2b96eb6882802beaac17a5b371747
[ "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
23,831
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Gluing metric spaces Authors: Sébastien Gouëzel -/ import topology.metric_space.isometry import topology.metric_space.premetric_space /-! # Metric space gluing Gluing two metric spaces along a common subset. Formally, we are given ``` Φ γ ---> α | |Ψ v β ``` where `hΦ : isometry Φ` and `hΨ : isometry Ψ`. We want to complete the square by a space `glue_space hΦ hΨ` and two isometries `to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute. We start by defining a predistance on the disjoint union `α ⊕ β`, for which points `Φ p` and `Ψ p` are at distance 0. The (quotient) metric space associated to this predistance is the desired space. This is an instance of a more general construction, where `Φ` and `Ψ` do not have to be isometries, but the distances in the image almost coincide, up to `2ε` say. Then one can almost glue the two spaces so that the images of a point under `Φ` and `Ψ` are ε-close. If `ε > 0`, this yields a metric space structure on `α ⊕ β`, without the need to take a quotient. In particular, when `α` and `β` are inhabited, this gives a natural metric space structure on `α ⊕ β`, where the basepoints are at distance 1, say, and the distances between other points are obtained by going through the two basepoints. We also define the inductive limit of metric spaces. Given ``` f 0 f 1 f 2 f 3 X 0 -----> X 1 -----> X 2 -----> X 3 -----> ... ``` where the `X n` are metric spaces and `f n` isometric embeddings, we define the inductive limit of the `X n`, also known as the increasing union of the `X n` in this context, if we identify `X n` and `X (n+1)` through `f n`. This is a metric space in which all `X n` embed isometrically and in a way compatible with `f n`. -/ noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open function set premetric namespace metric section approx_gluing variables [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} {ε : ℝ} open sum (inl inr) /-- Define a predistance on α ⊕ β, for which Φ p and Ψ p are at distance ε -/ def glue_dist (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) : α ⊕ β → α ⊕ β → ℝ | (inl x) (inl y) := dist x y | (inr x) (inr y) := dist x y | (inl x) (inr y) := infi (λp, dist x (Φ p) + dist y (Ψ p)) + ε | (inr x) (inl y) := infi (λp, dist y (Φ p) + dist x (Ψ p)) + ε private lemma glue_dist_self (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) : ∀x, glue_dist Φ Ψ ε x x = 0 | (inl x) := dist_self _ | (inr x) := dist_self _ lemma glue_dist_glued_points [nonempty γ] (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (p : γ) : glue_dist Φ Ψ ε (inl (Φ p)) (inr (Ψ p)) = ε := begin have : infi (λq, dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q)) = 0, { have A : ∀q, 0 ≤ dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q) := λq, by rw ← add_zero (0 : ℝ); exact add_le_add dist_nonneg dist_nonneg, refine le_antisymm _ (le_cinfi A), have : 0 = dist (Φ p) (Φ p) + dist (Ψ p) (Ψ p), by simp, rw this, exact cinfi_le ⟨0, forall_range_iff.2 A⟩ p }, rw [glue_dist, this, zero_add] end private lemma glue_dist_comm (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) : ∀x y, glue_dist Φ Ψ ε x y = glue_dist Φ Ψ ε y x | (inl x) (inl y) := dist_comm _ _ | (inr x) (inr y) := dist_comm _ _ | (inl x) (inr y) := rfl | (inr x) (inl y) := rfl variable [nonempty γ] private lemma glue_dist_triangle (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (H : ∀p q, abs (dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)) ≤ 2 * ε) : ∀x y z, glue_dist Φ Ψ ε x z ≤ glue_dist Φ Ψ ε x y + glue_dist Φ Ψ ε y z | (inl x) (inl y) (inl z) := dist_triangle _ _ _ | (inr x) (inr y) (inr z) := dist_triangle _ _ _ | (inr x) (inl y) (inl z) := begin have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : infi (λp, dist z (Φ p) + dist x (Ψ p)) ≤ infi (λp, dist y (Φ p) + dist x (Ψ p)) + dist y z, { have : infi (λp, dist y (Φ p) + dist x (Ψ p)) + dist y z = infi ((λt, t + dist y z) ∘ (λp, dist y (Φ p) + dist x (Ψ p))), { refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_le_cinfi (B _ _) (λp, _), calc dist z (Φ p) + dist x (Ψ p) ≤ (dist y z + dist y (Φ p)) + dist x (Ψ p) : add_le_add (dist_triangle_left _ _ _) (le_refl _) ... = dist y (Φ p) + dist x (Ψ p) + dist y z : by ring }, linarith end | (inr x) (inr y) (inl z) := begin have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : infi (λp, dist z (Φ p) + dist x (Ψ p)) ≤ dist x y + infi (λp, dist z (Φ p) + dist y (Ψ p)), { have : dist x y + infi (λp, dist z (Φ p) + dist y (Ψ p)) = infi ((λt, dist x y + t) ∘ (λp, dist z (Φ p) + dist y (Ψ p))), { refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_le_cinfi (B _ _) (λp, _), calc dist z (Φ p) + dist x (Ψ p) ≤ dist z (Φ p) + (dist x y + dist y (Ψ p)) : add_le_add (le_refl _) (dist_triangle _ _ _) ... = dist x y + (dist z (Φ p) + dist y (Ψ p)) : by ring }, linarith end | (inl x) (inl y) (inr z) := begin have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : infi (λp, dist x (Φ p) + dist z (Ψ p)) ≤ dist x y + infi (λp, dist y (Φ p) + dist z (Ψ p)), { have : dist x y + infi (λp, dist y (Φ p) + dist z (Ψ p)) = infi ((λt, dist x y + t) ∘ (λp, dist y (Φ p) + dist z (Ψ p))), { refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_le_cinfi (B _ _) (λp, _), calc dist x (Φ p) + dist z (Ψ p) ≤ (dist x y + dist y (Φ p)) + dist z (Ψ p) : add_le_add (dist_triangle _ _ _) (le_refl _) ... = dist x y + (dist y (Φ p) + dist z (Ψ p)) : by ring }, linarith end | (inl x) (inr y) (inr z) := begin have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : infi (λp, dist x (Φ p) + dist z (Ψ p)) ≤ infi (λp, dist x (Φ p) + dist y (Ψ p)) + dist y z, { have : infi (λp, dist x (Φ p) + dist y (Ψ p)) + dist y z = infi ((λt, t + dist y z) ∘ (λp, dist x (Φ p) + dist y (Ψ p))), { refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_le_cinfi (B _ _) (λp, _), calc dist x (Φ p) + dist z (Ψ p) ≤ dist x (Φ p) + (dist y z + dist y (Ψ p)) : add_le_add (le_refl _) (dist_triangle_left _ _ _) ... = dist x (Φ p) + dist y (Ψ p) + dist y z : by ring }, linarith end | (inl x) (inr y) (inl z) := real.le_of_forall_epsilon_le $ λδ δpos, begin have : ∃a ∈ range (λp, dist x (Φ p) + dist y (Ψ p)), a < infi (λp, dist x (Φ p) + dist y (Ψ p)) + δ/2 := exists_lt_of_cInf_lt (range_nonempty _) (by rw [infi]; linarith), rcases this with ⟨a, arange, ha⟩, rcases mem_range.1 arange with ⟨p, pa⟩, rw ← pa at ha, have : ∃b ∈ range (λp, dist z (Φ p) + dist y (Ψ p)), b < infi (λp, dist z (Φ p) + dist y (Ψ p)) + δ/2 := exists_lt_of_cInf_lt (range_nonempty _) (by rw [infi]; linarith), rcases this with ⟨b, brange, hb⟩, rcases mem_range.1 brange with ⟨q, qb⟩, rw ← qb at hb, have : dist (Φ p) (Φ q) ≤ dist (Ψ p) (Ψ q) + 2 * ε, { have := le_trans (le_abs_self _) (H p q), by linarith }, calc dist x z ≤ dist x (Φ p) + dist (Φ p) (Φ q) + dist (Φ q) z : dist_triangle4 _ _ _ _ ... ≤ dist x (Φ p) + dist (Ψ p) (Ψ q) + dist z (Φ q) + 2 * ε : by rw [dist_comm z]; linarith ... ≤ dist x (Φ p) + (dist y (Ψ p) + dist y (Ψ q)) + dist z (Φ q) + 2 * ε : add_le_add (add_le_add (add_le_add (le_refl _) (dist_triangle_left _ _ _)) (le_refl _)) (le_refl _) ... ≤ (infi (λp, dist x (Φ p) + dist y (Ψ p)) + ε) + (infi (λp, dist z (Φ p) + dist y (Ψ p)) + ε) + δ : by linarith end | (inr x) (inl y) (inr z) := real.le_of_forall_epsilon_le $ λδ δpos, begin have : ∃a ∈ range (λp, dist y (Φ p) + dist x (Ψ p)), a < infi (λp, dist y (Φ p) + dist x (Ψ p)) + δ/2 := exists_lt_of_cInf_lt (range_nonempty _) (by rw [infi]; linarith), rcases this with ⟨a, arange, ha⟩, rcases mem_range.1 arange with ⟨p, pa⟩, rw ← pa at ha, have : ∃b ∈ range (λp, dist y (Φ p) + dist z (Ψ p)), b < infi (λp, dist y (Φ p) + dist z (Ψ p)) + δ/2 := exists_lt_of_cInf_lt (range_nonempty _) (by rw [infi]; linarith), rcases this with ⟨b, brange, hb⟩, rcases mem_range.1 brange with ⟨q, qb⟩, rw ← qb at hb, have : dist (Ψ p) (Ψ q) ≤ dist (Φ p) (Φ q) + 2 * ε, { have := le_trans (neg_le_abs_self _) (H p q), by linarith }, calc dist x z ≤ dist x (Ψ p) + dist (Ψ p) (Ψ q) + dist (Ψ q) z : dist_triangle4 _ _ _ _ ... ≤ dist x (Ψ p) + dist (Φ p) (Φ q) + dist z (Ψ q) + 2 * ε : by rw [dist_comm z]; linarith ... ≤ dist x (Ψ p) + (dist y (Φ p) + dist y (Φ q)) + dist z (Ψ q) + 2 * ε : add_le_add (add_le_add (add_le_add (le_refl _) (dist_triangle_left _ _ _)) (le_refl _)) (le_refl _) ... ≤ (infi (λp, dist y (Φ p) + dist x (Ψ p)) + ε) + (infi (λp, dist y (Φ p) + dist z (Ψ p)) + ε) + δ : by linarith end private lemma glue_eq_of_dist_eq_zero (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (ε0 : 0 < ε) : ∀p q : α ⊕ β, glue_dist Φ Ψ ε p q = 0 → p = q | (inl x) (inl y) h := by rw eq_of_dist_eq_zero h | (inl x) (inr y) h := begin have : 0 ≤ infi (λp, dist x (Φ p) + dist y (Ψ p)) := le_cinfi (λp, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)), have : 0 + ε ≤ glue_dist Φ Ψ ε (inl x) (inr y) := add_le_add this (le_refl ε), exfalso, linarith end | (inr x) (inl y) h := begin have : 0 ≤ infi (λp, dist y (Φ p) + dist x (Ψ p)) := le_cinfi (λp, by simpa [add_comm] using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)), have : 0 + ε ≤ glue_dist Φ Ψ ε (inr x) (inl y) := add_le_add this (le_refl ε), exfalso, linarith end | (inr x) (inr y) h := by rw eq_of_dist_eq_zero h /-- Given two maps Φ and Ψ intro metric spaces α and β such that the distances between Φ p and Φ q, and between Ψ p and Ψ q, coincide up to 2 ε where ε > 0, one can almost glue the two spaces α and β along the images of Φ and Ψ, so that Φ p and Ψ p are at distance ε. -/ def glue_metric_approx (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (ε0 : 0 < ε) (H : ∀p q, abs (dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)) ≤ 2 * ε) : metric_space (α ⊕ β) := { dist := glue_dist Φ Ψ ε, dist_self := glue_dist_self Φ Ψ ε, dist_comm := glue_dist_comm Φ Ψ ε, dist_triangle := glue_dist_triangle Φ Ψ ε H, eq_of_dist_eq_zero := glue_eq_of_dist_eq_zero Φ Ψ ε ε0 } end approx_gluing section sum /- A particular case of the previous construction is when one uses basepoints in α and β and one glues only along the basepoints, putting them at distance 1. We give a direct definition of the distance, without infi, as it is easier to use in applications, and show that it is equal to the gluing distance defined above to take advantage of the lemmas we have already proved. -/ variables [metric_space α] [metric_space β] [inhabited α] [inhabited β] open sum (inl inr) /- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible with each factor. If the two spaces are bounded, one can say for instance that each point in the first is at distance `diam α + diam β + 1` of each point in the second. Instead, we choose a construction that works for unbounded spaces, but requires basepoints. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ def sum.dist : α ⊕ β → α ⊕ β → ℝ | (inl a) (inl a') := dist a a' | (inr b) (inr b') := dist b b' | (inl a) (inr b) := dist a (default α) + 1 + dist (default β) b | (inr b) (inl a) := dist b (default β) + 1 + dist (default α) a lemma sum.dist_eq_glue_dist {p q : α ⊕ β} : sum.dist p q = glue_dist (λ_ : unit, default α) (λ_ : unit, default β) 1 p q := by cases p; cases q; refl <|> simp [sum.dist, glue_dist, dist_comm, add_comm, add_left_comm] private lemma sum.dist_comm (x y : α ⊕ β) : sum.dist x y = sum.dist y x := by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm] lemma sum.one_dist_le {x : α} {y : β} : 1 ≤ sum.dist (inl x) (inr y) := le_trans (le_add_of_nonneg_right dist_nonneg) $ add_le_add_right (le_add_of_nonneg_left dist_nonneg) _ lemma sum.one_dist_le' {x : α} {y : β} : 1 ≤ sum.dist (inr y) (inl x) := by rw sum.dist_comm; exact sum.one_dist_le private lemma sum.mem_uniformity (s : set ((α ⊕ β) × (α ⊕ β))) : s ∈ (@uniformity (α ⊕ β) _).sets ↔ ∃ ε > 0, ∀ a b, sum.dist a b < ε → (a, b) ∈ s := begin split, { rintro ⟨hsα, hsβ⟩, rcases mem_uniformity_dist.1 hsα with ⟨εα, εα0, hα⟩, rcases mem_uniformity_dist.1 hsβ with ⟨εβ, εβ0, hβ⟩, refine ⟨min (min εα εβ) 1, lt_min (lt_min εα0 εβ0) zero_lt_one, _⟩, rintro (a|a) (b|b) h, { exact hα (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) }, { cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le }, { cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' }, { exact hβ (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } }, { rintro ⟨ε, ε0, H⟩, split; rw [filter.mem_map, mem_uniformity_dist]; exact ⟨ε, ε0, λ x y h, H _ _ (by exact h)⟩ } end /-- The distance on the disjoint union indeed defines a metric space. All the distance properties follow from our choice of the distance. The harder work is to show that the uniform structure defined by the distance coincides with the disjoint union uniform structure. -/ def metric_space_sum : metric_space (α ⊕ β) := { dist := sum.dist, dist_self := λx, by cases x; simp only [sum.dist, dist_self], dist_comm := sum.dist_comm, dist_triangle := λp q r, by simp only [dist, sum.dist_eq_glue_dist]; exact glue_dist_triangle _ _ _ (by simp; norm_num) _ _ _, eq_of_dist_eq_zero := λp q, by simp only [dist, sum.dist_eq_glue_dist]; exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _, to_uniform_space := sum.uniform_space, uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity } local attribute [instance] metric_space_sum lemma sum.dist_eq {x y : α ⊕ β} : dist x y = sum.dist x y := rfl /-- The left injection of a space in a disjoint union in an isometry -/ lemma isometry_on_inl : isometry (sum.inl : α → (α ⊕ β)) := isometry_emetric_iff_metric.2 $ λx y, rfl /-- The right injection of a space in a disjoint union in an isometry -/ lemma isometry_on_inr : isometry (sum.inr : β → (α ⊕ β)) := isometry_emetric_iff_metric.2 $ λx y, rfl end sum section gluing /- Exact gluing of two metric spaces along isometric subsets. -/ variables [nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} {ε : ℝ} open sum (inl inr) local attribute [instance] premetric.dist_setoid def glue_premetric (hΦ : isometry Φ) (hΨ : isometry Ψ) : premetric_space (α ⊕ β) := { dist := glue_dist Φ Ψ 0, dist_self := glue_dist_self Φ Ψ 0, dist_comm := glue_dist_comm Φ Ψ 0, dist_triangle := glue_dist_triangle Φ Ψ 0 $ λp q, by rw [hΦ.dist_eq, hΨ.dist_eq]; simp } def glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : Type* := @metric_quot _ (glue_premetric hΦ hΨ) instance metric_space_glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : metric_space (glue_space hΦ hΨ) := @premetric.metric_space_quot _ (glue_premetric hΦ hΨ) def to_glue_l (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : α) : glue_space hΦ hΨ := by letI : premetric_space (α ⊕ β) := glue_premetric hΦ hΨ; exact ⟦inl x⟧ def to_glue_r (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : β) : glue_space hΦ hΨ := by letI : premetric_space (α ⊕ β) := glue_premetric hΦ hΨ; exact ⟦inr y⟧ instance inhabited_left (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited α] : inhabited (glue_space hΦ hΨ) := ⟨to_glue_l _ _ (default _)⟩ instance inhabited_right (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited β] : inhabited (glue_space hΦ hΨ) := ⟨to_glue_r _ _ (default _)⟩ lemma to_glue_commute (hΦ : isometry Φ) (hΨ : isometry Ψ) : (to_glue_l hΦ hΨ) ∘ Φ = (to_glue_r hΦ hΨ) ∘ Ψ := begin letI : premetric_space (α ⊕ β) := glue_premetric hΦ hΨ, funext, simp only [comp, to_glue_l, to_glue_r, quotient.eq], exact glue_dist_glued_points Φ Ψ 0 x end lemma to_glue_l_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) := isometry_emetric_iff_metric.2 $ λ_ _, rfl lemma to_glue_r_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) := isometry_emetric_iff_metric.2 $ λ_ _, rfl end gluing --section section inductive_limit /- In this section, we define the inductive limit of f 0 f 1 f 2 f 3 X 0 -----> X 1 -----> X 2 -----> X 3 -----> ... where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric space structure on Σn, X n, where the predistance dist x y is obtained by pushing x and y in a common X k using composition by the f n, and taking the distance there. This does not depend on the choice of k as the f n are isometries. The metric space associated to this premetric space is the desired inductive limit.-/ open nat variables {X : ℕ → Type u} [∀n, metric_space (X n)] {f : Πn, X n → X (n+1)} /-- Predistance on the disjoint union Σn, X n. -/ def inductive_limit_dist (f : Πn, X n → X (n+1)) (x y : Σn, X n) : ℝ := dist (le_rec_on (le_max_left x.1 y.1) f x.2 : X (max x.1 y.1)) (le_rec_on (le_max_right x.1 y.1) f y.2 : X (max x.1 y.1)) /-- The predistance on the disjoint union Σn, X n can be computed in any X k for large enough k.-/ lemma inductive_limit_dist_eq_dist (I : ∀n, isometry (f n)) (x y : Σn, X n) (m : ℕ) : ∀hx : x.1 ≤ m, ∀hy : y.1 ≤ m, inductive_limit_dist f x y = dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) := begin induction m with m hm, { assume hx hy, have A : max x.1 y.1 = 0, { rw [le_zero_iff_eq.1 hx, le_zero_iff_eq.1 hy], simp }, unfold inductive_limit_dist, congr; simp only [A] }, { assume hx hy, by_cases h : max x.1 y.1 = m.succ, { unfold inductive_limit_dist, congr; simp only [h] }, { have : max x.1 y.1 ≤ succ m := by simp [hx, hy], have : max x.1 y.1 ≤ m := by simpa [h] using of_le_succ this, have xm : x.1 ≤ m := le_trans (le_max_left _ _) this, have ym : y.1 ≤ m := le_trans (le_max_right _ _) this, rw [le_rec_on_succ xm, le_rec_on_succ ym, (I m).dist_eq], exact hm xm ym }} end /-- Premetric space structure on Σn, X n.-/ def inductive_premetric (I : ∀n, isometry (f n)) : premetric_space (Σn, X n) := { dist := inductive_limit_dist f, dist_self := λx, by simp [dist, inductive_limit_dist], dist_comm := λx y, begin let m := max x.1 y.1, have hx : x.1 ≤ m := le_max_left _ _, have hy : y.1 ≤ m := le_max_right _ _, unfold dist, rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y x m hy hx, dist_comm] end, dist_triangle := λx y z, begin let m := max (max x.1 y.1) z.1, have hx : x.1 ≤ m := le_trans (le_max_left _ _) (le_max_left _ _), have hy : y.1 ≤ m := le_trans (le_max_right _ _) (le_max_left _ _), have hz : z.1 ≤ m := le_max_right _ _, calc inductive_limit_dist f x z = dist (le_rec_on hx f x.2 : X m) (le_rec_on hz f z.2 : X m) : inductive_limit_dist_eq_dist I x z m hx hz ... ≤ dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) + dist (le_rec_on hy f y.2 : X m) (le_rec_on hz f z.2 : X m) : dist_triangle _ _ _ ... = inductive_limit_dist f x y + inductive_limit_dist f y z : by rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y z m hy hz] end } local attribute [instance] inductive_premetric premetric.dist_setoid /-- The type giving the inductive limit in a metric space context. -/ def inductive_limit (I : ∀n, isometry (f n)) : Type* := @metric_quot _ (inductive_premetric I) /-- Metric space structure on the inductive limit. -/ instance metric_space_inductive_limit (I : ∀n, isometry (f n)) : metric_space (inductive_limit I) := @premetric.metric_space_quot _ (inductive_premetric I) /-- Mapping each `X n` to the inductive limit. -/ def to_inductive_limit (I : ∀n, isometry (f n)) (n : ℕ) (x : X n) : metric.inductive_limit I := by letI : premetric_space (Σn, X n) := inductive_premetric I; exact ⟦sigma.mk n x⟧ instance (I : ∀ n, isometry (f n)) [inhabited (X 0)] : inhabited (inductive_limit I) := ⟨to_inductive_limit _ 0 (default _)⟩ /-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/ lemma to_inductive_limit_isometry (I : ∀n, isometry (f n)) (n : ℕ) : isometry (to_inductive_limit I n) := isometry_emetric_iff_metric.2 $ λx y, begin change inductive_limit_dist f ⟨n, x⟩ ⟨n, y⟩ = dist x y, rw [inductive_limit_dist_eq_dist I ⟨n, x⟩ ⟨n, y⟩ n (le_refl n) (le_refl n), le_rec_on_self, le_rec_on_self] end /-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/ lemma to_inductive_limit_commute (I : ∀n, isometry (f n)) (n : ℕ) : (to_inductive_limit I n.succ) ∘ (f n) = to_inductive_limit I n := begin funext, simp only [comp, to_inductive_limit, quotient.eq], show inductive_limit_dist f ⟨n.succ, f n x⟩ ⟨n, x⟩ = 0, { rw [inductive_limit_dist_eq_dist I ⟨n.succ, f n x⟩ ⟨n, x⟩ n.succ, le_rec_on_self, le_rec_on_succ, le_rec_on_self, dist_self], exact le_refl _, exact le_refl _, exact le_succ _ } end end inductive_limit --section end metric --namespace
b55503bcea2842c6dd754a56dbb1f1091a113964
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/category/CommRing/colimits.lean
f4a3b8d687c1ffe478757ff7924c529a1a072cfd
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
12,908
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.CommRing.basic import category_theory.limits.has_limits import category_theory.limits.concrete_category /-! # The category of commutative rings has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `comm_ring` and `ring_hom`. -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. /- `#print comm_ring` says: structure comm_ring : Type u → Type u fields: comm_ring.zero : Π (α : Type u) [c : comm_ring α], α comm_ring.one : Π (α : Type u) [c : comm_ring α], α comm_ring.neg : Π {α : Type u} [c : comm_ring α], α → α comm_ring.add : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.mul : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.zero_add : ∀ {α : Type u} [c : comm_ring α] (a : α), 0 + a = a comm_ring.add_zero : ∀ {α : Type u} [c : comm_ring α] (a : α), a + 0 = a comm_ring.one_mul : ∀ {α : Type u} [c : comm_ring α] (a : α), 1 * a = a comm_ring.mul_one : ∀ {α : Type u} [c : comm_ring α] (a : α), a * 1 = a comm_ring.add_left_neg : ∀ {α : Type u} [c : comm_ring α] (a : α), -a + a = 0 comm_ring.add_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a + b = b + a comm_ring.mul_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a * b = b * a comm_ring.add_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a + b + c_1 = a + (b + c_1) comm_ring.mul_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) comm_ring.left_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * (b + c_1) = a * b + a * c_1 comm_ring.right_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), (a + b) * c_1 = a * c_1 + b * c_1 -/ namespace CommRing.colimits /-! We build the colimit of a diagram in `CommRing` by constructing the free commutative ring on the disjoint union of all the commutative rings in the diagram, then taking the quotient by the commutative ring laws within each commutative ring, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ CommRing.{v}) /-- An inductive type representing all commutative ring expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | one : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the commutative ring laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | one : Π (j), relation (of j 1) one | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | mul_comm : Π (x y), relation (mul x y) (mul y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | left_distrib : Π (x y z), relation (mul x (add y z)) (add (mul x y) (mul x z)) | right_distrib : Π (x y z), relation (mul (add x y) z) (add (mul x z) (mul y z)) /-- The setoid corresponding to commutative expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `CommRing`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance : comm_ring (colimit_type F) := { zero := begin exact quot.mk _ zero end, one := begin exact quot.mk _ one end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, mul_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.mul_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, left_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.left_distrib, refl, refl, refl, end, right_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.right_distrib, refl, refl, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled commutative ring giving the colimit of a diagram. -/ def colimit : CommRing := CommRing.of (colimit_type F) /-- The function from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The ring homomorphism from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := by apply quot.sound; apply relation.one, map_mul' := by intros; apply quot.sound; apply relation.mul, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit commutative ring. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. /-- The function from the free commutative ring on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | one := 1 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit commutative ring to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- one { simp, }, -- neg { simp, }, -- add { simp, }, -- mul { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- mul_comm { rw mul_comm, }, -- add_assoc { rw add_assoc, }, -- mul_assoc { rw mul_assoc, }, -- left_distrib { rw left_distrib, }, -- right_distrib { rw right_distrib, } } end /-- The ring homomorphism from the colimit commutative ring to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp, }, { simp, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_CommRing : has_colimits CommRing := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end CommRing.colimits
448470ef78e563974ce792c2f3cbabe56b5a4ac5
80746c6dba6a866de5431094bf9f8f841b043d77
/src/category_theory/yoneda.lean
e3e94e482c519905f317a537458bbe7036ea62e0
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
6,505
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison /- The Yoneda embedding, as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`, along with an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/ import category_theory.natural_transformation import category_theory.opposites import category_theory.types import category_theory.fully_faithful import category_theory.natural_isomorphism namespace category_theory universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop Y ⟶ X, map := λ Y Y' f g, f.unop ≫ g, map_comp' := begin intros X_1 Y Z f g, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X_1, ext1, dsimp at *, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_comp' := begin intros X_1 Y Z f g, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X_1, ext1, dsimp at *, erw [category.comp_id] end }, map := λ X X' f, { app := λ Y g, f.unop ≫ g }, map_comp' := begin intros X Y Z f g, ext1, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X, ext1, ext1, dsimp at *, erw [category.id_comp] end } namespace yoneda @[simp] lemma obj_obj (X : C) (Y : Cᵒᵖ) : (yoneda.obj X).obj Y = (unop Y ⟶ X) := rfl @[simp] lemma obj_map (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') : (yoneda.obj X).map f = λ g, f.unop ≫ g := rfl @[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : Cᵒᵖ) : (yoneda.map f).app Y = λ g, g ≫ f := rfl lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) : ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) := begin erw [functor_to_types.naturality], refl end instance yoneda_fully_faithful : fully_faithful (@yoneda C _) := { preimage := λ X Y f, (f.app (op X)) (𝟙 X), injectivity' := λ X Y f g p, begin injection p with h, convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp, end } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ yoneda _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁) end yoneda namespace coyoneda @[simp] lemma obj_obj (X : Cᵒᵖ) (Y : C) : (coyoneda.obj X).obj Y = (unop X ⟶ Y) := rfl @[simp] lemma obj_map {X' X : C} (f : X' ⟶ X) (Y : Cᵒᵖ) : (coyoneda.obj Y).map f = λ g, g ≫ f := rfl @[simp] lemma map_app (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') : (coyoneda.map f).app X = λ g, f.unop ≫ g := rfl end coyoneda class representable (F : Cᵒᵖ ⥤ Type v₁) := (X : C) (w : yoneda.obj X ≅ F) variables (C) open yoneda def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := functor.prod yoneda.op (functor.id (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))), naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp at *, simp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down, naturality' := begin intros X Y f, ext1, cases x, cases F, dsimp at *, erw [functor_to_types.map_comp] end }, naturality' := begin intros X Y f, ext1, ext1, ext1, cases x, cases f, cases Y, cases X, dsimp at *, erw [←functor_to_types.naturality, functor_to_types.map_comp] end }, hom_inv_id' := begin ext1, ext1, ext1, ext1, cases X, dsimp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id], refl, end, inv_hom_id' := begin ext1, ext1, ext1, cases x, cases X, dsimp at *, erw [functor_to_types.map_id] end }. variables {C} @[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟹ F) ≅ ulift.{u₁} (F.obj (op X)) := nat_iso.app (yoneda_lemma C) (op X, F) omit 𝒞 @[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟹ F) ≅ F.obj (op X) := yoneda_sections X F ≪≫ ulift_trivial _ end category_theory
ba20a54e77756d630a05516e373cf9ecd1a06fdd
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/stone_cech.lean
4f93bb4abf2a2ae31995881e1c832ea65146f348
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,075
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import topology.bases import topology.dense_embedding /-! # Stone-Čech compactification Construction of the Stone-Čech compactification using ultrafilters. Parts of the formalization are based on "Ultrafilters and Topology" by Marius Stekelenburg, particularly section 5. -/ noncomputable theory open filter set open_locale topological_space universes u v section ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `ultrafilter α`. -/ def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) := range $ λ s : set α, {u | s ∈ u} variables {α : Type u} instance : topological_space (ultrafilter α) := topological_space.generate_from (ultrafilter_basis α) lemma ultrafilter_basis_is_basis : topological_space.is_topological_basis (ultrafilter_basis α) := ⟨begin rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩, refine ⟨_, ⟨a ∩ b, rfl⟩, inter_mem ua ub, assume v hv, ⟨_, _⟩⟩; apply mem_of_superset hv; simp [inter_subset_right a b] end, eq_univ_of_univ_subset $ subset_sUnion_of_mem $ ⟨univ, eq_univ_of_forall (λ u, univ_mem)⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ lemma ultrafilter_is_open_basic (s : set α) : is_open {u : ultrafilter α | s ∈ u} := ultrafilter_basis_is_basis.is_open ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ lemma ultrafilter_is_closed_basic (s : set α) : is_closed {u : ultrafilter α | s ∈ u} := begin rw ← is_open_compl_iff, convert ultrafilter_is_open_basic sᶜ, ext u, exact ultrafilter.compl_mem_iff_not_mem.symm end /-- Every ultrafilter `u` on `ultrafilter α` converges to a unique point of `ultrafilter α`, namely `mjoin u`. -/ lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} : ↑u ≤ 𝓝 x ↔ x = mjoin u := begin rw [eq_comm, ← ultrafilter.coe_le_coe], change ↑u ≤ 𝓝 x ↔ ∀ s ∈ x, {v : ultrafilter α | s ∈ v} ∈ u, simp only [topological_space.nhds_generate_from, le_infi_iff, ultrafilter_basis, le_principal_iff, mem_set_of_eq], split, { intros h a ha, exact h _ ⟨ha, a, rfl⟩ }, { rintros h a ⟨xi, a, rfl⟩, exact h _ xi } end instance ultrafilter_compact : compact_space (ultrafilter α) := ⟨is_compact_iff_ultrafilter_le_nhds.mpr $ assume f _, ⟨mjoin f, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance ultrafilter.t2_space : t2_space (ultrafilter α) := t2_iff_ultrafilter.mpr $ assume x y f fx fy, have hx : x = mjoin f, from ultrafilter_converges_iff.mp fx, have hy : y = mjoin f, from ultrafilter_converges_iff.mp fy, hx.trans hy.symm instance : totally_disconnected_space (ultrafilter α) := begin rw totally_disconnected_space_iff_connected_component_singleton, intro A, simp only [set.eq_singleton_iff_unique_mem, mem_connected_component, true_and], intros B hB, rw ← ultrafilter.coe_le_coe, intros s hs, rw [connected_component_eq_Inter_clopen, set.mem_Inter] at hB, let Z := { F : ultrafilter α | s ∈ F }, have hZ : is_clopen Z := ⟨ultrafilter_is_open_basic s, ultrafilter_is_closed_basic s⟩, exact hB ⟨Z, hZ, hs⟩, end lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (𝓝 b) ≤ b := begin rw topological_space.nhds_generate_from, simp only [comap_infi, comap_principal], intros s hs, rw ←le_principal_iff, refine infi_le_of_le {u | s ∈ u} _, refine infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _, exact principal_mono.2 (λ a, id) end section embedding lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) := begin intros x y h, have : {x} ∈ (pure x : ultrafilter α) := singleton_mem_pure, rw h at this, exact (mem_singleton_iff.mp (mem_pure.mp this)).symm end open topological_space /-- The range of `pure : α → ultrafilter α` is dense in `ultrafilter α`. -/ lemma dense_range_pure : dense_range (pure : α → ultrafilter α) := λ x, mem_closure_iff_ultrafilter.mpr ⟨x.map pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩ /-- The map `pure : α → ultra_filter α` induces on `α` the discrete topology. -/ lemma induced_topology_pure : topological_space.induced (pure : α → ultrafilter α) ultrafilter.topological_space = ⊥ := begin apply eq_bot_of_singletons_open, intros x, use [{u : ultrafilter α | {x} ∈ u}, ultrafilter_is_open_basic _], simp, end /-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/ lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥; exact ⟨⟨induced_topology_pure.symm⟩, dense_range_pure⟩ -- The following refined version will never be used /-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/ lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥ ; exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure } end embedding section extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `ultrafilter α → γ`. We already know it must be unique because `α → ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `dense_embedding.continuous_extend`. -/ variables {γ : Type*} [topological_space γ] /-- The extension of a function `α → γ` to a function `ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def ultrafilter.extend (f : α → γ) : ultrafilter α → γ := by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f variables [t2_space γ] lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f := begin letI : topological_space α := ⊥, haveI : discrete_topology α := ⟨rfl⟩, exact funext (dense_inducing_pure.extend_eq continuous_of_discrete_topology) end variables [compact_space γ] lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) := have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap pure (𝓝 b)) (𝓝 c) := assume b, -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h⟩ := compact_univ.ultrafilter_le_nhds (b.map f) (by rw [le_principal_iff]; exact univ_mem) in ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩, begin letI : topological_space α := ⊥, haveI : normal_space γ := normal_of_compact_t2, exact dense_inducing_pure.continuous_extend this end /-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} : ultrafilter.extend f b = c ↔ ↑(b.map f) ≤ 𝓝 c := ⟨assume h, begin -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : ultrafilter (ultrafilter α) := b.map pure, have t : ↑b' ≤ 𝓝 b, from ultrafilter_converges_iff.mpr (bind_pure _).symm, rw ←h, have := (continuous_ultrafilter_extend f).tendsto b, refine le_trans _ (le_trans (map_mono t) this), change _ ≤ map (ultrafilter.extend f ∘ pure) ↑b, rw ultrafilter_extend_extends, exact le_rfl end, assume h, by letI : topological_space α := ⊥; exact dense_inducing_pure.extend_eq_of_tendsto (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end extension end ultrafilter section stone_cech /- Now, we start with a (not necessarily discrete) topological space α and we want to construct its Stone-Čech compactification. We can build it as a quotient of `ultrafilter α` by the relation which identifies two points if the extension of every continuous function α → γ to a compact Hausdorff space sends the two points to the same point of γ. -/ variables (α : Type u) [topological_space α] instance stone_cech_setoid : setoid (ultrafilter α) := { r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI ∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f), ultrafilter.extend f x = ultrafilter.extend f y, iseqv := ⟨assume x γ tγ h₁ h₂ f hf, rfl, assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm, assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ } /-- The Stone-Čech compactification of a topological space. -/ def stone_cech : Type u := quotient (stone_cech_setoid α) variables {α} instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance instance [inhabited α] : inhabited (stone_cech α) := by unfold stone_cech; apply_instance /-- The natural map from α to its Stone-Čech compactification. -/ def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧ /-- The image of stone_cech_unit is dense. (But stone_cech_unit need not be an embedding, for example if α is not Hausdorff.) -/ lemma dense_range_stone_cech_unit : dense_range (stone_cech_unit : α → stone_cech α) := dense_range_pure.quotient section extension variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ] variables {γ' : Type u} [topological_space γ'] [t2_space γ'] variables {f : α → γ} (hf : continuous f) local attribute [elab_with_expected_type] quotient.lift /-- The extension of a continuous function from α to a compact Hausdorff space γ to the Stone-Čech compactification of α. -/ def stone_cech_extend : stone_cech α → γ := quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf) lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f := ultrafilter_extend_extends f lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) := continuous_quot_lift _ (continuous_ultrafilter_extend f) lemma stone_cech_hom_ext {g₁ g₂ : stone_cech α → γ'} (h₁ : continuous g₁) (h₂ : continuous g₂) (h : g₁ ∘ stone_cech_unit = g₂ ∘ stone_cech_unit) : g₁ = g₂ := begin apply continuous.ext_on dense_range_stone_cech_unit h₁ h₂, rintros x ⟨x, rfl⟩, apply (congr_fun h x) end end extension lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : ↑u ≤ 𝓝 x) : u ≈ pure x := assume γ tγ h₁ h₂ f hf, begin resetI, transitivity f x, swap, symmetry, all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) }, { apply pure_le_nhds }, { exact ux } end lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) := continuous_iff_ultrafilter.mpr $ λ x g gx, have ↑(g.map pure) ≤ 𝓝 g, by rw ultrafilter_converges_iff; exact (bind_pure _).symm, have (g.map stone_cech_unit : filter (stone_cech α)) ≤ 𝓝 ⟦g⟧, from continuous_at_iff_ultrafilter.mp (continuous_quotient_mk.tendsto g) _ this, by rwa (show ⟦g⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this instance stone_cech.t2_space : t2_space (stone_cech α) := begin rw t2_iff_ultrafilter, rintros ⟨x⟩ ⟨y⟩ g gx gy, apply quotient.sound, intros γ tγ h₁ h₂ f hf, resetI, let ff := stone_cech_extend hf, change ff ⟦x⟧ = ff ⟦y⟧, have lim := λ (z : ultrafilter α) (gz : (g : filter (stone_cech α)) ≤ 𝓝 ⟦z⟧), ((continuous_stone_cech_extend hf).tendsto _).mono_left gz, exact tendsto_nhds_unique (lim x gx) (lim y gy) end instance stone_cech.compact_space : compact_space (stone_cech α) := quotient.compact_space end stone_cech
9f5dee1d9276ad73d014b791c98687f17c7ba378
dc253be9829b840f15d96d986e0c13520b085033
/cohomology/basic.hlean
fcaac450d759ccabd2c09e787f4de65bb15b1bbd
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
25,586
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Ulrik Buchholtz Reduced cohomology of spectra and cohomology theories -/ import ..spectrum.basic ..algebra.arrow_group ..algebra.product_group ..choice ..homotopy.fwedge ..homotopy.pushout ..homotopy.EM ..homotopy.wedge open eq spectrum int trunc pointed EM group algebra circle sphere nat EM.ops equiv susp is_trunc function fwedge cofiber bool lift sigma is_equiv choice pushout algebra unit pi is_conn wedge namespace cohomology universe variables u u' v w /- The cohomology of X with coefficients in Y is trunc 0 (A →* Ω[2] (Y (n+2))) In the file arrow_group (in algebra) we construct the group structure on this type. Equivalently, it's πₛ[n] (sp_cotensor X Y) -/ definition cohomology (X : Type*) (Y : spectrum) (n : ℤ) : AbGroup := AbGroup_trunc_pmap X (Y (n+2)) definition ordinary_cohomology [reducible] (X : Type*) (G : AbGroup) (n : ℤ) : AbGroup := cohomology X (EM_spectrum G) n definition ordinary_cohomology_Z [reducible] (X : Type*) (n : ℤ) : AbGroup := ordinary_cohomology X agℤ n definition unreduced_cohomology (X : Type) (Y : spectrum) (n : ℤ) : AbGroup := cohomology X₊ Y n definition unreduced_ordinary_cohomology [reducible] (X : Type) (G : AbGroup) (n : ℤ) : AbGroup := unreduced_cohomology X (EM_spectrum G) n definition unreduced_ordinary_cohomology_Z [reducible] (X : Type) (n : ℤ) : AbGroup := unreduced_ordinary_cohomology X agℤ n definition parametrized_cohomology {X : Type*} (Y : X → spectrum) (n : ℤ) : AbGroup := AbGroup_trunc_ppi (λx, Y x (n+2)) definition ordinary_parametrized_cohomology [reducible] {X : Type*} (G : X → AbGroup) (n : ℤ) : AbGroup := parametrized_cohomology (λx, EM_spectrum (G x)) n definition unreduced_parametrized_cohomology {X : Type} (Y : X → spectrum) (n : ℤ) : AbGroup := parametrized_cohomology (add_point_spectrum Y) n definition unreduced_ordinary_parametrized_cohomology [reducible] {X : Type} (G : X → AbGroup) (n : ℤ) : AbGroup := unreduced_parametrized_cohomology (λx, EM_spectrum (G x)) n notation `H^` n `[`:0 X:0 `, ` Y:0 `]`:0 := cohomology X Y n notation `oH^` n `[`:0 X:0 `, ` G:0 `]`:0 := ordinary_cohomology X G n notation `H^` n `[`:0 X:0 `]`:0 := ordinary_cohomology_Z X n notation `uH^` n `[`:0 X:0 `, ` Y:0 `]`:0 := unreduced_cohomology X Y n notation `uoH^` n `[`:0 X:0 `, ` G:0 `]`:0 := unreduced_ordinary_cohomology X G n notation `uH^` n `[`:0 X:0 `]`:0 := unreduced_ordinary_cohomology_Z X n notation `pH^` n `[`:0 binders `, ` r:(scoped Y, parametrized_cohomology Y n) `]`:0 := r notation `opH^` n `[`:0 binders `, ` r:(scoped G, ordinary_parametrized_cohomology G n) `]`:0 := r notation `upH^` n `[`:0 binders `, ` r:(scoped Y, unreduced_parametrized_cohomology Y n) `]`:0 := r notation `uopH^` n `[`:0 binders `, ` r:(scoped G, unreduced_ordinary_parametrized_cohomology G n) `]`:0 := r /- an alternate definition of cohomology -/ definition parametrized_cohomology_isomorphism_shomotopy_group_spi {X : Type*} (Y : X → spectrum) {n m : ℤ} (p : -m = n) : pH^n[(x : X), Y x] ≃g πₛ[m] (spi X Y) := begin apply isomorphism.trans (trunc_ppi_loop_isomorphism (λx, Ω (Y x (n + 2))))⁻¹ᵍ, apply homotopy_group_isomorphism_of_pequiv 0, esimp, have q : sub 2 m = n + 2, from (int.add_comm (of_nat 2) (-m) ⬝ ap (λk, k + of_nat 2) p), rewrite q, symmetry, apply loop_pppi_pequiv end definition unreduced_parametrized_cohomology_isomorphism_shomotopy_group_supi {X : Type} (Y : X → spectrum) {n m : ℤ} (p : -m = n) : upH^n[(x : X), Y x] ≃g πₛ[m] (supi X Y) := begin refine parametrized_cohomology_isomorphism_shomotopy_group_spi (add_point_spectrum Y) p ⬝g _, apply shomotopy_group_isomorphism_of_pequiv, intro k, apply pppi_add_point_over end definition cohomology_isomorphism_shomotopy_group_sp_cotensor (X : Type*) (Y : spectrum) {n m : ℤ} (p : -m = n) : H^n[X, Y] ≃g πₛ[m] (sp_cotensor X Y) := begin refine parametrized_cohomology_isomorphism_shomotopy_group_spi (λx, Y) p ⬝g _, apply shomotopy_group_isomorphism_of_pequiv, intro k, apply pppi_pequiv_ppmap end definition unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor (X : Type) (Y : spectrum) {n m : ℤ} (p : -m = n) : uH^n[X, Y] ≃g πₛ[m] (sp_ucotensor X Y) := begin refine cohomology_isomorphism_shomotopy_group_sp_cotensor X₊ Y p ⬝g _, apply shomotopy_group_isomorphism_of_pequiv, intro k, apply ppmap_add_point end /- functoriality -/ definition cohomology_functor [constructor] {X X' : Type*} (f : X' →* X) (Y : spectrum) (n : ℤ) : cohomology X Y n →g cohomology X' Y n := Group_trunc_pmap_homomorphism f notation `H^→` n `[`:0 f:0 `, ` Y:0 `]`:0 := cohomology_functor f Y n definition cohomology_functor_pid (X : Type*) (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) : cohomology_functor (pid X) Y n f = f := !Group_trunc_pmap_pid definition cohomology_functor_pcompose {X X' X'' : Type*} (f : X' →* X) (g : X'' →* X') (Y : spectrum) (n : ℤ) (h : H^n[X, Y]) : cohomology_functor (f ∘* g) Y n h = cohomology_functor g Y n (cohomology_functor f Y n h) := !Group_trunc_pmap_pcompose definition cohomology_functor_phomotopy {X X' : Type*} {f g : X' →* X} (p : f ~* g) (Y : spectrum) (n : ℤ) : cohomology_functor f Y n ~ cohomology_functor g Y n := Group_trunc_pmap_phomotopy p notation `H^~` n `[`:0 h:0 `, ` Y:0 `]`:0 := cohomology_functor_phomotopy h Y n definition cohomology_functor_phomotopy_refl {X X' : Type*} (f : X' →* X) (Y : spectrum) (n : ℤ) (x : H^n[X, Y]) : cohomology_functor_phomotopy (phomotopy.refl f) Y n x = idp := Group_trunc_pmap_phomotopy_refl f x definition cohomology_functor_pconst {X X' : Type*} (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) : cohomology_functor (pconst X' X) Y n f = 1 := !Group_trunc_pmap_pconst definition cohomology_isomorphism {X X' : Type*} (f : X' ≃* X) (Y : spectrum) (n : ℤ) : H^n[X, Y] ≃g H^n[X', Y] := Group_trunc_pmap_isomorphism f notation `H^≃` n `[`:0 e:0 `, ` Y:0 `]`:0 := cohomology_isomorphism e Y n definition cohomology_isomorphism_refl (X : Type*) (Y : spectrum) (n : ℤ) (x : H^n[X,Y]) : H^≃n[pequiv.refl X, Y] x = x := !Group_trunc_pmap_isomorphism_refl definition cohomology_isomorphism_right (X : Type*) {Y Y' : spectrum} (e : Πn, Y n ≃* Y' n) (n : ℤ) : H^n[X, Y] ≃g H^n[X, Y'] := cohomology_isomorphism_shomotopy_group_sp_cotensor X Y !neg_neg ⬝g shomotopy_group_isomorphism_of_pequiv (-n) (λk, ppmap_pequiv_ppmap_right (e k)) ⬝g (cohomology_isomorphism_shomotopy_group_sp_cotensor X Y' !neg_neg)⁻¹ᵍ definition unreduced_cohomology_isomorphism {X X' : Type} (f : X' ≃ X) (Y : spectrum) (n : ℤ) : uH^n[X, Y] ≃g uH^n[X', Y] := cohomology_isomorphism (add_point_pequiv f) Y n notation `uH^≃` n `[`:0 e:0 `, ` Y:0 `]`:0 := unreduced_cohomology_isomorphism e Y n definition unreduced_cohomology_isomorphism_right (X : Type) {Y Y' : spectrum} (e : Πn, Y n ≃* Y' n) (n : ℤ) : uH^n[X, Y] ≃g uH^n[X, Y'] := cohomology_isomorphism_right X₊ e n definition unreduced_ordinary_cohomology_isomorphism {X X' : Type} (f : X' ≃ X) (G : AbGroup) (n : ℤ) : uoH^n[X, G] ≃g uoH^n[X', G] := unreduced_cohomology_isomorphism f (EM_spectrum G) n notation `uoH^≃` n `[`:0 e:0 `, ` Y:0 `]`:0 := unreduced_ordinary_cohomology_isomorphism e Y n definition unreduced_ordinary_cohomology_isomorphism_right (X : Type) {G G' : AbGroup} (e : G ≃g G') (n : ℤ) : uoH^n[X, G] ≃g uoH^n[X, G'] := unreduced_cohomology_isomorphism_right X (EM_spectrum_pequiv e) n definition parametrized_cohomology_isomorphism_right {X : Type*} {Y Y' : X → spectrum} (e : Πx n, Y x n ≃* Y' x n) (n : ℤ) : pH^n[(x : X), Y x] ≃g pH^n[(x : X), Y' x] := parametrized_cohomology_isomorphism_shomotopy_group_spi Y !neg_neg ⬝g shomotopy_group_isomorphism_of_pequiv (-n) (λk, ppi_pequiv_right (λx, e x k)) ⬝g (parametrized_cohomology_isomorphism_shomotopy_group_spi Y' !neg_neg)⁻¹ᵍ definition unreduced_parametrized_cohomology_isomorphism_right {X : Type} {Y Y' : X → spectrum} (e : Πx n, Y x n ≃* Y' x n) (n : ℤ) : upH^n[(x : X), Y x] ≃g upH^n[(x : X), Y' x] := parametrized_cohomology_isomorphism_right (λx' k, add_point_over_pequiv (λx, e x k) x') n definition unreduced_ordinary_parametrized_cohomology_isomorphism_right {X : Type} {G G' : X → AbGroup} (e : Πx, G x ≃g G' x) (n : ℤ) : uopH^n[(x : X), G x] ≃g uopH^n[(x : X), G' x] := unreduced_parametrized_cohomology_isomorphism_right (λx, EM_spectrum_pequiv (e x)) n definition ordinary_cohomology_isomorphism_right (X : Type*) {G G' : AbGroup} (e : G ≃g G') (n : ℤ) : oH^n[X, G] ≃g oH^n[X, G'] := cohomology_isomorphism_right X (EM_spectrum_pequiv e) n definition ordinary_parametrized_cohomology_isomorphism_right {X : Type*} {G G' : X → AbGroup} (e : Πx, G x ≃g G' x) (n : ℤ) : opH^n[(x : X), G x] ≃g opH^n[(x : X), G' x] := parametrized_cohomology_isomorphism_right (λx, EM_spectrum_pequiv (e x)) n definition uopH_isomorphism_opH {X : Type} (G : X → AbGroup) (n : ℤ) : uopH^n[(x : X), G x] ≃g opH^n[(x : X₊), add_point_AbGroup G x] := parametrized_cohomology_isomorphism_right begin intro x n, induction x with x, { symmetry, apply EM_spectrum_trivial, }, { reflexivity } end n definition pH_isomorphism_H {X : Type*} (Y : spectrum) (n : ℤ) : pH^n[(x : X), Y] ≃g H^n[X, Y] := by reflexivity definition opH_isomorphism_oH {X : Type*} (G : AbGroup) (n : ℤ) : opH^n[(x : X), G] ≃g oH^n[X, G] := by reflexivity definition upH_isomorphism_uH {X : Type} (Y : spectrum) (n : ℤ) : upH^n[(x : X), Y] ≃g uH^n[X, Y] := unreduced_parametrized_cohomology_isomorphism_shomotopy_group_supi _ !neg_neg ⬝g (unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor _ _ !neg_neg)⁻¹ᵍ definition uopH_isomorphism_uoH {X : Type} (G : AbGroup) (n : ℤ) : uopH^n[(x : X), G] ≃g uoH^n[X, G] := !upH_isomorphism_uH definition uopH_isomorphism_uoH_of_is_conn {X : Type*} (G : X → AbGroup) (n : ℤ) (H : is_conn 1 X) : uopH^n[(x : X), G x] ≃g uoH^n[X, G pt] := begin refine _ ⬝g !uopH_isomorphism_uoH, apply unreduced_ordinary_parametrized_cohomology_isomorphism_right, refine is_conn.elim 0 _ _, reflexivity end definition cohomology_change_int (X : Type*) (Y : spectrum) {n n' : ℤ} (p : n = n') : H^n[X, Y] ≃g H^n'[X, Y] := isomorphism_of_eq (ap (λn, H^n[X, Y]) p) definition parametrized_cohomology_change_int (X : Type*) (Y : X → spectrum) {n n' : ℤ} (p : n = n') : pH^n[(x : X), Y x] ≃g pH^n'[(x : X), Y x] := isomorphism_of_eq (ap (λn, pH^n[(x : X), Y x]) p) /- suspension axiom -/ definition cohomology_susp_2 (Y : spectrum) (n : ℤ) : Ω (Ω[2] (Y ((n+1)+2))) ≃* Ω[2] (Y (n+2)) := begin apply loopn_pequiv_loopn 2, exact loop_pequiv_loop (pequiv_of_eq (ap Y (add.right_comm n 1 2))) ⬝e* !equiv_glue⁻¹ᵉ* end definition cohomology_susp_1 (X : Type*) (Y : spectrum) (n : ℤ) : susp X →* Ω (Ω (Y (n + 1 + 2))) ≃ X →* Ω (Ω (Y (n+2))) := calc susp X →* Ω[2] (Y (n + 1 + 2)) ≃ X →* Ω (Ω[2] (Y (n + 1 + 2))) : susp_adjoint_loop_unpointed ... ≃ X →* Ω[2] (Y (n+2)) : equiv_of_pequiv (ppmap_pequiv_ppmap_right (cohomology_susp_2 Y n)) definition cohomology_susp_1_pmap_mul {X : Type*} {Y : spectrum} {n : ℤ} (f g : susp X →* Ω (Ω (Y (n + 1 + 2)))) : cohomology_susp_1 X Y n (pmap_mul f g) ~* pmap_mul (cohomology_susp_1 X Y n f) (cohomology_susp_1 X Y n g) := begin unfold [cohomology_susp_1], refine pwhisker_left _ !loop_susp_intro_pmap_mul ⬝* _, apply pcompose_pmap_mul end definition cohomology_susp_equiv (X : Type*) (Y : spectrum) (n : ℤ) : H^n+1[susp X, Y] ≃ H^n[X, Y] := trunc_equiv_trunc _ (cohomology_susp_1 X Y n) definition cohomology_susp (X : Type*) (Y : spectrum) (n : ℤ) : H^n+1[susp X, Y] ≃g H^n[X, Y] := isomorphism_of_equiv (cohomology_susp_equiv X Y n) begin intro f₁ f₂, induction f₁ with f₁, induction f₂ with f₂, apply ap tr, apply eq_of_phomotopy, exact cohomology_susp_1_pmap_mul f₁ f₂ end definition cohomology_susp_natural {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) : cohomology_susp X Y n ∘ cohomology_functor (susp_functor f) Y (n+1) ~ cohomology_functor f Y n ∘ cohomology_susp X' Y n := begin refine (trunc_functor_compose _ _ _)⁻¹ʰᵗʸ ⬝hty _ ⬝hty trunc_functor_compose _ _ _, apply trunc_functor_homotopy, intro g, apply eq_of_phomotopy, refine _ ⬝* !passoc⁻¹*, apply pwhisker_left, apply loop_susp_intro_natural end /- exactness -/ definition cohomology_exact {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) : is_exact_g (cohomology_functor (pcod f) Y n) (cohomology_functor f Y n) := is_exact_trunc_functor (cofiber_exact f) /- additivity -/ definition additive_hom [constructor] {I : Type} (X : I → Type*) (Y : spectrum) (n : ℤ) : H^n[⋁X, Y] →g Πᵍ i, H^n[X i, Y] := Group_pi_intro (λi, cohomology_functor (pinl i) Y n) definition additive_equiv {I : Type.{u}} (H : has_choice.{u (max v w)} 0 I) (X : I → pType.{v}) (Y : spectrum.{w}) (n : ℤ) : H^n[⋁X, Y] ≃ Πᵍ i, H^n[X i, Y] := trunc_fwedge_pmap_equiv H X (Ω[2] (Y (n+2))) definition spectrum_additive {I : Type} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum) (n : ℤ) : is_equiv (additive_hom X Y n) := is_equiv_of_equiv_of_homotopy (additive_equiv H X Y n) begin intro f, induction f, reflexivity end definition cohomology_fwedge {I : Type.{u}} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum) (n : ℤ) : H^n[⋁X, Y] ≃g Πᵍ i, H^n[X i, Y] := isomorphism.mk (additive_hom X Y n) (spectrum_additive H X Y n) /- dimension axiom for ordinary cohomology -/ open is_conn trunc_index theorem ordinary_cohomology_dimension (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (oH^n[pbool, G]) := begin apply is_conn_equiv_closed 0 !pmap_pbool_equiv⁻¹ᵉ, apply is_conn_equiv_closed 0 !equiv_glue2⁻¹ᵉ, cases n with n n, { cases n with n, { exfalso, apply H, reflexivity }, { apply is_conn_of_le, apply zero_le_of_nat n, exact is_conn_EMadd1 G n, }}, { apply is_trunc_trunc_of_is_trunc, apply @is_contr_loop_of_is_trunc (n+1) (K G 0), apply is_trunc_of_le _ (zero_le_of_nat n) _ } end theorem ordinary_cohomology_dimension_plift (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (oH^n[plift pbool, G]) := is_trunc_equiv_closed_rev -2 (equiv_of_isomorphism (cohomology_isomorphism (pequiv_plift pbool) _ _)) (ordinary_cohomology_dimension G n H) definition cohomology_iterate_susp (X : Type*) (Y : spectrum) (n : ℤ) (k : ℕ) : H^n+k[iterate_susp k X, Y] ≃g H^n[X, Y] := begin induction k with k IH, { exact cohomology_change_int X Y !add_zero }, { exact cohomology_change_int _ _ !add.assoc⁻¹ ⬝g cohomology_susp _ _ _ ⬝g IH } end definition ordinary_cohomology_pbool (G : AbGroup) : oH^0[pbool, G] ≃g G := begin refine cohomology_isomorphism_shomotopy_group_sp_cotensor _ _ !neg_neg ⬝g _, change πg[2] (pbool →** EM G 2) ≃g G, refine homotopy_group_isomorphism_of_pequiv 1 !ppmap_pbool_pequiv ⬝g ghomotopy_group_EM G 1 end definition ordinary_cohomology_sphere (G : AbGroup) (n : ℕ) : oH^n[sphere n, G] ≃g G := begin refine cohomology_isomorphism_shomotopy_group_sp_cotensor _ _ !neg_neg ⬝g _, change πg[2] (sphere n →** EM_spectrum G (2 - -n)) ≃g G, refine homotopy_group_isomorphism_of_pequiv 1 _ ⬝g ghomotopy_group_EMadd1 G 1, have p : 2 - (-n) = succ (1 + n), from !sub_eq_add_neg ⬝ ap (add 2) !neg_neg ⬝ ap of_nat !succ_add, refine !sphere_pmap_pequiv ⬝e* Ω≃[n] (pequiv_ap (EM_spectrum G) p) ⬝e* loopn_EMadd1_add G n 1, end definition ordinary_cohomology_sphere_of_neq (G : AbGroup) {n : ℤ} {k : ℕ} (p : n ≠ k) : is_contr (oH^n[sphere k, G]) := begin refine is_contr_equiv_closed_rev _ (ordinary_cohomology_dimension G (n-k) (λh, p (eq_of_sub_eq_zero h))), apply equiv_of_isomorphism, exact cohomology_change_int _ _ !neg_add_cancel_right⁻¹ ⬝g cohomology_iterate_susp pbool (EM_spectrum G) (n - k) k end definition cohomology_punit (Y : spectrum) (n : ℤ) : is_contr (H^n[punit, Y]) := @is_trunc_trunc_of_is_trunc _ _ _ !is_contr_punit_pmap definition cohomology_wedge (X : pType.{u}) (X' : pType.{u'}) (Y : spectrum.{v}) (n : ℤ) : H^n[wedge X X', Y] ≃g H^n[X, Y] ×ag H^n[X', Y] := H^≃n[(wedge_pequiv !pequiv_plift !pequiv_plift ⬝e* wedge_pequiv_fwedge (plift.{u u'} X) (plift.{u' u} X'))⁻¹ᵉ*, Y] ⬝g cohomology_fwedge (has_choice_bool _) _ Y n ⬝g Group_pi_isomorphism_Group_pi erfl begin intro b, induction b: reflexivity end ⬝g (product_isomorphism_Group_pi H^n[plift.{u u'} X, Y] H^n[plift.{u' u} X', Y])⁻¹ᵍ ⬝g proof H^≃n[!pequiv_plift, Y] ×≃g H^≃n[!pequiv_plift, Y] qed definition cohomology_isomorphism_of_equiv {X X' : Type*} (e : X ≃ X') (Y : spectrum) (n : ℤ) : H^n[X', Y] ≃g H^n[X, Y] := !cohomology_susp⁻¹ᵍ ⬝g H^≃n+1[susp_pequiv_of_equiv e, Y] ⬝g !cohomology_susp definition unreduced_cohomology_split (X : pType.{u}) (Y : spectrum.{v}) (n : ℤ) : uH^n[X, Y] ≃g H^n[X, Y] ×ag H^n[pbool, Y] := cohomology_isomorphism_of_equiv (wedge_pbool_equiv_add_point X) Y n ⬝g cohomology_wedge X pbool Y n definition unreduced_ordinary_cohomology_nonzero (X : pType.{u}) (G : AbGroup.{v}) (n : ℤ) (H : n ≠ 0) : uoH^n[X, G] ≃g oH^n[X, G] := unreduced_cohomology_split X (EM_spectrum G) n ⬝g product_trivial_right _ _ (ordinary_cohomology_dimension _ _ H) definition unreduced_ordinary_cohomology_zero (X : Type*) (G : AbGroup) : uoH^0[X, G] ≃g oH^0[X, G] ×ag G := unreduced_cohomology_split X (EM_spectrum G) 0 ⬝g (!isomorphism.refl ×≃g ordinary_cohomology_pbool G) definition unreduced_ordinary_cohomology_pbool (G : AbGroup.{v}) : uoH^0[pbool, G] ≃g G ×ag G := unreduced_ordinary_cohomology_zero pbool G ⬝g (ordinary_cohomology_pbool G ×≃g !isomorphism.refl) definition unreduced_ordinary_cohomology_pbool_nonzero (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (uoH^n[pbool, G]) := is_contr_equiv_closed_rev (equiv_of_isomorphism (unreduced_ordinary_cohomology_nonzero pbool G n H)) (ordinary_cohomology_dimension G n H) definition unreduced_ordinary_cohomology_sphere_zero (G : AbGroup.{u}) (n : ℕ) (H : n ≠ 0) : uoH^0[sphere n, G] ≃g G := unreduced_ordinary_cohomology_zero (sphere n) G ⬝g product_trivial_left _ _ (ordinary_cohomology_sphere_of_neq _ (λh, H (of_nat.inj h⁻¹))) definition unreduced_ordinary_cohomology_sphere (G : AbGroup) (n : ℕ) (H : n ≠ 0) : uoH^n[sphere n, G] ≃g G := unreduced_ordinary_cohomology_nonzero (sphere n) G n (λh, H (of_nat.inj h)) ⬝g ordinary_cohomology_sphere G n definition unreduced_ordinary_cohomology_sphere_of_neq (G : AbGroup) {n : ℤ} {k : ℕ} (p : n ≠ k) (q : n ≠ 0) : is_contr (uoH^n[sphere k, G]) := is_contr_equiv_closed_rev (equiv_of_isomorphism (unreduced_ordinary_cohomology_nonzero (sphere k) G n q)) (ordinary_cohomology_sphere_of_neq G p) definition unreduced_ordinary_cohomology_sphere_of_neq_nat (G : AbGroup) {n k : ℕ} (p : n ≠ k) (q : n ≠ 0) : is_contr (uoH^n[sphere k, G]) := unreduced_ordinary_cohomology_sphere_of_neq G (λh, p (of_nat.inj h)) (λh, q (of_nat.inj h)) definition unreduced_ordinary_cohomology_sphere_of_gt (G : AbGroup) {n k : ℕ} (p : n > k) : is_contr (uoH^n[sphere k, G]) := unreduced_ordinary_cohomology_sphere_of_neq_nat G (ne_of_gt p) (ne_of_gt (lt_of_le_of_lt (zero_le k) p)) theorem is_contr_cohomology_of_is_contr_spectrum (n : ℤ) (X : Type*) (Y : spectrum) (H : is_contr (Y n)) : is_contr (H^n[X, Y]) := begin apply is_trunc_trunc_of_is_trunc, apply is_trunc_pmap, refine is_contr_equiv_closed_rev _ H, exact loop_pequiv_loop (loop_pequiv_loop (pequiv_ap Y (add.assoc n 1 1)⁻¹) ⬝e* (equiv_glue Y (n+1))⁻¹ᵉ*) ⬝e (equiv_glue Y n)⁻¹ᵉ* end theorem is_contr_ordinary_cohomology (n : ℤ) (X : Type*) (G : AbGroup) (H : is_contr G) : is_contr (oH^n[X, G]) := begin apply is_contr_cohomology_of_is_contr_spectrum, exact is_contr_EM_spectrum _ _ H end theorem is_contr_unreduced_ordinary_cohomology (n : ℤ) (X : Type) (G : AbGroup) (H : is_contr G) : is_contr (uoH^n[X, G]) := is_contr_ordinary_cohomology _ _ _ H theorem is_contr_ordinary_cohomology_of_neg {n : ℤ} (X : Type*) (G : AbGroup) (H : n < 0) : is_contr (oH^n[X, G]) := begin apply is_contr_cohomology_of_is_contr_spectrum, cases n with n n, contradiction, apply is_contr_EM_spectrum_neg end /- cohomology theory -/ structure cohomology_theory : Type := (HH : ℤ → pType.{u} → AbGroup.{u}) (Hiso : Π(n : ℤ) {X Y : Type*} (f : X ≃* Y), HH n Y ≃g HH n X) (Hiso_refl : Π(n : ℤ) (X : Type*) (x : HH n X), Hiso n pequiv.rfl x = x) (Hh : Π(n : ℤ) {X Y : Type*} (f : X →* Y), HH n Y →g HH n X) (Hhomotopy : Π(n : ℤ) {X Y : Type*} {f g : X →* Y} (p : f ~* g), Hh n f ~ Hh n g) (Hhomotopy_refl : Π(n : ℤ) {X Y : Type*} (f : X →* Y) (x : HH n Y), Hhomotopy n (phomotopy.refl f) x = idp) (Hid : Π(n : ℤ) {X : Type*} (x : HH n X), Hh n (pid X) x = x) (Hcompose : Π(n : ℤ) {X Y Z : Type*} (g : Y →* Z) (f : X →* Y) (z : HH n Z), Hh n (g ∘* f) z = Hh n f (Hh n g z)) (Hsusp : Π(n : ℤ) (X : Type*), HH (succ n) (susp X) ≃g HH n X) (Hsusp_natural : Π(n : ℤ) {X Y : Type*} (f : X →* Y), Hsusp n X ∘ Hh (succ n) (susp_functor f) ~ Hh n f ∘ Hsusp n Y) (Hexact : Π(n : ℤ) {X Y : Type*} (f : X →* Y), is_exact_g (Hh n (pcod f)) (Hh n f)) (Hadditive : Π(n : ℤ) {I : Type.{u}} (X : I → Type*), has_choice.{u u} 0 I → is_equiv (Group_pi_intro (λi, Hh n (pinl i)) : HH n (⋁ X) → Πᵍ i, HH n (X i))) structure ordinary_cohomology_theory extends cohomology_theory.{u} : Type := (Hdimension : Π(n : ℤ), n ≠ 0 → is_contr (HH n (plift pbool))) attribute cohomology_theory.HH [coercion] postfix `^→`:90 := cohomology_theory.Hh open cohomology_theory definition Hequiv (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X ≃* Y) : H n Y ≃ H n X := equiv_of_isomorphism (Hiso H n f) definition Hsusp_neg (H : cohomology_theory) (n : ℤ) (X : Type*) : H n (susp X) ≃g H (pred n) X := isomorphism_of_eq (ap (λn, H n _) proof (sub_add_cancel n 1)⁻¹ qed) ⬝g cohomology_theory.Hsusp H (pred n) X definition Hsusp_neg_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : Hsusp_neg H n X ∘ H ^→ n (susp_functor f) ~ H ^→ (pred n) f ∘ Hsusp_neg H n Y := sorry definition Hsusp_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : H ^→ (succ n) (susp_functor f) ∘g (Hsusp H n Y)⁻¹ᵍ ~ (Hsusp H n X)⁻¹ᵍ ∘ H ^→ n f := sorry definition Hsusp_neg_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : H ^→ n (susp_functor f) ∘g (Hsusp_neg H n Y)⁻¹ᵍ ~ (Hsusp_neg H n X)⁻¹ᵍ ∘ H ^→ (pred n) f := sorry definition Hadditive_equiv (H : cohomology_theory) (n : ℤ) {I : Type} (X : I → Type*) (H2 : has_choice 0 I) : H n (⋁ X) ≃g Πᵍ i, H n (X i) := isomorphism.mk _ (Hadditive H n X H2) definition Hlift_empty (H : cohomology_theory.{u}) (n : ℤ) : is_contr (H n (plift punit)) := let P : lift empty → Type* := lift.rec empty.elim in let x := Hadditive H n P _ in begin note z := equiv.mk _ x, refine @(is_trunc_equiv_closed_rev -2 (_ ⬝e z ⬝e _)) !is_contr_unit, refine Hequiv H n (pequiv_punit_of_is_contr _ _ ⬝e* !pequiv_plift), apply is_contr_fwedge_of_neg, intro y, induction y with y, exact y, apply equiv_unit_of_is_contr, apply is_contr_pi_of_neg, intro y, induction y with y, exact y end definition Hempty (H : cohomology_theory.{0}) (n : ℤ) : is_contr (H n punit) := @(is_trunc_equiv_closed _ (Hequiv H n !pequiv_plift)) (Hlift_empty H n) definition Hconst (H : cohomology_theory) (n : ℤ) {X Y : Type*} (y : H n Y) : H ^→ n (pconst X Y) y = 1 := begin refine Hhomotopy H n (pconst_pcompose (pconst X (plift punit)))⁻¹* y ⬝ _, refine Hcompose H n _ _ y ⬝ _, refine ap (H ^→ n _) (@eq_of_is_contr _ (Hlift_empty H n) _ 1) ⬝ _, apply respect_one end -- definition Hwedge (H : cohomology_theory) (n : ℤ) (A B : Type*) : H n (A ∨ B) ≃g H n A ×ag H n B := -- begin -- refine Hiso H n (wedge_pequiv_fwedge A B)⁻¹ᵉ* ⬝g _, -- refine Hadditive_equiv H n _ _ ⬝g _ -- end definition cohomology_theory_spectrum [constructor] (Y : spectrum.{u}) : cohomology_theory.{u} := cohomology_theory.mk (λn A, H^n[A, Y]) (λn A B f, cohomology_isomorphism f Y n) (λn A, cohomology_isomorphism_refl A Y n) (λn A B f, cohomology_functor f Y n) (λn A B f g p, cohomology_functor_phomotopy p Y n) (λn A B f x, cohomology_functor_phomotopy_refl f Y n x) (λn A x, cohomology_functor_pid A Y n x) (λn A B C g f x, cohomology_functor_pcompose g f Y n x) (λn A, cohomology_susp A Y n) (λn A B f, cohomology_susp_natural f Y n) (λn A B f, cohomology_exact f Y n) (λn I A H, spectrum_additive H A Y n) definition ordinary_cohomology_theory_EM [constructor] (G : AbGroup) : ordinary_cohomology_theory := ⦃ordinary_cohomology_theory, cohomology_theory_spectrum (EM_spectrum G), Hdimension := ordinary_cohomology_dimension_plift G ⦄ end cohomology
17711b6a09b6a7eca25dee862b8096ef871ccfca
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/simplexfmatrix.lean
55be97bd57e695df437b3046b3d3b6d3502989d5
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
648
lean
import .simplex_new_pivot .fmatrix namespace fmatrix open pequiv simplex variables {m n : ℕ} def pivot_element (B : prebasis m n) (A_bar : fmatrix m n) (r : fin m) (s : fin (n - m)) : ℚ := A_bar.read r (B.nonbasisg s) def choose_pivot_row (B : prebasis m n) (A_bar : fmatrix m n) (b_bar : fmatrix m 1) (c : fmatrix 1 n) (s : fin (n - m)) : option (fin m) := fin.find (λ r : fin m, 0 < pivot_element B A_bar r s ∧ ∀ i : fin m, 0 < pivot_element B A_bar i s) → ratio B A_bar b_bar r s ≤ ratio B A_bar b_bar i s) def simplex : Π (B : prebasis m n) (A_bar : fmatrix m n) (b_bar : fmatrix m 1) (c : fmatrix 1 n) end fmatrix
3e3bfc8bd553322770dd8816beb2a99a25c2ec9f
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/combinatorics/simple_graph/basic.lean
8cf62cbaa9fc07fd7ceea7673e8cb7bb6eeefec8
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
11,305
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov -/ import data.fintype.basic import data.sym2 /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `neighbor_set` is the `set` of vertices adjacent to a given vertex * `neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `incidence_set` is the `set` of edges containing a given vertex * `incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite ## Implementation notes * A locally finite graph is one with instances `∀ v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. TODO: This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. TODO: Part of this would include defining, for example, subgraphs of a simple graph. -/ open finset universe u /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent edges; see `simple_graph.edge_set` for the corresponding edge set. -/ @[ext] structure simple_graph (V : Type u) := (adj : V → V → Prop) (sym : symmetric adj . obviously) (loopless : irreflexive adj . obviously) /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := { adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a), sym := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩, loopless := λ a ⟨hn, _⟩, hn rfl } noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) := by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext } @[simp] lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := by refl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } instance (V : Type u) : inhabited (simple_graph V) := ⟨complete_graph V⟩ instance complete_graph_adj_decidable (V : Type u) [decidable_eq V] : decidable_rel (complete_graph V).adj := by { dsimp [complete_graph], apply_instance } namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) lemma ne_of_adj {a b : V} (hab : G.adj a b) : a ≠ b := by { rintro rfl, exact G.loopless a hab } /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. -/ def edge_set : set (sym2 V) := sym2.from_rel G.sym /-- The `incidence_set` is the set of edges incident to a given vertex. -/ def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e} lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set := λ _ h, h.1 @[simp] lemma mem_edge_set {v w : V} : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := by refl /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩, { simpa }, { rintro ⟨hne, e, he, hv⟩, rw sym2.elems_iff_eq hne at hv, subst e, rwa mem_edge_set at he } end lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.mem_other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance edges_fintype [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := by { dunfold edge_set, exact subtype.fintype _ } instance mem_edge_set_decidable [decidable_rel G.adj] (e : sym2 V) : decidable (e ∈ G.edge_set) := by { dunfold edge_set, apply_instance } instance mem_incidence_set_decidable [decidable_eq V] [decidable_rel G.adj] (v : V) (e : sym2 V) : decidable (e ∈ G.incidence_set v) := by { dsimp [incidence_set], apply_instance } /-- The `edge_set` of the graph as a `finset`. -/ def edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] : finset (sym2 V) := set.to_finset G.edge_set @[simp] lemma mem_edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] (e : sym2 V) : e ∈ G.edge_finset ↔ e ∈ G.edge_set := by { dunfold edge_finset, simp } @[simp] lemma edge_set_univ_card [decidable_eq V] [fintype V] [decidable_rel G.adj] : (univ : finset G.edge_set).card = G.edge_finset.card := fintype.card_of_subtype G.edge_finset (mem_edge_finset _) @[simp] lemma irrefl {v : V} : ¬G.adj v v := G.loopless v @[symm] lemma edge_symm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.sym x, λ x, G.sym x⟩ @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := by tauto @[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w := by simp [incidence_set] lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v := by simp only [mem_incidence_set, mem_neighbor_set] lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) : G.incidence_set v ∩ G.incidence_set h.other = {e} := begin ext e', simp only [incidence_set, set.mem_sep_eq, set.mem_inter_eq, set.mem_singleton_iff], split, { intro h', rw ←sym2.mem_other_spec h, exact (sym2.elems_iff_eq (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩, }, { rintro rfl, use [he, h, he], apply sym2.mem_other_mem, }, end section incidence variable [decidable_eq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other' lemma edge_mem_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : e ∈ G.incidence_set (G.other_vertex_of_incident h) := by { use h.1, simp [other_vertex_of_incident, sym2.mem_other_mem'] } lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : G.other_vertex_of_incident h ∈ G.neighbor_set v := by { cases h with he hv, rwa [←sym2.mem_other_spec' hv, mem_edge_set] at he } @[simp] lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) : G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w := sym2.congr_right.mp (sym2.mem_other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v := { to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩, inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩, left_inv := λ x, by simp [other_vertex_of_incident], right_inv := λ ⟨w, hw⟩, by simp } end incidence section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v : V) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := by simp [neighbor_finset] /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := by simp [degree, neighbor_finset] lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w := by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset] instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) := fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset @[simp] lemma card_incidence_set_eq_degree [decidable_eq V] : fintype.card (G.incidence_set v) = G.degree v := by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp } @[simp] lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) : e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v := set.mem_to_finset end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d end locally_finite section finite variables [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (complete_graph V).degree v = fintype.card V - 1 := begin convert univ.card.pred_eq_sub_one, erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v)], end lemma complete_graph_is_regular [decidable_eq V] : (complete_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } /-- The minimum degree of all vertices -/ def min_degree (G : simple_graph V) [nonempty V] [decidable_rel G.adj] : ℕ := finset.min' (univ.image (λ (v : V), G.degree v)) (nonempty.image univ_nonempty _) /-- The maximum degree of all vertices -/ def max_degree (G : simple_graph V) [nonempty V] [decidable_rel G.adj] : ℕ := finset.max' (univ.image (λ (v : V), G.degree v)) (nonempty.image univ_nonempty _) end finite end simple_graph
ca37b4d3ab14ca158e3b283a645ec2b4d25bdaf6
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/complex/roots_of_unity.lean
69b5a6ed117238368ecfa2b54833aacd2ac9d531
[ "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
6,998
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 analysis.special_functions.complex.log import ring_theory.roots_of_unity /-! # Complex roots of unity In this file we show that the `n`-th complex roots of unity are exactly the complex numbers `e ^ (2 * real.pi * complex.I * (i / n))` for `i ∈ finset.range n`. ## Main declarations * `complex.mem_roots_of_unity`: the complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. * `complex.card_roots_of_unity`: the number of `n`-th roots of unity is exactly `n`. -/ namespace complex open polynomial real open_locale nat real lemma is_primitive_root_exp_of_coprime (i n : ℕ) (h0 : n ≠ 0) (hi : i.coprime n) : is_primitive_root (exp (2 * π * I * (i / n))) n := begin rw is_primitive_root.iff_def, simp only [← exp_nat_mul, exp_eq_one_iff], have hn0 : (n : ℂ) ≠ 0, by exact_mod_cast h0, split, { use i, field_simp [hn0, mul_comm (i : ℂ), mul_comm (n : ℂ)] }, { simp only [hn0, mul_right_comm _ _ ↑n, mul_left_inj' two_pi_I_ne_zero, ne.def, not_false_iff, mul_comm _ (i : ℂ), ← mul_assoc _ (i : ℂ), exists_imp_distrib] with field_simps, norm_cast, rintro l k hk, have : n ∣ i * l, { rw [← int.coe_nat_dvd, hk], apply dvd_mul_left }, exact hi.symm.dvd_of_dvd_mul_left this } end lemma is_primitive_root_exp (n : ℕ) (h0 : n ≠ 0) : is_primitive_root (exp (2 * π * I / n)) n := by simpa only [nat.cast_one, one_div] using is_primitive_root_exp_of_coprime 1 n h0 n.coprime_one_left lemma is_primitive_root_iff (ζ : ℂ) (n : ℕ) (hn : n ≠ 0) : is_primitive_root ζ n ↔ (∃ (i < (n : ℕ)) (hi : i.coprime n), exp (2 * π * I * (i / n)) = ζ) := begin have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast hn, split, swap, { rintro ⟨i, -, hi, rfl⟩, exact is_primitive_root_exp_of_coprime i n hn hi }, intro h, obtain ⟨i, hi, rfl⟩ := (is_primitive_root_exp n hn).eq_pow_of_pow_eq_one h.pow_eq_one (nat.pos_of_ne_zero hn), refine ⟨i, hi, ((is_primitive_root_exp n hn).pow_iff_coprime (nat.pos_of_ne_zero hn) i).mp h, _⟩, rw [← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] end /-- The complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. -/ lemma mem_roots_of_unity (n : ℕ+) (x : units ℂ) : x ∈ roots_of_unity n ℂ ↔ (∃ i < (n : ℕ), exp (2 * π * I * (i / n)) = x) := begin rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, units.coe_one], have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast (n.ne_zero), split, { intro h, obtain ⟨i, hi, H⟩ : ∃ i < (n : ℕ), exp (2 * π * I / n) ^ i = x, { simpa only using (is_primitive_root_exp n n.ne_zero).eq_pow_of_pow_eq_one h n.pos }, refine ⟨i, hi, _⟩, rw [← H, ← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] }, { rintro ⟨i, hi, H⟩, rw [← H, ← exp_nat_mul, exp_eq_one_iff], use i, field_simp [hn0, mul_comm ((n : ℕ) : ℂ), mul_comm (i : ℂ)] } end lemma card_roots_of_unity (n : ℕ+) : fintype.card (roots_of_unity n ℂ) = n := (is_primitive_root_exp n n.ne_zero).card_roots_of_unity lemma card_primitive_roots (k : ℕ) : (primitive_roots k ℂ).card = φ k := begin by_cases h : k = 0, { simp [h] }, exact (is_primitive_root_exp k h).card_primitive_roots, end end complex lemma is_primitive_root.norm'_eq_one {ζ : ℂ} {n : ℕ} (h : is_primitive_root ζ n) (hn : n ≠ 0) : ∥ζ∥ = 1 := complex.norm_eq_one_of_pow_eq_one h.pow_eq_one hn lemma is_primitive_root.nnnorm_eq_one {ζ : ℂ} {n : ℕ} (h : is_primitive_root ζ n) (hn : n ≠ 0) : ∥ζ∥₊ = 1 := subtype.ext $ h.norm'_eq_one hn lemma is_primitive_root.arg_ext {n m : ℕ} {ζ μ : ℂ} (hζ : is_primitive_root ζ n) (hμ : is_primitive_root μ m) (hn : n ≠ 0) (hm : m ≠ 0) (h : ζ.arg = μ.arg) : ζ = μ := complex.ext_abs_arg ((hζ.norm'_eq_one hn).trans (hμ.norm'_eq_one hm).symm) h lemma is_primitive_root.arg_eq_zero_iff {n : ℕ} {ζ : ℂ} (hζ : is_primitive_root ζ n) (hn : n ≠ 0) : ζ.arg = 0 ↔ ζ = 1 := ⟨λ h, hζ.arg_ext is_primitive_root.one hn one_ne_zero (h.trans complex.arg_one.symm), λ h, h.symm ▸ complex.arg_one⟩ lemma is_primitive_root.arg_eq_pi_iff {n : ℕ} {ζ : ℂ} (hζ : is_primitive_root ζ n) (hn : n ≠ 0) : ζ.arg = real.pi ↔ ζ = -1 := ⟨λ h, hζ.arg_ext (is_primitive_root.neg_one 0 two_ne_zero.symm) hn two_ne_zero (h.trans complex.arg_neg_one.symm), λ h, h.symm ▸ complex.arg_neg_one⟩ lemma is_primitive_root.arg {n : ℕ} {ζ : ℂ} (h : is_primitive_root ζ n) (hn : n ≠ 0) : ∃ i : ℤ, ζ.arg = i / n * (2 * real.pi) ∧ is_coprime i n ∧ i.nat_abs < n := begin rw complex.is_primitive_root_iff _ _ hn at h, obtain ⟨i, h, hin, rfl⟩ := h, rw [mul_comm, ←mul_assoc, complex.exp_mul_I], refine ⟨if i * 2 ≤ n then i else i - n, _, _, _⟩, work_on_goal 2 { replace hin := nat.is_coprime_iff_coprime.mpr hin, split_ifs with _, { exact hin }, { convert hin.add_mul_left_left (-1), rw [mul_neg_one, sub_eq_add_neg] } }, work_on_goal 2 { split_ifs with h₂, { exact_mod_cast h }, suffices : (i - n : ℤ).nat_abs = n - i, { rw this, apply tsub_lt_self hn.bot_lt, contrapose! h₂, rw [nat.eq_zero_of_le_zero h₂, zero_mul], exact zero_le _ }, rw [←int.nat_abs_neg, neg_sub, int.nat_abs_eq_iff], exact or.inl (int.coe_nat_sub h.le).symm }, split_ifs with h₂, { convert complex.arg_cos_add_sin_mul_I _, { push_cast }, { push_cast }, field_simp [hn], refine ⟨(neg_lt_neg real.pi_pos).trans_le _, _⟩, { rw neg_zero, exact mul_nonneg (mul_nonneg i.cast_nonneg $ by simp [real.pi_pos.le]) (by simp) }, rw [←mul_rotate', mul_div_assoc], rw ←mul_one n at h₂, exact mul_le_of_le_one_right real.pi_pos.le ((div_le_iff' $ by exact_mod_cast (pos_of_gt h)).mpr $ by exact_mod_cast h₂) }, rw [←complex.cos_sub_two_pi, ←complex.sin_sub_two_pi], convert complex.arg_cos_add_sin_mul_I _, { push_cast, rw [←sub_one_mul, sub_div, div_self], exact_mod_cast hn }, { push_cast, rw [←sub_one_mul, sub_div, div_self], exact_mod_cast hn }, field_simp [hn], refine ⟨_, le_trans _ real.pi_pos.le⟩, work_on_goal 2 { rw [mul_div_assoc], exact mul_nonpos_of_nonpos_of_nonneg (sub_nonpos.mpr $ by exact_mod_cast h.le) (div_nonneg (by simp [real.pi_pos.le]) $ by simp) }, rw [←mul_rotate', mul_div_assoc, neg_lt, ←mul_neg, mul_lt_iff_lt_one_right real.pi_pos, ←neg_div, ←neg_mul, neg_sub, div_lt_iff, one_mul, sub_mul, sub_lt, ←mul_sub_one], norm_num, exact_mod_cast not_le.mp h₂, { exact (nat.cast_pos.mpr hn.bot_lt) } end
d0231fa40dca6a117531ec8f093aeaa0b0d1de6d
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Init/Meta.lean
c8b1c66ba923897404217878b008bcc915cb2685
[ "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
31,957
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private constant version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private constant version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private constant version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () -- @[extern c inline "lean_mk_string(LEAN_GITHASH)"] -- constant getGithash (u : Unit) : String -- def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] constant version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] constant version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _ _) => n | n@(num anonymous _ _) => n | str n _ _ => getRoot n | num n _ _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s _ => s.contains '✝' || s == "_inaccessible" | Name.num p idx _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst s[0] && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s _ => maybeEscape s | num anonymous v _ => toString v | str n s _ => toStringWithSep n ++ sep ++ maybeEscape s | num n v _ => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let Name.str _ s _ := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString instance : Repr Name where reprPrec n _ := Std.Format.text "`" ++ n.toString def capitalize : Name → Name | Name.str p s _ => Name.mkStr p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s _), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s _), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s _ => Name.mkStr p (pre ++ s) | num p n _ => Name.mkNum (Name.mkStr p pre) n end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node k args, Syntax.node k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node _ args => args.findSomeRev? getTailInfo? | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i] match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node k args | none => none | stx => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos trail endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a.get ⟨i, h⟩; match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node k args | noxne => none | stx => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | stx => stx /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node _ args => args.findSome? getHead? | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : Syntax := Syntax.node k args /- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand all macros in the given syntax -/ partial def expandMacros : Syntax → MacroM Syntax | stx@(Syntax.node k args) => do match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros pure <| Syntax.node k args | stx => pure stx /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := Syntax.ident (SourceInfo.fromRef src) (toString val).toSubstring val [] def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) : m Syntax := do return mkIdentFrom (← getRef) val /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope Syntax.ident (SourceInfo.fromRef src) (toString id).toSubstring id [(c, [])] def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) : m Syntax := do return mkCIdentFrom (← getRef) c def mkCIdent (c : Name) : Syntax := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident SourceInfo.none (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := Syntax.node nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := Syntax.node groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => Syntax.node nullKind #[arg] | none => Syntax.node nullKind #[] def mkHole (ref : Syntax) : Syntax := Syntax.node `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (mkAtomFrom ref sep)⟩ instance (sep) : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Syntax) : (args : Array Syntax) → Syntax | #[] => fn | args => Syntax.node `Lean.Parser.Term.app #[fn, mkNullNode args] def mkCApp (fn : Name) (args : Array Syntax) : Syntax := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : Syntax := let atom : Syntax := Syntax.atom info val Syntax.node kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : Syntax := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : Syntax := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : Syntax := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : Syntax := mkLit nameLitKind val info /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get 1 if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := OptionM.run do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := OptionM.run do let c := s.get 1 if c == '\\' then do let (c, _) ← decodeQuotedChar s 2 pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def decodeNameLitAux (s : String) (i : Nat) (r : Name) : Option Name := OptionM.run do let continue? (i : Nat) (r : Name) : OptionM Name := if s.get i == '.' then decodeNameLitAux s (s.next i) r else if s.atEnd i then pure r else none let curr := s.get i if isIdBeginEscape curr then let startPart := s.next i let stopPart := s.nextUntil isIdEndEscape startPart if !isIdEndEscape (s.get stopPart) then none else continue? (s.next stopPart) (Name.mkStr r (s.extract startPart stopPart)) else if isIdFirst curr then let startPart := i let stopPart := s.nextWhile isIdRest startPart continue? stopPart (Name.mkStr r (s.extract startPart stopPart)) else none def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then decodeNameLitAux s 1 Name.anonymous else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) where quote : α → Syntax export Quote (quote) instance : Quote Syntax := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String := ⟨Syntax.mkStrLit⟩ instance : Quote Nat := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → OptionM (List String) | Name.anonymous => acc | Name.str n s _ => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num n i _ => none private def quoteNameMk : Name → Syntax | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s _ => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | Name.num n i _ => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name where quote n := match getEscapedNameParts? [] n with | some ss => mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)] | none => quoteNameMk n instance {α β : Type} [Quote α] [Quote β] : Quote (α × β) where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList {α : Type} [Quote α] : List α → Syntax | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance {α : Type} [Quote α] : Quote (List α) where quote := quoteList instance {α : Type} [Quote α] : Quote (Array α) where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] private def quoteOption {α : Type} [Quote α] : Option α → Syntax | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] instance Option.hasQuote {α : Type} [Quote α] : Quote (Option α) where quote := quoteOption /- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):numLit) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):numLit) macro "eval_prec " p:prec:max : term => return quote (← evalPrec p) def evalOptPrec : Option Syntax → MacroM Nat | some prec => evalPrec prec | none => return 0 /- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):numLit) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):numLit) macro "eval_prio " p:prio:max : term => return quote (← evalPrio p) def evalOptPrio : Option Syntax → MacroM Nat | some prio => evalPrio prio | none => return eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.predLt hz let sepStx := a.get ⟨i.pred, Nat.ltTrans this h⟩ filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax.SepArray def getElems {sep} (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance (sep) : CoeTail (SepArray sep) (Array Syntax) where coe := getElems end Lean.Syntax.SepArray /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /- Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : OptionM String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop 1 "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result def expandInterpolatedStr (interpStr : Syntax) (type : Syntax) (toTypeFn : Syntax) : MacroM Syntax := do let ref := interpStr let r ← expandInterpolatedStrChunks interpStr.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace Meta.Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true iota : Bool := true proj : Bool := true decide : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true end Meta.Simp end Lean
a414fb1164dc6fa88ea76dc20791469d74a40001
88892181780ff536a81e794003fe058062f06758
/src/algorithms/data/array.lean
1d3f32e9412e6a7d90594f453e864a0ea4553a35
[]
no_license
AtnNn/lean-sandbox
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
8c68afbdc09213173aef1be195da7a9a86060a97
refs/heads/master
1,623,004,395,876
1,579,969,507,000
1,579,969,507,000
146,666,368
0
0
null
null
null
null
UTF-8
Lean
false
false
1,022
lean
import tactic.suggest import lib.attempt import logic.function import tactic.interactive namespace algorithms structure array (α : Type) := (size : nat) (get : fin size → α) namespace array def index {α : Type} (a : array α) := fin a.size def set {α} (a : array α) (i : a.index) (v : α) : array α := mk a.size $ λ j, if j = i then v else a.get j lemma empty_eq_empty (a b : array nat) (h: a.size = 0) (g : b.size = 0) : a = b := begin cases a, cases b, cases h, cases g, rw array.mk.inj_eq, split, { refl }, { apply function.hfunext rfl, intros a, exact fin.elim0 a } end lemma set_set_eq_set {α} {a : array α} {x y : α} {i : a.index} : set (set a i y) i x = set a i x := begin unfold set, rw array.mk.inj_eq, split, { refl }, { apply function.hfunext rfl, intros b c h, rw eq_of_heq h, by_cases he : c = i, { rw if_pos he, rw if_pos he }, { rw if_neg he, rw if_neg he, dunfold array.set at *, simp [he] } } end end array end algorithms
d8e0a4df9e41fea76bc4eb5b3e52fbe31798e20b
83c8119e3298c0bfc53fc195c41a6afb63d01513
/library/init/meta/well_founded_tactics.lean
ea247737c0d981c530e2bdc8e7a57607e9973a95
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
6,560
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta init.data.sigma.lex init.data.nat.lemmas init.data.list.instances import init.data.list.qsort init.data.string.instances /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_of_zero_lt_left (a b : nat) (h : 0 < b) : a < a + b := suffices a + 0 < a + b, by {simp at this, assumption}, by {apply nat.add_lt_add_left, assumption} /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.zero_lt_one_add (a : nat) : 0 < 1 + a := suffices 0 < a + 1, by {simp [add_comm], assumption}, nat.zero_lt_succ _ /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_right (a b c : nat) : a < b → a < b + c := λ h, lt_of_lt_of_le h (nat.le_add_right _ _) /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_left (a b c : nat) : a < b → a < c + b := λ h, lt_of_lt_of_le h (nat.le_add_left _ _) namespace well_founded_tactics open tactic private meta def clear_wf_rec_goal_aux : list expr → tactic unit | [] := return () | (h::hs) := clear_wf_rec_goal_aux hs >> try (guard (h.local_pp_name.is_internal || h.is_aux_decl) >> clear h) meta def clear_internals : tactic unit := local_context >>= clear_wf_rec_goal_aux meta def unfold_wf_rel : tactic unit := dunfold_target [``has_well_founded.r] {fail_if_unchanged := ff} meta def is_psigma_mk : expr → tactic (expr × expr) | `(psigma.mk %%a %%b) := return (a, b) | _ := failed meta def process_lex : tactic unit → tactic unit | tac := do t ← target >>= whnf, if t.is_napp_of `psigma.lex 6 then let a := t.app_fn.app_arg in let b := t.app_arg in do (a₁, a₂) ← is_psigma_mk a, (b₁, b₂) ← is_psigma_mk b, (is_def_eq a₁ b₁ >> `[apply psigma.lex.right] >> process_lex tac) <|> (`[apply psigma.lex.left] >> tac) else tac private meta def unfold_sizeof_measure : tactic unit := dunfold_target [``sizeof_measure, ``measure, ``inv_image] {fail_if_unchanged := ff} private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n ff, add_simps s' ns private meta def collect_sizeof_lemmas (e : expr) : tactic simp_lemmas := e.mfold simp_lemmas.mk $ λ c d s, if c.is_constant then match c.const_name with | name.mk_string "sizeof" p := do eqns ← get_eqn_lemmas_for tt c.const_name, add_simps s eqns | _ := return s end else return s private meta def unfold_sizeof_loop : tactic unit := do dunfold_target [``sizeof, ``has_sizeof.sizeof] {fail_if_unchanged := ff}, S ← target >>= collect_sizeof_lemmas, (simp_target S >> unfold_sizeof_loop) <|> try `[simp] meta def unfold_sizeof : tactic unit := unfold_sizeof_measure >> unfold_sizeof_loop /- The following section should be removed as soon as we implement the algebraic normalizer. -/ section simple_dec_tac open tactic expr private meta def collect_add_args : expr → list expr | `(%%a + %%b) := collect_add_args a ++ collect_add_args b | e := [e] private meta def mk_nat_add : list expr → tactic expr | [] := to_expr ``(0) | [a] := return a | (a::as) := do rs ← mk_nat_add as, to_expr ``(%%a + %%rs) private meta def mk_nat_add_add : list expr → list expr → tactic expr | [] b := mk_nat_add b | a [] := mk_nat_add a | a b := do t ← mk_nat_add a, s ← mk_nat_add b, to_expr ``(%%t + %%s) private meta def get_add_fn (e : expr) : expr := if is_napp_of e `has_add.add 4 then e.app_fn.app_fn else e private meta def prove_eq_by_perm (a b : expr) : tactic expr := (is_def_eq a b >> to_expr ``(eq.refl %%a)) <|> perm_ac (get_add_fn a) `(nat.add_assoc) `(nat.add_comm) a b private meta def num_small_lt (a b : expr) : bool := if a = b then ff else if is_napp_of a `has_one.one 2 then tt else if is_napp_of b `has_one.one 2 then ff else a.lt b private meta def sort_args (args : list expr) : list expr := args.qsort num_small_lt meta def cancel_nat_add_lt : tactic unit := do `(%%lhs < %%rhs) ← target, ty ← infer_type lhs >>= whnf, guard (ty = `(nat)), let lhs_args := collect_add_args lhs, let rhs_args := collect_add_args rhs, let common := lhs_args.bag_inter rhs_args, if common = [] then return () else do let lhs_rest := lhs_args.diff common, let rhs_rest := rhs_args.diff common, new_lhs ← mk_nat_add_add common (sort_args lhs_rest), new_rhs ← mk_nat_add_add common (sort_args rhs_rest), lhs_pr ← prove_eq_by_perm lhs new_lhs, rhs_pr ← prove_eq_by_perm rhs new_rhs, target_pr ← to_expr ``(congr (congr_arg (<) %%lhs_pr) %%rhs_pr), new_target ← to_expr ``(%%new_lhs < %%new_rhs), replace_target new_target target_pr, `[apply nat.add_lt_add_left] <|> `[apply nat.lt_add_of_zero_lt_left] meta def check_target_is_value_lt : tactic unit := do `(%%lhs < %%rhs) ← target, guard lhs.is_numeral meta def trivial_nat_lt : tactic unit := comp_val <|> `[apply nat.zero_lt_one_add] <|> assumption <|> (do check_target_is_value_lt, (`[apply nat.lt_add_right] >> trivial_nat_lt) <|> (`[apply nat.lt_add_left] >> trivial_nat_lt)) <|> failed end simple_dec_tac meta def default_dec_tac : tactic unit := abstract $ do clear_internals, unfold_wf_rel, -- The next line was adapted from code in mathlib by Scott Morrison. -- Because `unfold_sizeof` could actually discharge the goal, add a test -- using `done` to detect this. process_lex (unfold_sizeof >> (done <|> (cancel_nat_add_lt >> trivial_nat_lt))) end well_founded_tactics /-- Argument for using_well_founded The tactic `rel_tac` has to synthesize an element of type (has_well_founded A). The two arguments are: a local representing the function being defined by well founded recursion, and a list of recursive equations. The equations can be used to decide which well founded relation should be used. The tactic `dec_tac` has to synthesize decreasing proofs. -/ meta structure well_founded_tactics := (rel_tac : expr → list expr → tactic unit := λ _ _, tactic.apply_instance) (dec_tac : tactic unit := well_founded_tactics.default_dec_tac) meta def well_founded_tactics.default : well_founded_tactics := {}
c4029e838d8ae5ff5cb746f29819c78f651e7541
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_881.lean
cdb3bbba13f14acba356a581658dfd73ea584a47
[]
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
181
lean
import data.set.function variables {α β : Type*} variable f : α → β variables (s : set α) (t : set β) -- BEGIN example : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := sorry -- END
c8dbe895d3eaee5867eb9bf813ac5087f6460a0e
0003047346476c031128723dfd16fe273c6bc605
/src/data/gaussian_int.lean
410f54f70cb0eb6897a68bdff105387a1be19551
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,115
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes The gaussian integers ℤ[i]. -/ import number_theory.pell data.complex.basic algebra.euclidean_domain algebra.associated open zsqrtd complex @[reducible] def gaussian_int : Type := zsqrtd (-1) local notation `ℤ[i]` := gaussian_int namespace gaussian_int instance : has_repr ℤ[i] := ⟨λ x, "⟨" ++ repr x.re ++ ", " ++ repr x.im ++ "⟩"⟩ instance : comm_ring ℤ[i] := zsqrtd.comm_ring def to_complex (x : ℤ[i]) : ℂ := x.re + x.im * I instance : has_coe (ℤ[i]) ℂ := ⟨to_complex⟩ lemma to_complex_def (x : ℤ[i]) : (x : ℂ) = x.re + x.im * I := rfl lemma to_complex_def' (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ) = x + y * I := by simp [to_complex_def] lemma to_complex_def₂ (x : ℤ[i]) : (x : ℂ) = ⟨x.re, x.im⟩ := by apply complex.ext; simp [to_complex_def] instance to_complex.is_ring_hom : is_ring_hom to_complex:= by refine_struct {..}; intros; apply complex.ext; simp [to_complex] instance : is_ring_hom (coe : ℤ[i] → ℂ) := to_complex.is_ring_hom @[simp] lemma to_real_re (x : ℤ[i]) : ((x.re : ℤ) : ℝ) = (x : ℂ).re := by simp [to_complex_def] @[simp] lemma to_real_im (x : ℤ[i]) : ((x.im : ℤ) : ℝ) = (x : ℂ).im := by simp [to_complex_def] @[simp] lemma to_complex_re (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).re = x := by simp [to_complex_def] @[simp] lemma to_complex_im (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).im = y := by simp [to_complex_def] @[simp] lemma to_complex_add (x y : ℤ[i]) : ((x + y : ℤ[i]) : ℂ) = x + y := is_ring_hom.map_add coe @[simp] lemma to_complex_mul (x y : ℤ[i]) : ((x * y : ℤ[i]) : ℂ) = x * y := is_ring_hom.map_mul coe @[simp] lemma to_complex_one : ((1 : ℤ[i]) : ℂ) = 1 := is_ring_hom.map_one coe @[simp] lemma to_complex_zero : ((0 : ℤ[i]) : ℂ) = 0 := is_ring_hom.map_zero coe @[simp] lemma to_complex_neg (x : ℤ[i]) : ((-x : ℤ[i]) : ℂ) = -x := is_ring_hom.map_neg coe @[simp] lemma to_complex_sub (x y : ℤ[i]) : ((x - y : ℤ[i]) : ℂ) = x - y := is_ring_hom.map_sub coe @[simp] lemma to_complex_inj {x y : ℤ[i]} : (x : ℂ) = y ↔ x = y := by cases x; cases y; simp [to_complex_def₂] @[simp] lemma to_complex_eq_zero {x : ℤ[i]} : (x : ℂ) = 0 ↔ x = 0 := by rw [← to_complex_zero, to_complex_inj] @[simp] lemma nat_cast_real_norm (x : ℤ[i]) : (x.norm : ℝ) = (x : ℂ).norm_sq := by rw [norm, norm_sq]; simp @[simp] lemma nat_cast_complex_norm (x : ℤ[i]) : (x.norm : ℂ) = (x : ℂ).norm_sq := by cases x; rw [norm, norm_sq]; simp lemma norm_nonneg (x : ℤ[i]) : 0 ≤ norm x := norm_nonneg trivial _ @[simp] lemma norm_eq_zero {x : ℤ[i]} : norm x = 0 ↔ x = 0 := by rw [← @int.cast_inj ℝ _ _ _]; simp lemma norm_pos {x : ℤ[i]} : 0 < norm x ↔ x ≠ 0 := by rw [lt_iff_le_and_ne, ne.def, eq_comm, norm_eq_zero]; simp [norm_nonneg] @[simp] lemma coe_nat_abs_norm (x : ℤ[i]) : (x.norm.nat_abs : ℤ) = x.norm := int.nat_abs_of_nonneg (norm_nonneg _) @[simp] lemma nat_cast_nat_abs_norm {α : Type*} [ring α] (x : ℤ[i]) : (x.norm.nat_abs : α) = x.norm := by rw [← int.cast_coe_nat, coe_nat_abs_norm] lemma nat_abs_norm_eq (x : ℤ[i]) : x.norm.nat_abs = x.re.nat_abs * x.re.nat_abs + x.im.nat_abs * x.im.nat_abs := int.coe_nat_inj $ begin simp, simp [norm] end protected def div (x y : ℤ[i]) : ℤ[i] := ⟨round ((x * conj y).re / norm y : ℚ), round ((x * conj y).im / norm y : ℚ)⟩ instance : has_div ℤ[i] := ⟨gaussian_int.div⟩ lemma div_def (x y : ℤ[i]) : x / y = ⟨round ((x * conj y).re / norm y : ℚ), round ((x * conj y).im / norm y : ℚ)⟩ := rfl lemma to_complex_div_re (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).re = round ((x / y : ℂ).re) := by rw [div_def, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] lemma to_complex_div_im (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).im = round ((x / y : ℂ).im) := by rw [div_def, ← @rat.cast_round ℝ _ _, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] local notation `abs'` := _root_.abs lemma norm_sq_le_norm_sq_of_re_le_of_im_le {x y : ℂ} (hre : abs' x.re ≤ abs' y.re) (him : abs' x.im ≤ abs' y.im) : x.norm_sq ≤ y.norm_sq := by rw [norm_sq, norm_sq, ← _root_.abs_mul_self, _root_.abs_mul, ← _root_.abs_mul_self y.re, _root_.abs_mul y.re, ← _root_.abs_mul_self x.im, _root_.abs_mul x.im, ← _root_.abs_mul_self y.im, _root_.abs_mul y.im]; exact (add_le_add (mul_self_le_mul_self (abs_nonneg _) hre) (mul_self_le_mul_self (abs_nonneg _) him)) lemma norm_sq_div_sub_div_lt_one (x y : ℤ[i]) : ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq < 1 := calc ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq = ((x / y : ℂ).re - ((x / y : ℤ[i]) : ℂ).re + ((x / y : ℂ).im - ((x / y : ℤ[i]) : ℂ).im) * I : ℂ).norm_sq : congr_arg _ $ by apply complex.ext; simp ... ≤ (1 / 2 + 1 / 2 * I).norm_sq : have abs' (2 / (2 * 2) : ℝ) = 1 / 2, by rw _root_.abs_of_nonneg; norm_num, norm_sq_le_norm_sq_of_re_le_of_im_le (by rw [to_complex_div_re]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).re) (by rw [to_complex_div_im]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).im) ... < 1 : by simp [norm_sq]; norm_num protected def mod (x y : ℤ[i]) : ℤ[i] := x - y * (x / y) instance : has_mod ℤ[i] := ⟨gaussian_int.mod⟩ lemma mod_def (x y : ℤ[i]) : x % y = x - y * (x / y) := rfl lemma norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm < y.norm := have (y : ℂ) ≠ 0, by rwa [ne.def, ← to_complex_zero, to_complex_inj], (@int.cast_lt ℝ _ _ _).1 $ calc ↑(norm (x % y)) = (x - y * (x / y : ℤ[i]) : ℂ).norm_sq : by simp [mod_def] ... = (y : ℂ).norm_sq * (((x / y) - (x / y : ℤ[i])) : ℂ).norm_sq : by rw [← norm_sq_mul, mul_sub, mul_div_cancel' _ this] ... < (y : ℂ).norm_sq * 1 : mul_lt_mul_of_pos_left (norm_sq_div_sub_div_lt_one _ _) (norm_sq_pos.2 this) ... = norm y : by simp lemma nat_abs_norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm.nat_abs < y.norm.nat_abs := int.coe_nat_lt.1 (by simp [-int.coe_nat_lt, norm_mod_lt x hy]) lemma norm_le_norm_mul_left (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (norm x).nat_abs ≤ (norm (x * y)).nat_abs := by rw [norm_mul, int.nat_abs_mul]; exact le_mul_of_ge_one_right' (nat.zero_le _) (int.coe_nat_le.1 (by rw [coe_nat_abs_norm]; exact norm_pos.2 hy)) instance : nonzero_comm_ring ℤ[i] := { zero_ne_one := dec_trivial, ..gaussian_int.comm_ring } instance : euclidean_domain ℤ[i] := { quotient := (/), remainder := (%), quotient_zero := λ _, by simp [div_def]; refl, quotient_mul_add_remainder_eq := λ _ _, by simp [mod_def], r := _, r_well_founded := measure_wf (int.nat_abs ∘ norm), remainder_lt := nat_abs_norm_mod_lt, mul_left_not_lt := λ a b hb0, not_lt_of_ge $ norm_le_norm_mul_left a hb0 } end gaussian_int
762a4a038bd25e70d2b52bd81a3a8afd5fa73d8a
ec62863c729b7eedee77b86d974f2c529fa79d25
/22/b.lean
4ddbbda064ce04362a6ba4f97abc6f4137e789c1
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
1,313
lean
import Std.Data.HashSet open Std def parseInput (input : String) : List Nat × List Nat:= match input.trim.splitOn "\n\n" with | [p1, p2] => (((p1.splitOn "\n").drop 1).map String.toNat!, ((p2.splitOn "\n").drop 1).map String.toNat!) | _ => panic! "invalid parse" def score (deck : List Nat) : Nat := let N := deck.length deck.enum.foldl (λ sum ⟨i, val⟩ => sum + (N-i) * val) 0 partial def play' (seen : HashSet (List Nat × List Nat)) (d₁ d₂ : List Nat) : Bool := if seen.contains (d₁, d₂) then false else match d₁, d₂ with | [], xs => true | xs, [] => false | (x :: xs), (y :: ys) => let winner2 := if xs.length ≥ x ∧ ys.length ≥ y then play' HashSet.empty (xs.take x) (ys.take y) else x < y if winner2 then play' (seen.insert (d₁, d₂)) xs (ys ++ [y, x]) else play' (seen.insert (d₁, d₂)) (xs ++ [x, y]) ys partial def play : List Nat → List Nat → Nat | [], xs => score xs | xs, [] => score xs | (x :: xs), (y :: ys) => let winner2 := if xs.length ≥ x ∧ ys.length ≥ y then play' HashSet.empty (xs.take x) (ys.take y) else x < y if winner2 then play xs (ys ++ [y, x]) else play (xs ++ [x, y]) ys def main : IO Unit := do let input ← IO.FS.readFile "a.in" let decks := parseInput input IO.print s!"{play decks.1 decks.2}\n"
66ac6790e83604f327767a4ec950d5da04981f81
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/set/intervals/surj_on.lean
06d760b5d1008f9d848c53b8a3fc97edc21561d7
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
3,977
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import data.set.intervals.basic import data.set.function /-! # Monotone surjective functions are surjective on intervals A monotone surjective function sends any interval in the domain onto the interval with corresponding endpoints in the range. This is expressed in this file using `set.surj_on`, and provided for all permutations of interval endpoints. -/ variables {α : Type*} {β : Type*} [linear_order α] [partial_order β] {f : α → β} open set function lemma surj_on_Ioo_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) (a b : α) : surj_on f (Ioo a b) (Ioo (f a) (f b)) := begin classical, intros p hp, rcases h_surj p with ⟨x, rfl⟩, refine ⟨x, mem_Ioo.2 _, rfl⟩, by_contra h, cases not_and_distrib.mp h with ha hb, { exact has_lt.lt.false (lt_of_lt_of_le hp.1 (h_mono (not_lt.mp ha))) }, { exact has_lt.lt.false (lt_of_le_of_lt (h_mono (not_lt.mp hb)) hp.2) } end lemma surj_on_Ico_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) (a b : α) : surj_on f (Ico a b) (Ico (f a) (f b)) := begin obtain hab | hab := lt_or_le a b, { intros p hp, rcases mem_Ioo_or_eq_left_of_mem_Ico hp with hp'|hp', { rw hp', exact ⟨a, left_mem_Ico.mpr hab, rfl⟩ }, { have := surj_on_Ioo_of_monotone_surjective h_mono h_surj a b hp', cases this with x hx, exact ⟨x, Ioo_subset_Ico_self hx.1, hx.2⟩ } }, { rw Ico_eq_empty (h_mono hab).not_lt, exact surj_on_empty f _ } end lemma surj_on_Ioc_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) (a b : α) : surj_on f (Ioc a b) (Ioc (f a) (f b)) := begin convert @surj_on_Ico_of_monotone_surjective _ _ _ _ _ h_mono.order_dual h_surj b a; simp end -- to see that the hypothesis `a ≤ b` is necessary, consider a constant function lemma surj_on_Icc_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) {a b : α} (hab : a ≤ b) : surj_on f (Icc a b) (Icc (f a) (f b)) := begin rcases lt_or_eq_of_le hab with hab|hab, { intros p hp, rcases mem_Ioo_or_eq_endpoints_of_mem_Icc hp with hp'|⟨hp'|hp'⟩, { rw hp', refine ⟨a, left_mem_Icc.mpr (le_of_lt hab), rfl⟩ }, { rw hp', refine ⟨b, right_mem_Icc.mpr (le_of_lt hab), rfl⟩ }, { have := surj_on_Ioo_of_monotone_surjective h_mono h_surj a b hp', cases this with x hx, exact ⟨x, Ioo_subset_Icc_self hx.1, hx.2⟩ } }, { simp only [hab, Icc_self], intros _ hp, exact ⟨b, mem_singleton _, (mem_singleton_iff.mp hp).symm⟩ } end lemma surj_on_Ioi_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : surj_on f (Ioi a) (Ioi (f a)) := begin classical, intros p hp, rcases h_surj p with ⟨x, rfl⟩, refine ⟨x, _, rfl⟩, simp only [mem_Ioi], by_contra h, exact has_lt.lt.false (lt_of_lt_of_le hp (h_mono (not_lt.mp h))) end lemma surj_on_Iio_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : surj_on f (Iio a) (Iio (f a)) := @surj_on_Ioi_of_monotone_surjective _ _ _ _ _ (monotone.order_dual h_mono) h_surj a lemma surj_on_Ici_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : surj_on f (Ici a) (Ici (f a)) := begin intros p hp, rw [mem_Ici, le_iff_lt_or_eq] at hp, rcases hp with hp'|hp', { cases (surj_on_Ioi_of_monotone_surjective h_mono h_surj a hp') with x hx, exact ⟨x, Ioi_subset_Ici_self hx.1, hx.2⟩ }, { rw ← hp', refine ⟨a, left_mem_Ici, rfl⟩ } end lemma surj_on_Iic_of_monotone_surjective (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : surj_on f (Iic a) (Iic (f a)) := @surj_on_Ici_of_monotone_surjective _ _ _ _ _ (monotone.order_dual h_mono) h_surj a
aebec01f7e7366873c98b41ccc94b51f7b2b0c68
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/structInst1.lean
970d72019174e6a5eb174e3a97777f06adc66a34
[ "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
786
lean
structure A where x : Nat w : Nat structure B extends A where y : Nat structure C extends B where z : Nat def f1 (c : C) (a : A) : C := { c with toA := a, x := 0 } -- Error, `toA` and `x` are both updates to field `x` def f2 (c : C) (a : A) : C := { c with toA := a } def f3 (c : C) (a : A) : C := { a, c with x := 0 } theorem ex1 (a : A) (c : C) : (f3 c a).x = 0 := rfl theorem ex2 (a : A) (c : C) : (f3 c a).w = a.w := rfl def f4 (c : C) (a : A) : C := { c, a with x := 0 } -- TODO: generate error that `a` was not used? theorem ex3 (a : A) (c : C) : (f4 c a).w = c.w := rfl theorem ex4 (a : A) (c : C) : (f4 c a).x = 0 := rfl def f5 (c : C) (a : A) := { c, a with x := 0 } #check f5 def f6 (c : C) (a : A) := { a, c with x := 0 } #check f6
52ff84076c6c8e284b8c4523595d5a144effec70
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eq13.lean
5fdba119f90fe61cdd10eab84f48a2bf364ea372
[ "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
293
lean
open nat definition f : nat → nat → nat | n 0 := 0 | 0 n := 1 | n m := arbitrary nat theorem f_zero_right : ∀ a, f a 0 = 0 | 0 := rfl | (succ a) := rfl theorem f_zero_succ (a : nat) : f 0 (a+1) = 1 := rfl theorem f_succ_succ (a b : nat) : f (a+1) (b+1) = arbitrary nat := rfl
e3d1263d065447ea8a05900c43baca5df748c8c5
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/lie/matrix.lean
0bc8aef9940a8ae3de45df04d3574e5f2bdb1c0d
[ "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
3,355
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import linear_algebra.matrix /-! # Lie algebras of matrices An important class of Lie algebras are those arising from the associative algebra structure on square matrices over a commutative ring. This file provides some very basic definitions whose primary value stems from their utility when constructing the classical Lie algebras using matrices. ## Main definitions * `lie_equiv_matrix'` * `matrix.lie_conj` * `matrix.reindex_lie_equiv` ## Tags lie algebra, matrix -/ universes u v w w₁ w₂ section matrices open_locale matrix variables {R : Type u} [comm_ring R] variables {n : Type w} [decidable_eq n] [fintype n] /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the Lie algebra structures. -/ def lie_equiv_matrix' : module.End R (n → R) ≃ₗ⁅R⁆ matrix n n R := { map_lie' := λ T S, begin let f := @linear_map.to_matrix' R _ n n _ _ _, change f (T.comp S - S.comp T) = (f T) * (f S) - (f S) * (f T), have h : ∀ (T S : module.End R _), f (T.comp S) = (f T) ⬝ (f S) := linear_map.to_matrix'_comp, rw [linear_equiv.map_sub, h, h, matrix.mul_eq_mul, matrix.mul_eq_mul], end, ..linear_map.to_matrix' } @[simp] lemma lie_equiv_matrix'_apply (f : module.End R (n → R)) : lie_equiv_matrix' f = f.to_matrix' := rfl @[simp] lemma lie_equiv_matrix'_symm_apply (A : matrix n n R) : (@lie_equiv_matrix' R _ n _ _).symm A = A.to_lin' := rfl /-- An invertible matrix induces a Lie algebra equivalence from the space of matrices to itself. -/ noncomputable def matrix.lie_conj (P : matrix n n R) (h : is_unit P) : matrix n n R ≃ₗ⁅R⁆ matrix n n R := ((@lie_equiv_matrix' R _ n _ _).symm.trans (P.to_linear_equiv' h).lie_conj).trans lie_equiv_matrix' @[simp] lemma matrix.lie_conj_apply (P A : matrix n n R) (h : is_unit P) : P.lie_conj h A = P ⬝ A ⬝ P⁻¹ := by simp [linear_equiv.conj_apply, matrix.lie_conj, linear_map.to_matrix'_comp, linear_map.to_matrix'_to_lin'] @[simp] lemma matrix.lie_conj_symm_apply (P A : matrix n n R) (h : is_unit P) : (P.lie_conj h).symm A = P⁻¹ ⬝ A ⬝ P := by simp [linear_equiv.symm_conj_apply, matrix.lie_conj, linear_map.to_matrix'_comp, linear_map.to_matrix'_to_lin'] /-- For square matrices, the natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence of Lie algebras. -/ def matrix.reindex_lie_equiv {m : Type w₁} [decidable_eq m] [fintype m] (e : n ≃ m) : matrix n n R ≃ₗ⁅R⁆ matrix m m R := { map_lie' := λ M N, by simp only [lie_ring.of_associative_ring_bracket, matrix.reindex_mul, matrix.mul_eq_mul, linear_equiv.map_sub, linear_equiv.to_fun_eq_coe], ..(matrix.reindex_linear_equiv e e) } @[simp] lemma matrix.reindex_lie_equiv_apply {m : Type w₁} [decidable_eq m] [fintype m] (e : n ≃ m) (M : matrix n n R) : matrix.reindex_lie_equiv e M = λ i j, M (e.symm i) (e.symm j) := rfl @[simp] lemma matrix.reindex_lie_equiv_symm_apply {m : Type w₁} [decidable_eq m] [fintype m] (e : n ≃ m) (M : matrix m m R) : (matrix.reindex_lie_equiv e).symm M = λ i j, M (e i) (e j) := rfl end matrices
7d0c9e764b4125a9b13b10e69bb571553b7508c3
bc6b522ca01a7d1eddd58687225d93b4bb90fc65
/test/simple2.lean
a37f73132cd9f80048bd3c1008b1cd73ea39e18e
[]
no_license
cipher1024/olean-rs
c8fcf0a47570e922be4dfd33b5f3b6ac9571e6f7
4707d26177733753ee4195b4b0883b4089e85f11
refs/heads/master
1,588,599,805,382
1,557,346,494,000
1,557,346,494,000
179,171,289
1
0
null
1,554,245,858,000
1,554,245,858,000
null
UTF-8
Lean
false
false
87
lean
import system.io import data.buffer def main : io unit := io.put_str_ln "hello world"
9f1fc13fdfcdf1285430a135d1fa2fb8ede6cbc9
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/111.lean
dc2a3636fa5fcce4da35d2cc64ec315238b62893
[ "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
225
lean
import Lean new_frontend open Lean #check mkNullNode -- Lean.Syntax #check mkNullNode #[] -- Lean.Syntax #check @mkNullNode #check let f : Array Syntax → Syntax := @mkNullNode; f #[] #check let f := @mkNullNode; f #[]
8bc02894160fa8ea26076335a929a1d752e0912d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/congr.lean
0a01c11f4cf308aa65c9aeaa92b98e107f1b8d9d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,091
lean
import algebra.group.defs import data.subtype import tactic.congr section congr open tactic.interactive example (c : Prop → Prop → Prop → Prop) (x x' y z z' : Prop) (h₀ : x ↔ x') (h₁ : z ↔ z') : c x y z ↔ c x' y z' := begin congr', { guard_target x = x', ext, assumption }, { guard_target z = z', ext, assumption }, end example {α β γ δ} {F : ∀{α β}, (α → β) → γ → δ} {f g : α → β} {s : γ} (h : ∀ (x : α), f x = g x) : F f s = F g s := by { congr' with x, apply_assumption } example {α β} {f : _ → β} {x y : {x : {x : α // x = x} // x = x} } (h : x.1 = y.1) : f x = f y := by { congr' with x : 1, exact h } example {α β} {F : _ → β} {f g : {f : α → β // f = f} } (h : ∀ x : α, (f : α → β) x = (g : α → β) x) : F f = F g := begin rcongr x, revert x, do { t ← tactic.target, s ← tactic.get_local_type `h, guard (t =ₐ s) }, exact h end example {ls : list ℕ} : ls.map (λ x, (ls.map (λ y, 1 + y)).sum + 1) = ls.map (λ x, (ls.map (λ y, nat.succ y)).sum + 1) := begin rcongr x y, guard_target (1 + y = y.succ), rw [nat.add_comm], end example {ls : list ℕ} {f g : ℕ → ℕ} {h : ∀ x, f x = g x} : ls.map (λ x, f x + 3) = ls.map (λ x, g x + 3) := begin rcongr x, exact h x end -- succeed when either `ext` or `congr` can close the goal example : () = () := by rcongr example : 0 = 0 := by rcongr example {α} (a : α) : a = a := by congr' example {α} (a b : α) (h : false) : a = b := by { fail_if_success {congr'}, cases h } end congr section convert_to example {α} [add_comm_monoid α] {a b c d : α} (H : a = c) (H' : b = d) : a + b = d + c := by {convert_to c + d = _ using 2, rw[add_comm]} example {α} [add_comm_monoid α] {a b c d : α} (H : a = c) (H' : b = d) : a + b = d + c := by {convert_to c + d = _ using 0, congr' 2, rw[add_comm]} example {α} [add_comm_monoid α] [partial_order α] {a b c d e f g : α} : (a + b) + (c + d) + (e + f) + g ≤ a + d + e + f + c + g + b := by {ac_change a + d + e + f + c + g + b ≤ _, refl} end convert_to
1bcba64cc6b2346e7504bc87df22ef97fc7fdf92
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Data/Options.lean
59342b335ef36b1af228d6c2b987cbb8f50849f0
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,871
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich and Leonardo de Moura -/ import Lean.Data.KVMap namespace Lean def Options := KVMap def Options.empty : Options := {} instance : Inhabited Options where default := {} instance : ToString Options := inferInstanceAs (ToString KVMap) structure OptionDecl where defValue : DataValue group : String := "" descr : String := "" deriving Inhabited def OptionDecls := NameMap OptionDecl instance : Inhabited OptionDecls := ⟨({} : NameMap OptionDecl)⟩ private def initOptionDeclsRef : IO (IO.Ref OptionDecls) := IO.mkRef (mkNameMap OptionDecl) @[builtinInit initOptionDeclsRef] private constant optionDeclsRef : IO.Ref OptionDecls @[export lean_register_option] def registerOption (name : Name) (decl : OptionDecl) : IO Unit := do let decls ← optionDeclsRef.get if decls.contains name then throw $ IO.userError s!"invalid option declaration '{name}', option already exists" optionDeclsRef.set $ decls.insert name decl def getOptionDecls : IO OptionDecls := optionDeclsRef.get @[export lean_get_option_decls_array] def getOptionDeclsArray : IO (Array (Name × OptionDecl)) := do let decls ← getOptionDecls pure $ decls.fold (fun (r : Array (Name × OptionDecl)) k v => r.push (k, v)) #[] def getOptionDecl (name : Name) : IO OptionDecl := do let decls ← getOptionDecls let (some decl) ← pure (decls.find? name) | throw $ IO.userError s!"unknown option '{name}'" pure decl def getOptionDefaulValue (name : Name) : IO DataValue := do let decl ← getOptionDecl name pure decl.defValue def getOptionDescr (name : Name) : IO String := do let decl ← getOptionDecl name pure decl.descr def setOptionFromString (opts : Options) (entry : String) : IO Options := do let ps := (entry.splitOn "=").map String.trim let [key, val] ← pure ps | throw $ IO.userError "invalid configuration option entry, it must be of the form '<key> = <value>'" let key := Name.mkSimple key let defValue ← getOptionDefaulValue key match defValue with | DataValue.ofString v => pure $ opts.setString key val | DataValue.ofBool v => if key == `true then pure $ opts.setBool key true else if key == `false then pure $ opts.setBool key false else throw $ IO.userError s!"invalid Bool option value '{val}'" | DataValue.ofName v => pure $ opts.setName key val.toName | DataValue.ofNat v => match val.toNat? with | none => throw (IO.userError s!"invalid Nat option value '{val}'") | some v => pure $ opts.setNat key v | DataValue.ofInt v => match val.toInt? with | none => throw (IO.userError s!"invalid Int option value '{val}'") | some v => pure $ opts.setInt key v builtin_initialize registerOption `verbose { defValue := true, group := "", descr := "disable/enable verbose messages" } registerOption `timeout { defValue := DataValue.ofNat 0, group := "", descr := "the (deterministic) timeout is measured as the maximum of memory allocations (in thousands) per task, the default is unbounded" } registerOption `maxMemory { defValue := DataValue.ofNat 2048, group := "", descr := "maximum amount of memory available for Lean in megabytes" } class MonadOptions (m : Type → Type) where getOptions : m Options export MonadOptions (getOptions) instance (m n) [MonadLift m n] [MonadOptions m] : MonadOptions n where getOptions := liftM (getOptions : m _) variables {m} [Monad m] [MonadOptions m] def getBoolOption (k : Name) (defValue := false) : m Bool := do let opts ← getOptions pure $ opts.getBool k defValue def getNatOption (k : Name) (defValue := 0) : m Nat := do let opts ← getOptions pure $ opts.getNat k defValue end Lean
4570dfda4e677fcad9da6ef04a8e0eedbc759ea2
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/hom/group_instances.lean
e1b70677df7757f49f49a4a2e6c7a635f1044c8f
[ "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
10,910
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.group_power.basic /-! # Instances on spaces of monoid and group morphisms We endow the space of monoid morphisms `M →* N` with a `comm_monoid` structure when the target is commutative, through pointwise multiplication, and with a `comm_group` structure when the target is a commutative group. We also prove the same instances for additive situations. Since these structures permit morphisms of morphisms, we also provide some composition-like operations. Finally, we provide the `ring` structure on `add_monoid.End`. -/ universes uM uN uP uQ variables {M : Type uM} {N : Type uN} {P : Type uP} {Q : Type uQ} /-- `(M →* N)` is a `comm_monoid` if `N` is commutative. -/ @[to_additive "`(M →+ N)` is an `add_comm_monoid` if `N` is commutative."] instance [mul_one_class M] [comm_monoid N] : comm_monoid (M →* N) := { mul := (*), mul_assoc := by intros; ext; apply mul_assoc, one := 1, one_mul := by intros; ext; apply one_mul, mul_one := by intros; ext; apply mul_one, mul_comm := by intros; ext; apply mul_comm, npow := λ n f, { to_fun := λ x, (f x) ^ n, map_one' := by simp, map_mul' := λ x y, by simp [mul_pow] }, npow_zero' := λ f, by { ext x, simp }, npow_succ' := λ n f, by { ext x, simp [pow_succ] } } /-- If `G` is a commutative group, then `M →* G` is a commutative group too. -/ @[to_additive "If `G` is an additive commutative group, then `M →+ G` is an additive commutative group too."] instance {M G} [mul_one_class M] [comm_group G] : comm_group (M →* G) := { inv := has_inv.inv, div := has_div.div, div_eq_mul_inv := by { intros, ext, apply div_eq_mul_inv }, mul_left_inv := by intros; ext; apply mul_left_inv, zpow := λ n f, { to_fun := λ x, (f x) ^ n, map_one' := by simp, map_mul' := λ x y, by simp [mul_zpow] }, zpow_zero' := λ f, by { ext x, simp }, zpow_succ' := λ n f, by { ext x, simp [zpow_of_nat, pow_succ] }, zpow_neg' := λ n f, by { ext x, simp }, ..monoid_hom.comm_monoid } instance [add_comm_monoid M] : add_comm_monoid (add_monoid.End M) := add_monoid_hom.add_comm_monoid instance [add_comm_monoid M] : semiring (add_monoid.End M) := { zero_mul := λ x, add_monoid_hom.ext $ λ i, rfl, mul_zero := λ x, add_monoid_hom.ext $ λ i, add_monoid_hom.map_zero _, left_distrib := λ x y z, add_monoid_hom.ext $ λ i, add_monoid_hom.map_add _ _ _, right_distrib := λ x y z, add_monoid_hom.ext $ λ i, rfl, nat_cast := λ n, n • 1, nat_cast_zero := add_monoid.nsmul_zero' _, nat_cast_succ := λ n, (add_monoid.nsmul_succ' n 1).trans (add_comm _ _), .. add_monoid.End.monoid M, .. add_monoid_hom.add_comm_monoid } /-- See also `add_monoid.End.nat_cast_def`. -/ @[simp] lemma add_monoid.End.nat_cast_apply [add_comm_monoid M] (n : ℕ) (m : M) : (↑n : add_monoid.End M) m = n • m := rfl instance [add_comm_group M] : add_comm_group (add_monoid.End M) := add_monoid_hom.add_comm_group instance [add_comm_group M] : ring (add_monoid.End M) := { int_cast := λ z, z • 1, int_cast_of_nat := of_nat_zsmul _, int_cast_neg_succ_of_nat := zsmul_neg_succ_of_nat _, .. add_monoid.End.semiring, .. add_monoid_hom.add_comm_group } /-- See also `add_monoid.End.int_cast_def`. -/ @[simp] lemma add_monoid.End.int_cast_apply [add_comm_group M] (z : ℤ) (m : M) : (↑z : add_monoid.End M) m = z • m := rfl /-! ### Morphisms of morphisms The structures above permit morphisms that themselves produce morphisms, provided the codomain is commutative. -/ namespace monoid_hom @[to_additive] lemma ext_iff₂ {mM : mul_one_class M} {mN : mul_one_class N} {mP : comm_monoid P} {f g : M →* N →* P} : f = g ↔ (∀ x y, f x y = g x y) := monoid_hom.ext_iff.trans $ forall_congr $ λ _, monoid_hom.ext_iff /-- `flip` arguments of `f : M →* N →* P` -/ @[to_additive "`flip` arguments of `f : M →+ N →+ P`"] def flip {mM : mul_one_class M} {mN : mul_one_class N} {mP : comm_monoid P} (f : M →* N →* P) : N →* M →* P := { to_fun := λ y, ⟨λ x, f x y, by rw [f.map_one, one_apply], λ x₁ x₂, by rw [f.map_mul, mul_apply]⟩, map_one' := ext $ λ x, (f x).map_one, map_mul' := λ y₁ y₂, ext $ λ x, (f x).map_mul y₁ y₂ } @[simp, to_additive] lemma flip_apply {mM : mul_one_class M} {mN : mul_one_class N} {mP : comm_monoid P} (f : M →* N →* P) (x : M) (y : N) : f.flip y x = f x y := rfl @[to_additive] lemma map_one₂ {mM : mul_one_class M} {mN : mul_one_class N} {mP : comm_monoid P} (f : M →* N →* P) (n : N) : f 1 n = 1 := (flip f n).map_one @[to_additive] lemma map_mul₂ {mM : mul_one_class M} {mN : mul_one_class N} {mP : comm_monoid P} (f : M →* N →* P) (m₁ m₂ : M) (n : N) : f (m₁ * m₂) n = f m₁ n * f m₂ n := (flip f n).map_mul _ _ @[to_additive] lemma map_inv₂ {mM : group M} {mN : mul_one_class N} {mP : comm_group P} (f : M →* N →* P) (m : M) (n : N) : f m⁻¹ n = (f m n)⁻¹ := (flip f n).map_inv _ @[to_additive] lemma map_div₂ {mM : group M} {mN : mul_one_class N} {mP : comm_group P} (f : M →* N →* P) (m₁ m₂ : M) (n : N) : f (m₁ / m₂) n = f m₁ n / f m₂ n := (flip f n).map_div _ _ /-- Evaluation of a `monoid_hom` at a point as a monoid homomorphism. See also `monoid_hom.apply` for the evaluation of any function at a point. -/ @[to_additive "Evaluation of an `add_monoid_hom` at a point as an additive monoid homomorphism. See also `add_monoid_hom.apply` for the evaluation of any function at a point.", simps] def eval [mul_one_class M] [comm_monoid N] : M →* (M →* N) →* N := (monoid_hom.id (M →* N)).flip /-- The expression `λ g m, g (f m)` as a `monoid_hom`. Equivalently, `(λ g, monoid_hom.comp g f)` as a `monoid_hom`. -/ @[to_additive "The expression `λ g m, g (f m)` as a `add_monoid_hom`. Equivalently, `(λ g, monoid_hom.comp g f)` as a `add_monoid_hom`. This also exists in a `linear_map` version, `linear_map.lcomp`.", simps] def comp_hom' [mul_one_class M] [mul_one_class N] [comm_monoid P] (f : M →* N) : (N →* P) →* M →* P := flip $ eval.comp f /-- Composition of monoid morphisms (`monoid_hom.comp`) as a monoid morphism. Note that unlike `monoid_hom.comp_hom'` this requires commutativity of `N`. -/ @[to_additive "Composition of additive monoid morphisms (`add_monoid_hom.comp`) as an additive monoid morphism. Note that unlike `add_monoid_hom.comp_hom'` this requires commutativity of `N`. This also exists in a `linear_map` version, `linear_map.llcomp`.", simps] def comp_hom [mul_one_class M] [comm_monoid N] [comm_monoid P] : (N →* P) →* (M →* N) →* (M →* P) := { to_fun := λ g, { to_fun := g.comp, map_one' := comp_one g, map_mul' := comp_mul g }, map_one' := by { ext1 f, exact one_comp f }, map_mul' := λ g₁ g₂, by { ext1 f, exact mul_comp g₁ g₂ f } } /-- Flipping arguments of monoid morphisms (`monoid_hom.flip`) as a monoid morphism. -/ @[to_additive "Flipping arguments of additive monoid morphisms (`add_monoid_hom.flip`) as an additive monoid morphism.", simps] def flip_hom {mM : mul_one_class M} {mN : mul_one_class N} {mP : comm_monoid P} : (M →* N →* P) →* (N →* M →* P) := { to_fun := monoid_hom.flip, map_one' := rfl, map_mul' := λ f g, rfl } /-- The expression `λ m q, f m (g q)` as a `monoid_hom`. Note that the expression `λ q n, f (g q) n` is simply `monoid_hom.comp`. -/ @[to_additive "The expression `λ m q, f m (g q)` as an `add_monoid_hom`. Note that the expression `λ q n, f (g q) n` is simply `add_monoid_hom.comp`. This also exists as a `linear_map` version, `linear_map.compl₂`"] def compl₂ [mul_one_class M] [mul_one_class N] [comm_monoid P] [mul_one_class Q] (f : M →* N →* P) (g : Q →* N) : M →* Q →* P := (comp_hom' g).comp f @[simp, to_additive] lemma compl₂_apply [mul_one_class M] [mul_one_class N] [comm_monoid P] [mul_one_class Q] (f : M →* N →* P) (g : Q →* N) (m : M) (q : Q) : (compl₂ f g) m q = f m (g q) := rfl /-- The expression `λ m n, g (f m n)` as a `monoid_hom`. -/ @[to_additive "The expression `λ m n, g (f m n)` as an `add_monoid_hom`. This also exists as a linear_map version, `linear_map.compr₂`"] def compr₂ [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q] (f : M →* N →* P) (g : P →* Q) : M →* N →* Q := (comp_hom g).comp f @[simp, to_additive] lemma compr₂_apply [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q] (f : M →* N →* P) (g : P →* Q) (m : M) (n : N) : (compr₂ f g) m n = g (f m n) := rfl end monoid_hom /-! ### Miscellaneous definitions Due to the fact this file imports `algebra.group_power.basic`, it is not possible to import it in some of the lower-level files like `algebra.ring.basic`. The following lemmas should be rehomed if the import structure permits them to be. -/ section semiring variables {R S : Type*} [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] /-- Multiplication of an element of a (semi)ring is an `add_monoid_hom` in both arguments. This is a more-strongly bundled version of `add_monoid_hom.mul_left` and `add_monoid_hom.mul_right`. Stronger versions of this exists for algebras as `linear_map.mul`, `non_unital_alg_hom.mul` and `algebra.lmul`. -/ def add_monoid_hom.mul : R →+ R →+ R := { to_fun := add_monoid_hom.mul_left, map_zero' := add_monoid_hom.ext $ zero_mul, map_add' := λ a b, add_monoid_hom.ext $ add_mul a b } lemma add_monoid_hom.mul_apply (x y : R) : add_monoid_hom.mul x y = x * y := rfl @[simp] lemma add_monoid_hom.coe_mul : ⇑(add_monoid_hom.mul : R →+ R →+ R) = add_monoid_hom.mul_left := rfl @[simp] lemma add_monoid_hom.coe_flip_mul : ⇑(add_monoid_hom.mul : R →+ R →+ R).flip = add_monoid_hom.mul_right := rfl /-- An `add_monoid_hom` preserves multiplication if pre- and post- composition with `add_monoid_hom.mul` are equivalent. By converting the statement into an equality of `add_monoid_hom`s, this lemma allows various specialized `ext` lemmas about `→+` to then be applied. -/ lemma add_monoid_hom.map_mul_iff (f : R →+ S) : (∀ x y, f (x * y) = f x * f y) ↔ (add_monoid_hom.mul : R →+ R →+ R).compr₂ f = (add_monoid_hom.mul.comp f).compl₂ f := iff.symm add_monoid_hom.ext_iff₂ /-- The left multiplication map: `(a, b) ↦ a * b`. See also `add_monoid_hom.mul_left`. -/ @[simps] def add_monoid.End.mul_left : R →+ add_monoid.End R := add_monoid_hom.mul /-- The right multiplication map: `(a, b) ↦ b * a`. See also `add_monoid_hom.mul_right`. -/ @[simps] def add_monoid.End.mul_right : R →+ add_monoid.End R := (add_monoid_hom.mul : R →+ add_monoid.End R).flip end semiring
855b67bf5d6616c4062a7ae94163768d502ac510
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/tactic/lint/simp.lean
b26a4d6564ca83be5e5187c33347757fe173c764
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
9,345
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import tactic.lint.basic /-! # Linter for simplification lemmas This files defines several linters that prevent common mistakes when declaring simp lemmas: * `simp_nf` checks that the left-hand side of a simp lemma is not simplified by a different lemma. * `simp_var_head` checks that the head symbol of the left-hand side is not a variable. * `simp_comm` checks that commutativity lemmas are not marked as simplification lemmas. -/ open tactic expr /-- `simp_lhs_rhs ty` returns the left-hand and right-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs_rhs : expr → tactic (expr × expr) | ty := do ty ← whnf ty transparency.reducible, -- We only detect a fixed set of simp relations here. -- This is somewhat justified since for a custom simp relation R, -- the simp lemma `R a b` is implicitly converted to `R a b ↔ true` as well. match ty with | `(¬ %%lhs) := pure (lhs, `(false)) | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | (expr.pi n bi a b) := do l ← mk_local' n bi a, simp_lhs_rhs (b.instantiate_var l) | ty := pure (ty, `(true)) end /-- `simp_lhs ty` returns the left-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs (ty : expr): tactic expr := prod.fst <$> simp_lhs_rhs ty /-- `simp_is_conditional_core ty` returns `none` if `ty` is a conditional simp lemma, and `some lhs` otherwise. -/ private meta def simp_is_conditional_core : expr → tactic (option expr) | ty := do ty ← whnf ty transparency.semireducible, match ty with | `(¬ %%lhs) := pure lhs | `(%%lhs = _) := pure lhs | `(%%lhs ↔ _) := pure lhs | (expr.pi n bi a b) := do l ← mk_local' n bi a, some lhs ← simp_is_conditional_core (b.instantiate_var l) | pure none, if bi ≠ binder_info.inst_implicit ∧ ¬ (lhs.abstract_local l.local_uniq_name).has_var then pure none else pure lhs | ty := pure ty end /-- `simp_is_conditional ty` returns true iff the simp lemma with type `ty` is conditional. -/ private meta def simp_is_conditional (ty : expr) : tactic bool := option.is_none <$> simp_is_conditional_core ty private meta def heuristic_simp_lemma_extraction (prf : expr) : tactic (list name) := prf.list_constant.to_list.mfilter is_simp_lemma /-- Checks whether two expressions are equal for the simplifier. That is, they are reducibly-definitional equal, and they have the same head symbol. -/ meta def is_simp_eq (a b : expr) : tactic bool := if a.get_app_fn.const_name ≠ b.get_app_fn.const_name then pure ff else succeeds $ is_def_eq a b transparency.reducible /-- Reports declarations that are simp lemmas whose left-hand side is not in simp-normal form. -/ meta def simp_nf_linter (timeout := 200000) (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, [] ← get_eqn_lemmas_for ff d.to_name | pure none, try_for timeout $ retrieve $ do g ← mk_meta_var d.type, set_goals [g], unfreezing intros, (lhs, rhs) ← target >>= simp_lhs_rhs, sls ← simp_lemmas.mk_default, let sls' := sls.erase [d.to_name], (lhs', prf1) ← decorate_error "simplify fails on left-hand side:" $ simplify sls [] lhs {fail_if_unchanged := ff}, prf1_lems ← heuristic_simp_lemma_extraction prf1, if d.to_name ∈ prf1_lems then pure none else do is_cond ← simp_is_conditional d.type, (rhs', prf2) ← decorate_error "simplify fails on right-hand side:" $ simplify sls [] rhs {fail_if_unchanged := ff}, lhs'_eq_rhs' ← is_simp_eq lhs' rhs', lhs_in_nf ← is_simp_eq lhs' lhs, if lhs'_eq_rhs' then do used_lemmas ← heuristic_simp_lemma_extraction (prf1 prf2), pure $ pure $ "simp can prove this:\n" ++ " by simp only " ++ to_string used_lemmas ++ "\n" ++ "One of the lemmas above could be a duplicate.\n" ++ "If that's not the case try reordering lemmas or adding @[priority].\n" else if ¬ lhs_in_nf then do lhs ← pp lhs, lhs' ← pp lhs', pure $ format.to_string $ to_fmt "Left-hand side simplifies from" ++ lhs.group.indent 2 ++ format.line ++ "to" ++ lhs'.group.indent 2 ++ format.line ++ "using " ++ (to_fmt prf1_lems).group.indent 2 ++ format.line ++ "Try to change the left-hand side to the simplified term!\n" else if ¬ is_cond ∧ lhs = lhs' then do pure "Left-hand side does not simplify.\nYou need to debug this yourself using `set_option trace.simplify.rewrite true`" else pure none /-- This note gives you some tips to debug any errors that the simp-normal form linter raises The reason that a lemma was considered faulty is because its left-hand side is not in simp-normal form. These lemmas are hence never used by the simplifier. This linter gives you a list of other simp lemmas, look at them! Here are some tips depending on the error raised by the linter: 1. 'the left-hand side reduces to XYZ': you should probably use XYZ as the left-hand side. 2. 'simp can prove this': This typically means that lemma is a duplicate, or is shadowed by another lemma: 2a. Always put more general lemmas after specific ones: @[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl @[simp] lemma add_zero : x + 0 = x := rfl And not the other way around! The simplifier always picks the last matching lemma. 2b. You can also use @[priority] instead of moving simp-lemmas around in the file. Tip: the default priority is 1000. Use `@[priority 1100]` instead of moving a lemma down, and `@[priority 900]` instead of moving a lemma up. 2c. Conditional simp lemmas are tried last, if they are shadowed just remove the simp attribute. 2d. If two lemmas are duplicates, the linter will complain about the first one. Try to fix the second one instead! (You can find it among the other simp lemmas the linter prints out!) 3. 'try_for tactic failed, timeout': This typically means that there is a loop of simp lemmas. Try to apply squeeze_simp to the right-hand side (removing this lemma from the simp set) to see what lemmas might be causing the loop. Another trick is to `set_option trace.simplify.rewrite true` and then apply `try_for 10000 { simp }` to the right-hand side. You will see a periodic sequence of lemma applications in the trace message. -/ library_note "simp-normal form" /-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/ @[linter] meta def linter.simp_nf : linter := { test := simp_nf_linter, auto_decls := tt, no_errors_found := "All left-hand sides of simp lemmas are in simp-normal form", errors_found := "SOME SIMP LEMMAS ARE NOT IN SIMP-NORMAL FORM. see note [simp-normal form] for tips how to debug this. https://leanprover-community.github.io/mathlib_docs/notes.html#simp-normal%20form " } private meta def simp_var_head (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, lhs ← simp_lhs d.type, head_sym@(expr.local_const _ _ _ _) ← pure lhs.get_app_fn | pure none, head_sym ← pp head_sym, pure $ format.to_string $ "Left-hand side has variable as head symbol: " ++ head_sym /-- A linter for simp lemmas whose lhs has a variable as head symbol, and which hence never fire. -/ @[linter] meta def linter.simp_var_head : linter := { test := simp_var_head, auto_decls := tt, no_errors_found := "No left-hand sides of a simp lemma has a variable as head symbol", errors_found := "LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL.\n" ++ "Some simp lemmas have a variable as head symbol of the left-hand side" } private meta def simp_comm (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, (lhs, rhs) ← simp_lhs_rhs d.type, if lhs.get_app_fn.const_name ≠ rhs.get_app_fn.const_name then pure none else do (lhs', rhs') ← (prod.snd <$> open_pis_metas d.type) >>= simp_lhs_rhs, tt ← succeeds $ unify rhs lhs' transparency.reducible | pure none, tt ← succeeds $ is_def_eq rhs lhs' transparency.reducible | pure none, -- ensure that the second application makes progress: ff ← succeeds $ unify lhs' rhs' transparency.reducible | pure none, pure $ "should not be marked simp" /-- A linter for commutativity lemmas that are marked simp. -/ @[linter] meta def linter.simp_comm : linter := { test := simp_comm, auto_decls := tt, no_errors_found := "No commutativity lemma is marked simp", errors_found := "COMMUTATIVITY LEMMA IS SIMP.\n" ++ "Some commutativity lemmas are simp lemmas" }
d17c4a7c1d8344ddca05a259ec28324782e4ba93
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/real/pi/leibniz.lean
5ba42465a6d9d00e99c3d9a7156897cb6605bbe6
[ "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
7,656
lean
/- Copyright (c) 2020 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import analysis.special_functions.trigonometric.arctan_deriv /-! ### Leibniz's Series for Pi -/ namespace real open filter set open_locale classical big_operators topological_space real local notation (name := abs) `|`x`|` := abs x /-- This theorem establishes **Leibniz's series for `π`**: The alternating sum of the reciprocals of the odd numbers is `π/4`. Note that this is a conditionally rather than absolutely convergent series. The main tool that this proof uses is the Mean Value Theorem (specifically avoiding the Fundamental Theorem of Calculus). Intuitively, the theorem holds because Leibniz's series is the Taylor series of `arctan x` centered about `0` and evaluated at the value `x = 1`. Therefore, much of this proof consists of reasoning about a function `f := arctan x - ∑ i in finset.range k, (-(1:ℝ))^i * x^(2*i+1) / (2*i+1)`, the difference between `arctan` and the `k`-th partial sum of its Taylor series. Some ingenuity is required due to the fact that the Taylor series is not absolutely convergent at `x = 1`. This proof requires a bound on `f 1`, the key idea being that `f 1` can be split as the sum of `f 1 - f u` and `f u`, where `u` is a sequence of values in [0,1], carefully chosen such that each of these two terms can be controlled (in different ways). We begin the proof by (1) introducing that sequence `u` and then proving that another sequence constructed from `u` tends to `0` at `+∞`. After (2) converting the limit in our goal to an inequality, we (3) introduce the auxiliary function `f` defined above. Next, we (4) compute the derivative of `f`, denoted by `f'`, first generally and then on each of two subintervals of [0,1]. We then (5) prove a bound for `f'`, again both generally as well as on each of the two subintervals. Finally, we (6) apply the Mean Value Theorem twice, obtaining bounds on `f 1 - f u` and `f u - f 0` from the bounds on `f'` (note that `f 0 = 0`). -/ theorem tendsto_sum_pi_div_four : tendsto (λ k, ∑ i in finset.range k, ((-(1:ℝ))^i / (2*i+1))) at_top (𝓝 (π/4)) := begin rw [tendsto_iff_norm_tendsto_zero, ← tendsto_zero_iff_norm_tendsto_zero], -- (1) We introduce a useful sequence `u` of values in [0,1], then prove that another sequence -- constructed from `u` tends to `0` at `+∞` let u := λ k : ℕ, (k:nnreal) ^ (-1 / (2 * (k:ℝ) + 1)), have H : tendsto (λ k : ℕ, (1:ℝ) - (u k) + (u k) ^ (2 * (k:ℝ) + 1)) at_top (𝓝 0), { convert (((tendsto_rpow_div_mul_add (-1) 2 1 two_ne_zero.symm).neg.const_add 1).add tendsto_inv_at_top_zero).comp tendsto_coe_nat_at_top_at_top, { ext k, simp only [nnreal.coe_nat_cast, function.comp_app, nnreal.coe_rpow], rw [← rpow_mul (nat.cast_nonneg k) ((-1)/(2*(k:ℝ)+1)) (2*(k:ℝ)+1), @div_mul_cancel _ _ (2*(k:ℝ)+1) _ (by { norm_cast, simp only [nat.succ_ne_zero, not_false_iff] }), rpow_neg_one k, sub_eq_add_neg] }, { simp only [add_zero, add_right_neg] } }, -- (2) We convert the limit in our goal to an inequality refine squeeze_zero_norm _ H, intro k, -- Since `k` is now fixed, we henceforth denote `u k` as `U` let U := u k, -- (3) We introduce an auxiliary function `f` let b := λ (i:ℕ) x, (-(1:ℝ))^i * x^(2*i+1) / (2*i+1), let f := λ x, arctan x - (∑ i in finset.range k, b i x), suffices f_bound : |f 1 - f 0| ≤ (1:ℝ) - U + U ^ (2 * (k:ℝ) + 1), { rw ← norm_neg, convert f_bound, simp only [f], simp [b] }, -- We show that `U` is indeed in [0,1] have hU1 : (U:ℝ) ≤ 1, { by_cases hk : k = 0, { simp [u, U, hk] }, { exact rpow_le_one_of_one_le_of_nonpos (by { norm_cast, exact nat.succ_le_iff.mpr (nat.pos_of_ne_zero hk) }) (le_of_lt (@div_neg_of_neg_of_pos _ _ (-(1:ℝ)) (2*k+1) (neg_neg_iff_pos.mpr zero_lt_one) (by { norm_cast, exact nat.succ_pos' }))) } }, have hU2 := nnreal.coe_nonneg U, -- (4) We compute the derivative of `f`, denoted by `f'` let f' := λ x : ℝ, (-x^2) ^ k / (1 + x^2), have has_deriv_at_f : ∀ x, has_deriv_at f (f' x) x, { intro x, have has_deriv_at_b : ∀ i ∈ finset.range k, (has_deriv_at (b i) ((-x^2)^i) x), { intros i hi, convert has_deriv_at.const_mul ((-1:ℝ)^i / (2*i+1)) (@has_deriv_at.pow _ _ _ _ _ (2*i+1) (has_deriv_at_id x)), { ext y, simp only [b, id.def], ring }, { simp only [nat.add_succ_sub_one, add_zero, mul_one, id.def, nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul], rw [← mul_assoc, @div_mul_cancel _ _ (2*(i:ℝ)+1) _ (by { norm_cast, linarith }), pow_mul x 2 i, ← mul_pow (-1) (x^2) i], ring_nf } }, convert (has_deriv_at_arctan x).sub (has_deriv_at.sum has_deriv_at_b), have g_sum := @geom_sum_eq _ _ (-x^2) ((neg_nonpos.mpr (sq_nonneg x)).trans_lt zero_lt_one).ne k, simp only [f'] at g_sum ⊢, rw [g_sum, ← neg_add' (x^2) 1, add_comm (x^2) 1, sub_eq_add_neg, neg_div', neg_div_neg_eq], ring }, have hderiv1 : ∀ x ∈ Icc (U:ℝ) 1, has_deriv_within_at f (f' x) (Icc (U:ℝ) 1) x := λ x hx, (has_deriv_at_f x).has_deriv_within_at, have hderiv2 : ∀ x ∈ Icc 0 (U:ℝ), has_deriv_within_at f (f' x) (Icc 0 (U:ℝ)) x := λ x hx, (has_deriv_at_f x).has_deriv_within_at, -- (5) We prove a general bound for `f'` and then more precise bounds on each of two subintervals have f'_bound : ∀ x ∈ Icc (-1:ℝ) 1, |f' x| ≤ |x|^(2*k), { intros x hx, rw [abs_div, is_absolute_value.abv_pow abs (-x^2) k, abs_neg, is_absolute_value.abv_pow abs x 2, ← pow_mul], refine div_le_of_nonneg_of_le_mul (abs_nonneg _) (pow_nonneg (abs_nonneg _) _) _, refine le_mul_of_one_le_right (pow_nonneg (abs_nonneg _) _) _, rw abs_of_nonneg ((add_nonneg zero_le_one (sq_nonneg x)) : (0 : ℝ) ≤ _), exact (le_add_of_nonneg_right (sq_nonneg x) : (1 : ℝ) ≤ _) }, have hbound1 : ∀ x ∈ Ico (U:ℝ) 1, |f' x| ≤ 1, { rintros x ⟨hx_left, hx_right⟩, have hincr := pow_le_pow_of_le_left (le_trans hU2 hx_left) (le_of_lt hx_right) (2*k), rw [one_pow (2*k), ← abs_of_nonneg (le_trans hU2 hx_left)] at hincr, rw ← abs_of_nonneg (le_trans hU2 hx_left) at hx_right, linarith [f'_bound x (mem_Icc.mpr (abs_le.mp (le_of_lt hx_right)))] }, have hbound2 : ∀ x ∈ Ico 0 (U:ℝ), |f' x| ≤ U ^ (2*k), { rintros x ⟨hx_left, hx_right⟩, have hincr := pow_le_pow_of_le_left hx_left (le_of_lt hx_right) (2*k), rw ← abs_of_nonneg hx_left at hincr hx_right, rw ← abs_of_nonneg hU2 at hU1 hx_right, linarith [f'_bound x (mem_Icc.mpr (abs_le.mp (le_trans (le_of_lt hx_right) hU1)))] }, -- (6) We twice apply the Mean Value Theorem to obtain bounds on `f` from the bounds on `f'` have mvt1 := norm_image_sub_le_of_norm_deriv_le_segment' hderiv1 hbound1 _ (right_mem_Icc.mpr hU1), have mvt2 := norm_image_sub_le_of_norm_deriv_le_segment' hderiv2 hbound2 _ (right_mem_Icc.mpr hU2), -- The following algebra is enough to complete the proof calc |f 1 - f 0| = |(f 1 - f U) + (f U - f 0)| : by ring_nf ... ≤ 1 * (1-U) + U^(2*k) * (U - 0) : le_trans (abs_add (f 1 - f U) (f U - f 0)) (add_le_add mvt1 mvt2) ... = 1 - U + U^(2*k) * U : by ring ... = 1 - (u k) + (u k)^(2*(k:ℝ)+1) : by { rw [← pow_succ' (U:ℝ) (2*k)], norm_cast }, end end real
0b176d494e1c34421362389805753fc5f6616cac
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/group_theory/congruence.lean
8e45c24ad2908d0f8c1e3066d63aceedca599cbc
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
42,874
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.group.pi import algebra.group.prod import data.equiv.mul_add import group_theory.submonoid.operations /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw [Sup_eq_con_gen, Sup_image], congr, ext x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o ((≤) : con c.quotient → con c.quotient → Prop) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive to_add_submonoid_inj] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective (ker_lift f) ⟨ker_lift_injective f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end con
5464d525db0d99beaae3376c364df3d4d1560ed7
e953c38599905267210b87fb5d82dcc3e52a4214
/library/data/real/complete.lean
23cf3fc7353399976fae96af801218b9dab0c451
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
33,691
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability, excluded middle, and Hilbert choice. Here, we show that ℝ is complete. -/ import data.real.basic data.real.order data.real.division data.rat data.nat data.pnat open -[coercions] rat local notation 0 := rat.of_num 0 local notation 1 := rat.of_num 1 open -[coercions] nat open eq.ops pnat classical local notation 2 := subtype.tag (nat.of_num 2) dec_trivial local notation 3 := subtype.tag (nat.of_num 3) dec_trivial namespace s theorem rat_approx_l1 {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → abs (s m - q) ≤ n⁻¹ := begin intro n, existsi (s (2 * n)), existsi 2 * n, intro m Hm, apply rat.le.trans, apply H, rewrite -(add_halves n), apply rat.add_le_add_right, apply inv_ge_of_le Hm end theorem rat_approx {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, s_le (s_abs (sadd s (sneg (const q)))) (const n⁻¹) := begin intro m, rewrite ↑s_le, cases rat_approx_l1 H m with [q, Hq], cases Hq with [N, HN], existsi q, apply nonneg_of_bdd_within, repeat (apply reg_add_reg | apply reg_neg_reg | apply abs_reg_of_reg | apply const_reg | assumption), intro n, existsi N, intro p Hp, rewrite ↑[sadd, sneg, s_abs, const], apply rat.le.trans, rotate 1, apply rat.sub_le_sub_left, apply HN, apply pnat.le.trans, apply Hp, rewrite -*pnat.mul.assoc, apply pnat.mul_le_mul_left, rewrite [sub_self, -neg_zero], apply neg_le_neg, apply rat.le_of_lt, apply inv_pos end definition r_abs (s : reg_seq) : reg_seq := reg_seq.mk (s_abs (reg_seq.sq s)) (abs_reg_of_reg (reg_seq.is_reg s)) theorem abs_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : s_abs s ≡ s_abs t := begin rewrite [↑equiv at *], intro n, rewrite ↑s_abs, apply rat.le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Heq end theorem r_abs_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_abs s) (r_abs t) := abs_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_rat_approx (s : reg_seq) : ∀ n : ℕ+, ∃ q : ℚ, r_le (r_abs (radd s (rneg (r_const q)))) (r_const n⁻¹) := rat_approx (reg_seq.is_reg s) theorem const_bound {s : seq} (Hs : regular s) (n : ℕ+) : s_le (s_abs (sadd s (sneg (const (s n))))) (const n⁻¹) := begin rewrite ↑[s_le, nonneg, s_abs, sadd, sneg, const], intro m, apply iff.mp !rat.le_add_iff_neg_le_sub_left, apply rat.le.trans, apply Hs, apply rat.add_le_add_right, rewrite -*pnat.mul.assoc, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem abs_const (a : ℚ) : const (abs a) ≡ s_abs (const a) := by apply equiv.refl theorem r_abs_const (a : ℚ) : requiv (r_const (abs a) ) (r_abs (r_const a)) := abs_const a theorem equiv_abs_of_ge_zero {s : seq} (Hs : regular s) (Hz : s_le zero s) : s_abs s ≡ s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply Hs, intro j, rewrite ↑s_abs, let Hz' := s_nonneg_of_ge_zero Hs Hz, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], rewrite [rat.abs_of_nonneg Hpos, sub_self, abs_zero], apply rat.le_of_lt, apply inv_pos, let Hneg' := lt_of_not_ge Hneg, have Hsn : -s n - s n > 0, from add_pos (neg_pos_of_neg Hneg') (neg_pos_of_neg Hneg'), rewrite [rat.abs_of_neg Hneg', rat.abs_of_pos Hsn], apply rat.le.trans, apply rat.add_le_add, repeat (apply rat.neg_le_neg; apply Hz'), rewrite *rat.neg_neg, apply rat.le.trans, apply rat.add_le_add, repeat (apply inv_ge_of_le; apply Hn), rewrite pnat.add_halves, apply rat.le.refl end theorem equiv_neg_abs_of_le_zero {s : seq} (Hs : regular s) (Hz : s_le s zero) : s_abs s ≡ sneg s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply reg_neg_reg Hs, intro j, rewrite [↑s_abs, ↑s_le at Hz], have Hz' : nonneg (sneg s), begin apply nonneg_of_nonneg_equiv, rotate 3, apply Hz, rotate 2, apply s_zero_add, repeat (apply Hs | apply zero_is_reg | apply reg_neg_reg | apply reg_add_reg) end, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], have Hsn : s n + s n ≥ 0, from add_nonneg Hpos Hpos, rewrite [rat.abs_of_nonneg Hpos, ↑sneg, rat.sub_neg_eq_add, rat.abs_of_nonneg Hsn], rewrite [↑nonneg at Hz', ↑sneg at Hz'], apply rat.le.trans, apply rat.add_le_add, repeat apply (rat.le_of_neg_le_neg !Hz'), apply rat.le.trans, apply rat.add_le_add, repeat (apply inv_ge_of_le; apply Hn), rewrite pnat.add_halves, apply rat.le.refl, let Hneg' := lt_of_not_ge Hneg, rewrite [rat.abs_of_neg Hneg', ↑sneg, rat.sub_neg_eq_add, rat.neg_add_eq_sub, rat.sub_self, abs_zero], apply rat.le_of_lt, apply inv_pos end theorem r_equiv_abs_of_ge_zero {s : reg_seq} (Hz : r_le r_zero s) : requiv (r_abs s) s := equiv_abs_of_ge_zero (reg_seq.is_reg s) Hz theorem r_equiv_neg_abs_of_le_zero {s : reg_seq} (Hz : r_le s r_zero) : requiv (r_abs s) (-s) := equiv_neg_abs_of_le_zero (reg_seq.is_reg s) Hz end s namespace real open [classes] s theorem p_add_fractions (n : ℕ+) : (2 * n)⁻¹ + (2 * 3 * n)⁻¹ + (3 * n)⁻¹ = n⁻¹ := assert T : 2⁻¹ + 2⁻¹ * 3⁻¹ + 3⁻¹ = 1, from dec_trivial, by rewrite[*inv_mul_eq_mul_inv,-*rat.right_distrib,T,rat.one_mul] theorem rewrite_helper9 (a b c : ℝ) : b - c = (b - a) - (c - a) := by rewrite[-sub_add_eq_sub_sub_swap,sub_add_cancel] theorem rewrite_helper10 (a b c d : ℝ) : c - d = (c - a) + (a - b) + (b - d) := by rewrite[*add_sub,*sub_add_cancel] noncomputable definition rep (x : ℝ) : s.reg_seq := some (quot.exists_rep x) definition re_abs (x : ℝ) : ℝ := quot.lift_on x (λ a, quot.mk (s.r_abs a)) (take a b Hab, quot.sound (s.r_abs_well_defined Hab)) theorem r_abs_nonneg {x : ℝ} : zero ≤ x → re_abs x = x := quot.induction_on x (λ a Ha, quot.sound (s.r_equiv_abs_of_ge_zero Ha)) theorem r_abs_nonpos {x : ℝ} : x ≤ zero → re_abs x = -x := quot.induction_on x (λ a Ha, quot.sound (s.r_equiv_neg_abs_of_le_zero Ha)) theorem abs_const' (a : ℚ) : of_rat (rat.abs a) = re_abs (of_rat a) := quot.sound (s.r_abs_const a) theorem re_abs_is_abs : re_abs = real.abs := funext (begin intro x, apply eq.symm, cases em (zero ≤ x) with [Hor1, Hor2], rewrite [abs_of_nonneg Hor1, r_abs_nonneg Hor1], have Hor2' : x ≤ zero, from le_of_lt (lt_of_not_ge Hor2), rewrite [abs_of_neg (lt_of_not_ge Hor2), r_abs_nonpos Hor2'] end) theorem abs_const (a : ℚ) : of_rat (rat.abs a) = abs (of_rat a) := by rewrite -re_abs_is_abs theorem rat_approx' (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, re_abs (x - of_rat q) ≤ of_rat n⁻¹ := quot.induction_on x (λ s n, s.r_rat_approx s n) theorem rat_approx (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, abs (x - of_rat q) ≤ of_rat n⁻¹ := by rewrite -re_abs_is_abs; apply rat_approx' noncomputable definition approx (x : ℝ) (n : ℕ+) := some (rat_approx x n) theorem approx_spec (x : ℝ) (n : ℕ+) : abs (x - (of_rat (approx x n))) ≤ of_rat n⁻¹ := some_spec (rat_approx x n) theorem approx_spec' (x : ℝ) (n : ℕ+) : abs ((of_rat (approx x n)) - x) ≤ of_rat n⁻¹ := by rewrite abs_sub; apply approx_spec notation `r_seq` := ℕ+ → ℝ noncomputable definition converges_to (X : r_seq) (a : ℝ) (N : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ n : ℕ+, n ≥ N k → abs (X n - a) ≤ of_rat k⁻¹ noncomputable definition cauchy (X : r_seq) (M : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ m n : ℕ+, m ≥ M k → n ≥ M k → abs (X m - X n) ≤ of_rat k⁻¹ theorem cauchy_of_converges_to {X : r_seq} {a : ℝ} {N : ℕ+ → ℕ+} (Hc : converges_to X a N) : cauchy X (λ k, N (2 * k)) := begin intro k m n Hm Hn, rewrite (rewrite_helper9 a), apply le.trans, apply abs_add_le_abs_add_abs, apply le.trans, apply add_le_add, apply Hc, apply Hm, krewrite abs_neg, apply Hc, apply Hn, xrewrite of_rat_add, apply of_rat_le_of_rat_of_le, rewrite pnat.add_halves, apply rat.le.refl end definition Nb (M : ℕ+ → ℕ+) := λ k, pnat.max (3 * k) (M (2 * k)) theorem Nb_spec_right (M : ℕ+ → ℕ+) (k : ℕ+) : M (2 * k) ≤ Nb M k := !max_right theorem Nb_spec_left (M : ℕ+ → ℕ+) (k : ℕ+) : 3 * k ≤ Nb M k := !max_left section lim_seq parameter {X : r_seq} parameter {M : ℕ+ → ℕ+} hypothesis Hc : cauchy X M include Hc noncomputable definition lim_seq : ℕ+ → ℚ := λ k, approx (X (Nb M k)) (2 * k) theorem lim_seq_reg_helper {m n : ℕ+} (Hmn : M (2 * n) ≤M (2 * m)) : abs (of_rat (lim_seq m) - X (Nb M m)) + abs (X (Nb M m) - X (Nb M n)) + abs (X (Nb M n) - of_rat (lim_seq n)) ≤ of_rat (m⁻¹ + n⁻¹) := begin apply le.trans, apply add_le_add_three, apply approx_spec', rotate 1, apply approx_spec, rotate 1, apply Hc, rotate 1, apply Nb_spec_right, rotate 1, apply pnat.le.trans, apply Hmn, apply Nb_spec_right, rewrite [*of_rat_add, rat.add.assoc, pnat.add_halves], apply of_rat_le_of_rat_of_le, apply rat.add_le_add_right, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem lim_seq_reg : s.regular lim_seq := begin rewrite ↑s.regular, intro m n, apply le_of_rat_le_of_rat, rewrite [abs_const, -of_rat_sub, (rewrite_helper10 (X (Nb M m)) (X (Nb M n)))], apply real.le.trans, apply abs_add_three, cases em (M (2 * m) ≥ M (2 * n)) with [Hor1, Hor2], apply lim_seq_reg_helper Hor1, let Hor2' := pnat.le_of_lt (pnat.lt_of_not_le Hor2), rewrite [real.abs_sub (X (Nb M n)), abs_sub (X (Nb M m)), abs_sub, rat.add.comm, add_comm_three], apply lim_seq_reg_helper Hor2' end theorem lim_seq_spec (k : ℕ+) : s.s_le (s.s_abs (s.sadd lim_seq (s.sneg (s.const (lim_seq k))))) (s.const k⁻¹) := by apply s.const_bound; apply lim_seq_reg noncomputable definition r_lim_seq : s.reg_seq := s.reg_seq.mk lim_seq lim_seq_reg theorem r_lim_seq_spec (k : ℕ+) : s.r_le (s.r_abs ((s.radd r_lim_seq (s.rneg (s.r_const ((s.reg_seq.sq r_lim_seq) k)))))) (s.r_const k⁻¹) := lim_seq_spec k noncomputable definition lim : ℝ := quot.mk r_lim_seq theorem re_lim_spec (k : ℕ+) : re_abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := r_lim_seq_spec k theorem lim_spec' (k : ℕ+) : abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := by rewrite -re_abs_is_abs; apply re_lim_spec theorem lim_spec (k : ℕ+) : abs ((of_rat (lim_seq k)) - lim) ≤ of_rat k⁻¹ := by rewrite abs_sub; apply lim_spec' theorem converges_of_cauchy : converges_to X lim (Nb M) := begin intro k n Hn, rewrite (rewrite_helper10 (X (Nb M n)) (of_rat (lim_seq n))), apply le.trans, apply abs_add_three, apply le.trans, apply add_le_add_three, apply Hc, apply pnat.le.trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_right, have HMk : M (2 * k) ≤ Nb M n, begin apply pnat.le.trans, apply Nb_spec_right, apply pnat.le.trans, apply Hn, apply pnat.le.trans, apply mul_le_mul_left 3, apply Nb_spec_left end, apply HMk, rewrite ↑lim_seq, apply approx_spec, apply lim_spec, rewrite 2 of_rat_add, apply of_rat_le_of_rat_of_le, apply rat.le.trans, apply rat.add_le_add_three, apply rat.le.refl, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le.trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, apply inv_ge_of_le, apply pnat.le.trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, rewrite [-*pnat.mul.assoc, p_add_fractions], apply rat.le.refl end end lim_seq ------------------------------------------- -- int embedding theorems -- archimedean properties, integer floor and ceiling section ints open int theorem archimedean (x : ℝ) : ∃ z : ℤ, x ≤ of_rat (of_int z) := begin apply quot.induction_on x, intro s, cases s.bdd_of_regular (s.reg_seq.is_reg s) with [b, Hb], existsi ubound b, have H : s.s_le (s.reg_seq.sq s) (s.const (rat.of_nat (ubound b))), begin apply s.s_le_of_le_pointwise (s.reg_seq.is_reg s), apply s.const_reg, intro n, apply rat.le.trans, apply Hb, apply ubound_ge end, apply H end theorem archimedean_strict (x : ℝ) : ∃ z : ℤ, x < of_rat (of_int z) := begin cases archimedean x with [z, Hz], existsi z + 1, apply lt_of_le_of_lt, apply Hz, apply of_rat_lt_of_rat_of_lt, apply iff.mpr !of_int_lt_of_int, apply int.lt_add_of_pos_right, apply dec_trivial end theorem archimedean' (x : ℝ) : ∃ z : ℤ, x ≥ of_rat (of_int z) := begin cases archimedean (-x) with [z, Hz], existsi -z, rewrite [of_int_neg, of_rat_neg], apply iff.mp !neg_le_iff_neg_le Hz end theorem archimedean_strict' (x : ℝ) : ∃ z : ℤ, x > of_rat (of_int z) := begin cases archimedean_strict (-x) with [z, Hz], existsi -z, rewrite [of_int_neg, of_rat_neg], apply iff.mp !neg_lt_iff_neg_lt Hz end theorem ex_smallest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≤ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, z < lb → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b + of_nat (least (λ n, P (b + of_nat n)) (succ (nat_abs (elt - b)))), have Heltb : elt > b, begin apply int.lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b + of_nat (nat_abs (elt - b))), begin rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !int.sub_pos_iff_lt Heltb)), int.add.comm, int.sub_add_cancel], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≤ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := int.lt_of_not_ge Hzb, let Hpos := iff.mpr !int.sub_pos_iff_lt Hzb', have Hzbk : z = b + of_nat (nat_abs (z - b)), by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.add.comm, int.sub_add_cancel], have Hk : nat_abs (z - b) < least (λ n, P (b + of_nat n)) (succ (nat_abs (elt - b))), begin let Hz' := iff.mp !int.lt_add_iff_sub_lt_left Hz, rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply iff.mp !int.of_nat_lt_of_nat Hz' end, let Hk' := nat.not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt.trans Hk, apply least_lt _ !lt_succ_self H' end theorem ex_largest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≥ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, z > ub → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b - of_nat (least (λ n, P (b - of_nat n)) (succ (nat_abs (b - elt)))), have Heltb : elt < b, begin apply int.lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b - of_nat (nat_abs (b - elt))), begin rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !int.sub_pos_iff_lt Heltb)), int.sub_sub_self], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≥ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := int.lt_of_not_ge Hzb, let Hpos := iff.mpr !int.sub_pos_iff_lt Hzb', have Hzbk : z = b - of_nat (nat_abs (b - z)), by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.sub_sub_self], have Hk : nat_abs (b - z) < least (λ n, P (b - of_nat n)) (succ (nat_abs (b - elt))), begin let Hz' := iff.mp !int.lt_add_iff_sub_lt_left (iff.mpr !int.lt_add_iff_sub_lt_right Hz), rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply iff.mp !int.of_nat_lt_of_nat Hz' end, let Hk' := nat.not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt.trans Hk, apply least_lt _ !lt_succ_self H' end definition ex_floor (x : ℝ) := (@ex_largest_of_bdd (λ z, x ≥ of_rat (of_int z)) (begin existsi some (archimedean_strict x), let Har := some_spec (archimedean_strict x), intros z Hz, apply not_le_of_gt, apply lt_of_lt_of_le, apply Har, have H : of_rat (of_int (some (archimedean_strict x))) ≤ of_rat (of_int z), begin apply of_rat_le_of_rat_of_le, apply iff.mpr !of_int_le_of_int, apply Hz end, exact H end) (by existsi some (archimedean' x); apply some_spec (archimedean' x))) noncomputable definition floor (x : ℝ) : ℤ := some (ex_floor x) noncomputable definition ceil (x : ℝ) : ℤ := - floor (-x) theorem floor_spec (x : ℝ) : of_rat (of_int (floor x)) ≤ x := and.left (some_spec (ex_floor x)) theorem floor_largest {x : ℝ} {z : ℤ} (Hz : z > floor x) : x < of_rat (of_int z) := begin apply lt_of_not_ge, cases some_spec (ex_floor x), apply a_1 _ Hz end theorem ceil_spec (x : ℝ) : of_rat (of_int (ceil x)) ≥ x := begin rewrite [↑ceil, of_int_neg, of_rat_neg], apply iff.mp !le_neg_iff_le_neg, apply floor_spec end theorem ceil_smallest {x : ℝ} {z : ℤ} (Hz : z < ceil x) : x > of_rat (of_int z) := begin rewrite ↑ceil at Hz, let Hz' := floor_largest (iff.mp !int.lt_neg_iff_lt_neg Hz), rewrite [of_int_neg at Hz', of_rat_neg at Hz'], apply lt_of_neg_lt_neg Hz' end theorem floor_succ (x : ℝ) : (floor x) + 1 = floor (x + 1) := begin apply by_contradiction, intro H, cases int.lt_or_gt_of_ne H with [Hlt, Hgt], let Hl := floor_largest (iff.mp !int.add_lt_iff_lt_sub_right Hlt), rewrite [of_int_sub at Hl, -of_rat_sub at Hl], apply not_le_of_gt (iff.mpr !add_lt_iff_lt_sub_right Hl) !floor_spec, let Hl := floor_largest Hgt, rewrite [of_int_add at Hl, -of_rat_add at Hl], apply not_le_of_gt (lt_of_add_lt_add_right Hl) !floor_spec end theorem floor_succ_lt (x : ℝ) : floor (x - 1) < floor x := begin apply @int.lt_of_add_lt_add_right _ 1, rewrite [floor_succ (x - 1), sub_add_cancel], apply int.lt_add_of_pos_right dec_trivial end theorem ceil_succ (x : ℝ) : ceil x < ceil (x + 1) := begin rewrite [↑ceil, neg_add], apply int.neg_lt_neg, apply floor_succ_lt end end ints -------------------------------------------------- -- supremum property -- this development roughly follows the proof of completeness done in Isabelle. -- It does not depend on the previous proof of Cauchy completeness. Much of the same -- machinery can be used to show that Cauchy completeness implies the supremum property. section supremum open prod nat local postfix `~` := nat_of_pnat -- The top part of this section could be refactored. What is the appropriate place to define -- bounds, supremum, etc? In algebra/ordered_field? They potentially apply to more than just ℝ. local notation 2 := (1 : ℚ) + 1 parameter X : ℝ → Prop -- this definition belongs somewhere else. Where? definition rpt {A : Type} (op : A → A) : ℕ → A → A | rpt 0 := λ a, a | rpt (succ k) := λ a, op (rpt k a) definition ub (x : ℝ) := ∀ y : ℝ, X y → y ≤ x definition sup (x : ℝ) := ub x ∧ ∀ y : ℝ, ub y → x ≤ y definition lb (x : ℝ) := ∀ y : ℝ, X y → x ≤ y definition inf (x : ℝ) := lb x ∧ ∀ y : ℝ, lb y → y ≤ x parameter elt : ℝ hypothesis inh : X elt parameter bound : ℝ hypothesis bdd : ub bound include inh bdd -- this should exist somewhere, no? I can't find it theorem not_forall_of_exists_not {A : Type} {P : A → Prop} (H : ∃ a : A, ¬ P a) : ¬ ∀ a : A, P a := begin intro Hall, cases H with [a, Ha], apply Ha (Hall a) end definition avg (a b : ℚ) := a / 2 + b / 2 noncomputable definition bisect (ab : ℚ × ℚ) := if ub (avg (pr1 ab) (pr2 ab)) then (pr1 ab, (avg (pr1 ab) (pr2 ab))) else (avg (pr1 ab) (pr2 ab), pr2 ab) noncomputable definition under : ℚ := of_int (floor (elt - 1)) theorem under_spec1 : of_rat under < elt := have H : of_rat under < of_rat (of_int (floor elt)), begin apply of_rat_lt_of_rat_of_lt, apply iff.mpr !of_int_lt_of_int, apply floor_succ_lt end, lt_of_lt_of_le H !floor_spec theorem under_spec : ¬ ub under := begin rewrite ↑ub, apply not_forall_of_exists_not, existsi elt, apply iff.mpr not_implies_iff_and_not, apply and.intro, apply inh, apply not_le_of_gt under_spec1 end noncomputable definition over : ℚ := of_int (ceil (bound + 1)) -- b theorem over_spec1 : bound < of_rat over := have H : of_rat (of_int (ceil bound)) < of_rat over, begin apply of_rat_lt_of_rat_of_lt, apply iff.mpr !of_int_lt_of_int, apply ceil_succ end, lt_of_le_of_lt !ceil_spec H theorem over_spec : ub over := begin rewrite ↑ub, intro y Hy, apply le_of_lt, apply lt_of_le_of_lt, apply bdd, apply Hy, apply over_spec1 end noncomputable definition under_seq := λ n : ℕ, pr1 (rpt bisect n (under, over)) -- A noncomputable definition over_seq := λ n : ℕ, pr2 (rpt bisect n (under, over)) -- B noncomputable definition avg_seq := λ n : ℕ, avg (over_seq n) (under_seq n) -- C theorem avg_symm (n : ℕ) : avg_seq n = avg (under_seq n) (over_seq n) := by rewrite [↑avg_seq, ↑avg, rat.add.comm] theorem over_0 : over_seq 0 = over := rfl theorem under_0 : under_seq 0 = under := rfl theorem succ_helper (n : ℕ) : avg (pr1 (rpt bisect n (under, over))) (pr2 (rpt bisect n (under, over))) = avg_seq n := by rewrite avg_symm theorem under_succ (n : ℕ) : under_seq (succ n) = (if ub (avg_seq n) then under_seq n else avg_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr1 (bisect (rpt bisect n (under, over))) = under_seq n, by rewrite [↑under_seq, ↑bisect at {2}, -succ_helper at Hub, if_pos Hub], apply H, rewrite [if_neg Hub], have H : pr1 (bisect (rpt bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_neg Hub, avg_symm], apply H end theorem over_succ (n : ℕ) : over_seq (succ n) = (if ub (avg_seq n) then avg_seq n else over_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr2 (bisect (rpt bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_pos Hub, avg_symm], apply H, rewrite [if_neg Hub], have H : pr2 (bisect (rpt bisect n (under, over))) = over_seq n, by rewrite [↑over_seq, ↑bisect at {2}, -succ_helper at Hub, if_neg Hub], apply H end theorem width (n : ℕ) : over_seq n - under_seq n = (over - under) / (rat.pow 2 n) := nat.induction_on n (by xrewrite [over_0, under_0, rat.pow_zero, rat.div_one]) (begin intro a Ha, rewrite [over_succ, under_succ], let Hou := calc (over_seq a) / 2 - (under_seq a) / 2 = ((over - under) / rat.pow 2 a) / 2 : by rewrite [rat.div_sub_div_same, Ha] ... = (over - under) / (rat.pow 2 a * 2) : rat.div_div_eq_div_mul (rat.ne_of_gt (rat.pow_pos dec_trivial _)) dec_trivial ... = (over - under) / rat.pow 2 (a + 1) : by rewrite rat.pow_add, cases em (ub (avg_seq a)), rewrite [*if_pos a_1, -add_one, -Hou, ↑avg_seq, ↑avg, rat.add.assoc, rat.div_two_sub_self], rewrite [*if_neg a_1, -add_one, -Hou, ↑avg_seq, ↑avg, rat.sub_add_eq_sub_sub, rat.sub_self_div_two] end) theorem binary_nat_bound (a : ℕ) : of_nat a ≤ (rat.pow 2 a) := nat.induction_on a (rat.zero_le_one) (take n, assume Hn, calc of_nat (succ n) = (of_nat n) + 1 : of_nat_add ... ≤ rat.pow 2 n + 1 : rat.add_le_add_right Hn ... ≤ rat.pow 2 n + rat.pow 2 n : rat.add_le_add_left (rat.pow_ge_one_of_ge_one rat.two_ge_one _) ... = rat.pow 2 (succ n) : rat.pow_two_add) theorem binary_bound (a : ℚ) : ∃ n : ℕ, a ≤ rat.pow 2 n := exists.intro (ubound a) (calc a ≤ of_nat (ubound a) : ubound_ge ... ≤ rat.pow 2 (ubound a) : binary_nat_bound) theorem rat_power_two_le (k : ℕ+) : rat_of_pnat k ≤ rat.pow 2 k~ := !binary_nat_bound theorem width_narrows : ∃ n : ℕ, over_seq n - under_seq n ≤ 1 := begin cases binary_bound (over - under) with [a, Ha], existsi a, rewrite (width a), apply rat.div_le_of_le_mul, apply rat.pow_pos dec_trivial, rewrite rat.mul_one, apply Ha end noncomputable definition over' := over_seq (some width_narrows) noncomputable definition under' := under_seq (some width_narrows) noncomputable definition over_seq' := λ n, over_seq (n + some width_narrows) noncomputable definition under_seq' := λ n, under_seq (n + some width_narrows) theorem over_seq'0 : over_seq' 0 = over' := by rewrite [↑over_seq', nat.zero_add] theorem under_seq'0 : under_seq' 0 = under' := by rewrite [↑under_seq', nat.zero_add] theorem under_over' : over' - under' ≤ 1 := some_spec width_narrows theorem width' (n : ℕ) : over_seq' n - under_seq' n ≤ 1 / rat.pow 2 n := nat.induction_on n (begin xrewrite [over_seq'0, under_seq'0, rat.pow_zero, rat.div_one], apply under_over' end) (begin intros a Ha, rewrite [↑over_seq' at *, ↑under_seq' at *, *succ_add at *, width at *, -add_one, -(add_one a), rat.pow_add, rat.pow_add _ a 1, *rat.pow_one], apply rat.div_mul_le_div_mul_of_div_le_div_pos' Ha dec_trivial end) theorem PA (n : ℕ) : ¬ ub (under_seq n) := nat.induction_on n (by rewrite under_0; apply under_spec) (begin intro a Ha, rewrite under_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) theorem PB (n : ℕ) : ub (over_seq n) := nat.induction_on n (by rewrite over_0; apply over_spec) (begin intro a Ha, rewrite over_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) theorem under_lt_over : under < over := begin cases exists_not_of_not_forall under_spec with [x, Hx], cases iff.mp not_implies_iff_and_not Hx with [HXx, Hxu], apply lt_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply over_spec _ HXx end theorem under_seq_lt_over_seq : ∀ m n : ℕ, under_seq m < over_seq n := begin intros, cases exists_not_of_not_forall (PA m) with [x, Hx], cases iff.mp not_implies_iff_and_not Hx with [HXx, Hxu], apply lt_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply PB, apply HXx end theorem under_seq_lt_over_seq_single : ∀ n : ℕ, under_seq n < over_seq n := by intros; apply under_seq_lt_over_seq theorem under_seq'_lt_over_seq' : ∀ m n : ℕ, under_seq' m < over_seq' n := by intros; apply under_seq_lt_over_seq theorem under_seq'_lt_over_seq'_single : ∀ n : ℕ, under_seq' n < over_seq' n := by intros; apply under_seq_lt_over_seq theorem under_seq_mono_helper (i k : ℕ) : under_seq i ≤ under_seq (i + k) := (nat.induction_on k (by rewrite nat.add_zero; apply rat.le.refl) (begin intros a Ha, rewrite [add_succ, under_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite (if_pos Havg), apply Ha, rewrite [if_neg Havg, ↑avg_seq, ↑avg], apply rat.le.trans, apply Ha, rewrite -rat.add_halves at {1}, apply rat.add_le_add_right, apply rat.div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial end)) theorem under_seq_mono (i j : ℕ) (H : i ≤ j) : under_seq i ≤ under_seq j := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply under_seq_mono_helper end theorem over_seq_mono_helper (i k : ℕ) : over_seq (i + k) ≤ over_seq i := nat.induction_on k (by rewrite nat.add_zero; apply rat.le.refl) (begin intros a Ha, rewrite [add_succ, over_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite [if_pos Havg, ↑avg_seq, ↑avg], apply rat.le.trans, rotate 1, apply Ha, rotate 1, rewrite -{over_seq (i + a)}rat.add_halves at {2}, apply rat.add_le_add_left, apply rat.div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial, rewrite [if_neg Havg], apply Ha end) theorem over_seq_mono (i j : ℕ) (H : i ≤ j) : over_seq j ≤ over_seq i := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply over_seq_mono_helper end theorem rat_power_two_inv_ge (k : ℕ+) : 1 / rat.pow 2 k~ ≤ k⁻¹ := rat.div_le_div_of_le !rat_of_pnat_is_pos !rat_power_two_le open s theorem regular_lemma_helper {s : seq} {m n : ℕ+} (Hm : m ≤ n) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : rat.abs (s m - s n) ≤ m⁻¹ + n⁻¹ := begin cases H m n Hm with [T1under, T1over], cases H m m (!pnat.le.refl) with [T2under, T2over], apply rat.le.trans, apply rat.dist_bdd_within_interval, apply under_seq'_lt_over_seq'_single, rotate 1, repeat assumption, apply rat.le.trans, apply width', apply rat.le.trans, apply rat_power_two_inv_ge, apply rat.le_add_of_nonneg_right, apply rat.le_of_lt (!inv_pos) end theorem regular_lemma (s : seq) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : regular s := begin rewrite ↑regular, intros, cases em (m ≤ n) with [Hm, Hn], apply regular_lemma_helper Hm H, let T := regular_lemma_helper (pnat.le_of_lt (pnat.lt_of_not_le Hn)) H, rewrite [rat.abs_sub at T, {n⁻¹ + _}rat.add.comm at T], exact T end noncomputable definition p_under_seq : seq := λ n : ℕ+, under_seq' n~ noncomputable definition p_over_seq : seq := λ n : ℕ+, over_seq' n~ theorem under_seq_regular : regular p_under_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply under_seq_mono, apply nat.add_le_add_right Hni, apply rat.le_of_lt, apply under_seq_lt_over_seq end theorem over_seq_regular : regular p_over_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply over_seq_mono, apply nat.add_le_add_right Hni end noncomputable definition sup_over : ℝ := quot.mk (reg_seq.mk p_over_seq over_seq_regular) noncomputable definition sup_under : ℝ := quot.mk (reg_seq.mk p_under_seq under_seq_regular) theorem over_bound : ub sup_over := begin rewrite ↑ub, intros y Hy, apply le_of_le_reprs, intro n, apply PB, apply Hy end theorem under_lowest_bound : ∀ y : ℝ, ub y → sup_under ≤ y := begin intros y Hy, apply le_of_reprs_le, intro n, cases exists_not_of_not_forall (PA _) with [x, Hx], cases iff.mp not_implies_iff_and_not Hx with [HXx, Hxn], apply le.trans, apply le_of_lt, apply lt_of_not_ge Hxn, apply Hy, apply HXx end theorem under_over_equiv : p_under_seq ≡ p_over_seq := begin intros, apply rat.le.trans, have H : p_under_seq n < p_over_seq n, from !under_seq_lt_over_seq, rewrite [rat.abs_of_neg (iff.mpr !rat.sub_neg_iff_lt H), rat.neg_sub], apply width', apply rat.le.trans, apply rat_power_two_inv_ge, apply rat.le_add_of_nonneg_left, apply rat.le_of_lt !inv_pos end theorem under_over_eq : sup_under = sup_over := quot.sound under_over_equiv theorem ex_sup_of_inh_of_bdd : ∃ x : ℝ, sup x := exists.intro sup_over (and.intro over_bound (under_over_eq ▸ under_lowest_bound)) end supremum definition bounding_set (X : ℝ → Prop) (x : ℝ) : Prop := ∀ y : ℝ, X y → x ≤ y theorem ex_inf_of_inh_of_bdd (X : ℝ → Prop) (elt : ℝ) (inh : X elt) (bound : ℝ) (bdd : lb X bound) : ∃ x : ℝ, inf X x := begin have Hinh : bounding_set X bound, begin intros y Hy, apply bdd, apply Hy end, have Hub : ub (bounding_set X) elt, begin intros y Hy, apply Hy, apply inh end, cases ex_sup_of_inh_of_bdd _ _ Hinh _ Hub with [supr, Hsupr], existsi supr, cases Hsupr with [Hubs1, Hubs2], apply and.intro, intros, apply Hubs2, intros z Hz, apply Hz, apply a, intros y Hlby, apply Hubs1, intros z Hz, apply Hlby, apply Hz end end real
3a908bab22f02a962e5170f18996229201ce1722
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/analysis/special_functions/exp_log.lean
75339936a264d49a381743084fddd53e3392a0f4
[ "Apache-2.0" ]
permissive
sflicht/mathlib
220fd16e463928110e7b0a50bbed7b731979407f
1b2048d7195314a7e34e06770948ee00f0ac3545
refs/heads/master
1,665,934,056,043
1,591,373,803,000
1,591,373,803,000
269,815,267
0
0
Apache-2.0
1,591,402,068,000
1,591,402,067,000
null
UTF-8
Lean
false
false
21,845
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 data.complex.exponential import analysis.complex.basic import analysis.calculus.mean_value /-! # Complex and real exponential, real logarithm ## Main statements This file establishes the basic analytical properties of the complex and real exponential functions (continuity, differentiability, computation of the derivative). It also contains the definition of the real logarithm function (as the inverse of the exponential on `(0, +∞)`, extended to `ℝ` by setting `log (-x) = log x`) and its basic properties (continuity, differentiability, formula for the derivative). The complex logarithm is *not* defined in this file as it relies on trigonometric functions. See instead `trigonometric.lean`. ## Tags exp, log -/ noncomputable theory open finset filter metric asymptotics 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), have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) := metric.ball_mem_nhds 0 zero_lt_one, apply filter.mem_sets_of_superset this (λz hz, _), simp only [metric.mem_ball, dist_zero_right] at hz, simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow, zero_add, set.mem_set_of_eq], calc ∥exp (x + z) - exp x - z * exp x∥ = ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring } ... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _ ... ≤ ∥exp x∥ * ∥z∥^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _) end lemma differentiable_exp : differentiable ℂ exp := λx, (has_deriv_at_exp x).differentiable_at 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 [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous end complex section variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} 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 differentiable_within_at.cexp (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.exp (f x)) s x := hf.has_deriv_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_deriv_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 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 namespace real variables {x y z : ℝ} lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_exp x) lemma differentiable_exp : differentiable ℝ exp := λx, (has_deriv_at_exp x).differentiable_at 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 [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous end real section /-! Register lemmas for the derivatives of the composition of `real.exp`, `real.cos`, `real.sin`, `real.cosh` and `real.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! `real.exp`-/ 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 differentiable_within_at.exp (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.exp (f x)) s x := hf.has_deriv_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_deriv_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 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 namespace real variables {x y z : ℝ} lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp, from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp ⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩, match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := this hx1 end /-- The real logarithm function, equal to the inverse of the exponential for `x > 0`, to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to `(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and the derivative of `log` is `1/x` away from `0`. -/ noncomputable def log (x : ℝ) : ℝ := if hx : x ≠ 0 then classical.some (exists_exp_eq_of_pos (abs_pos_iff.mpr hx)) else 0 lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = abs x := by { rw [log, dif_pos hx], exact classical.some_spec (exists_exp_eq_of_pos ((abs_pos_iff.mpr hx))) } lemma exp_log (hx : 0 < x) : exp (log x) = x := by { rw exp_log_eq_abs (ne_of_gt hx), exact abs_of_pos hx } lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x := by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx } @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] @[simp] lemma log_abs (x : ℝ) : log (abs x) = log x := begin by_cases h : x = 0, { simp [h] }, { apply exp_injective, rw [exp_log_eq_abs h, exp_log_eq_abs, abs_abs], simp [h] } end @[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x := by rw [← log_abs x, ← log_abs (-x), abs_neg] lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul] lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x := by { rw ← log_one, exact log_lt_log_iff (by norm_num) hx } lemma log_pos (hx : 1 < x) : 0 < log x := (log_pos_iff (lt_trans zero_lt_one hx)).2 hx lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg : 1 ≤ x → 0 ≤ log x := by { intro, rwa [← log_one, log_le_log], norm_num, linarith } lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 := begin by_cases x_zero : x = 0, { simp [x_zero] }, { rwa [← log_one, log_le_log (lt_of_le_of_ne hx (ne.symm x_zero))], norm_num } end section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos (le_of_lt this) hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos.2 x.2) y.2), have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul (ne_of_gt x.2) (ne_of_gt h.2), simp only [this, log_mul (ne_of_gt x.2) one_ne_zero, log_one], exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val), have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos.2 x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_val, suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` are provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma has_deriv_at_log_of_pos (hx : 0 < x) : has_deriv_at log x⁻¹ x := have has_deriv_at log (exp $ log x)⁻¹ x, from (has_deriv_at_exp $ log x).of_local_left_inverse (continuous_at_log hx) (ne_of_gt $ exp_pos _) $ eventually.mono (mem_nhds_sets is_open_Ioi hx) @exp_log, by rwa [exp_log hx] at this lemma has_deriv_at_log (hx : x ≠ 0) : has_deriv_at log x⁻¹ x := begin by_cases h : 0 < x, { exact has_deriv_at_log_of_pos h }, push_neg at h, convert ((has_deriv_at_log_of_pos (neg_pos.mpr (lt_of_le_of_ne h hx))) .comp x (has_deriv_at_id x).neg), { ext y, exact (log_neg_eq_log y).symm }, { field_simp [hx] } end end real section log_differentiable open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} lemma has_deriv_within_at.log (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, log (f y)) (f' / (f x)) s x := begin convert (has_deriv_at_log hx).comp_has_deriv_within_at x hf, field_simp end lemma has_deriv_at.log (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, log (f y)) (f' / f x) x := begin rw ← has_deriv_within_at_univ at *, exact hf.log hx end lemma differentiable_within_at.log (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, log (f x)) s x := (hf.has_deriv_within_at.log hx).differentiable_within_at @[simp] lemma differentiable_at.log (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, log (f x)) x := (hf.has_deriv_at.log hx).differentiable_at lemma differentiable_on.log (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, log (f x)) s := λx h, (hf x h).log (hx x h) @[simp] lemma differentiable.log (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, log (f x)) := λx, (hf x).log (hx x) lemma deriv_within_log' (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, log (f x)) s x = (deriv_within f s x) / (f x) := (hf.has_deriv_within_at.log hx).deriv_within hxs @[simp] lemma deriv_log' (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, log (f x)) x = (deriv f x) / (f x) := (hf.has_deriv_at.log hx).deriv end log_differentiable namespace real /-- The real exponential function tends to `+∞` at `+∞`. -/ lemma tendsto_exp_at_top : tendsto exp at_top at_top := begin have A : tendsto (λx:ℝ, x + 1) at_top at_top := tendsto_at_top_add_const_right at_top 1 tendsto_id, have B : ∀ᶠ x in at_top, x + 1 ≤ exp x, { have : ∀ᶠ (x : ℝ) in at_top, 0 ≤ x := mem_at_top 0, filter_upwards [this], exact λx hx, add_one_le_exp_of_nonneg hx }, exact tendsto_at_top_mono' at_top B A end /-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0` at +infinity -/ lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm) /-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/ lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top := begin have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n, have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos, have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n, { assume x hx, let y := x / (n+1), have y_pos : 0 < y := div_pos hx n_pos, have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc exp y = exp y * 1 : by simp ... ≤ exp y * (exp y / y)^n : begin apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)), apply one_le_div_of_le _ y_pos, apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)), exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one) end ... = exp y * exp (n * y) / y^n : by rw [div_pow, exp_nat_mul, mul_div_assoc] ... = exp ((n + 1) * y) / y^n : by rw [← exp_add, add_mul, one_mul, add_comm] ... = exp x / (x / (n+1))^n : by { dsimp [y], rw mul_div_cancel' _ n_ne_zero } ... = (n+1)^n * (exp x / x^n) : by rw [← mul_div_assoc, div_pow, div_div_eq_mul_div, mul_comm], rwa div_le_iff' (pow_pos n_pos n) }, have B : ∀ᶠ x in at_top, exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n := mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩, have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top := tendsto_at_top_div (pow_pos n_pos n) (tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)), exact tendsto_at_top_mono' at_top B C end /-- The function `x^n * exp(-x)` tends to `0` at `+∞`, for any natural number `n`. -/ lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx, by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg] open_locale big_operators /-- A crude lemma estimating the difference between `log (1-x)` and its Taylor series at `0`, where the main point of the bound is that it tends to `0`. The goal is to deduce the series expansion of the logarithm, in `has_sum_pow_div_log_of_abs_lt_1`. -/ lemma abs_log_sub_add_sum_range_le {x : ℝ} (h : abs x < 1) (n : ℕ) : abs ((∑ i in range n, x^(i+1)/(i+1)) + log (1-x)) ≤ (abs x)^(n+1) / (1 - abs x) := begin /- For the proof, we show that the derivative of the function to be estimated is small, and then apply the mean value inequality. -/ let F : ℝ → ℝ := λ x, ∑ i in range n, x^(i+1)/(i+1) + log (1-x), -- First step: compute the derivative of `F` have A : ∀ y ∈ set.Ioo (-1 : ℝ) 1, deriv F y = - (y^n) / (1 - y), { assume y hy, have : (∑ i in range n, (↑i + 1) * y ^ i / (↑i + 1)) = (∑ i in range n, y ^ i), { congr, ext i, have : (i : ℝ) + 1 ≠ 0 := ne_of_gt (nat.cast_add_one_pos i), field_simp [this, mul_comm] }, field_simp [F, this, ← geom_series_def, geom_sum (ne_of_lt hy.2), sub_ne_zero_of_ne (ne_of_gt hy.2), sub_ne_zero_of_ne (ne_of_lt hy.2)], ring }, -- second step: show that the derivative of `F` is small have B : ∀ y ∈ set.Icc (-abs x) (abs x), abs (deriv F y) ≤ (abs x)^n / (1 - abs x), { assume y hy, have : y ∈ set.Ioo (-(1 : ℝ)) 1 := ⟨lt_of_lt_of_le (neg_lt_neg h) hy.1, lt_of_le_of_lt hy.2 h⟩, calc abs (deriv F y) = abs (-(y^n) / (1 - y)) : by rw [A y this] ... ≤ (abs x)^n / (1 - abs x) : begin have : abs y ≤ abs x := abs_le_of_le_of_neg_le hy.2 (by linarith [hy.1]), have : 0 < 1 - abs x, by linarith, have : 1 - abs x ≤ abs (1 - y) := le_trans (by linarith [hy.2]) (le_abs_self _), simp only [← pow_abs, abs_div, abs_neg], apply_rules [div_le_div, pow_nonneg, abs_nonneg, pow_le_pow_of_le_left] end }, -- third step: apply the mean value inequality have C : ∥F x - F 0∥ ≤ ((abs x)^n / (1 - abs x)) * ∥x - 0∥, { have : ∀ y ∈ set.Icc (- abs x) (abs x), differentiable_at ℝ F y, { assume y hy, have : 1 - y ≠ 0 := sub_ne_zero_of_ne (ne_of_gt (lt_of_le_of_lt hy.2 h)), simp [F, this] }, apply convex.norm_image_sub_le_of_norm_deriv_le this B (convex_Icc _ _) _ _, { simpa using abs_nonneg x }, { simp [le_abs_self x, neg_le.mp (neg_le_abs_self x)] } }, -- fourth step: conclude by massaging the inequality of the third step simpa [F, norm_eq_abs, div_mul_eq_mul_div, pow_succ'] using C end /-- Power series expansion of the logarithm around `1`. -/ theorem has_sum_pow_div_log_of_abs_lt_1 {x : ℝ} (h : abs x < 1) : has_sum (λ (n : ℕ), x ^ (n + 1) / (n + 1)) (-log (1 - x)) := begin rw has_sum_iff_tendsto_nat_of_summable, show tendsto (λ (n : ℕ), ∑ (i : ℕ) in range n, x ^ (i + 1) / (i + 1)) at_top (𝓝 (-log (1 - x))), { rw [tendsto_iff_norm_tendsto_zero], simp only [norm_eq_abs, sub_neg_eq_add], refine squeeze_zero (λ n, abs_nonneg _) (abs_log_sub_add_sum_range_le h) _, suffices : tendsto (λ (t : ℕ), abs x ^ (t + 1) / (1 - abs x)) at_top (𝓝 (abs x * 0 / (1 - abs x))), by simpa, simp only [pow_succ], refine (tendsto_const_nhds.mul _).div_const, exact tendsto_pow_at_top_nhds_0_of_lt_1 (abs_nonneg _) h }, show summable (λ (n : ℕ), x ^ (n + 1) / (n + 1)), { refine summable_of_norm_bounded _ (summable_geometric_of_lt_1 (abs_nonneg _) h) (λ i, _), calc ∥x ^ (i + 1) / (i + 1)∥ = abs x ^ (i+1) / (i+1) : begin have : (0 : ℝ) ≤ i + 1 := le_of_lt (nat.cast_add_one_pos i), rw [norm_eq_abs, abs_div, ← pow_abs, abs_of_nonneg this], end ... ≤ abs x ^ (i+1) / (0 + 1) : begin apply_rules [div_le_div_of_le_left, pow_nonneg, abs_nonneg, add_le_add_right (nat.cast_nonneg i)], norm_num, end ... ≤ abs x ^ i : by simpa [pow_succ'] using mul_le_of_le_one_right (pow_nonneg (abs_nonneg x) i) (le_of_lt h) } end end real
db9c41beab9f42eace688bfb47a0829fa8bb3656
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/seq/computation.lean
05eb43361fc9417643179c077e9550ae31cdd958
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
37,484
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Coinductive formalization of unbounded computations. -/ import data.stream logic.relator tactic.basic universes u v w /- coinductive computation (α : Type u) : Type u | return : α → computation α | think : computation α → computation α -/ /-- `computation α` is the type of unbounded computations returning `α`. An element of `computation α` is an infinite sequence of `option α` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def computation (α : Type u) : Type u := { f : stream (option α) // ∀ {n a}, f n = some a → f (n+1) = some a } namespace computation variables {α : Type u} {β : Type v} {γ : Type w} -- constructors /-- `return a` is the computation that immediately terminates with result `a`. -/ def return (a : α) : computation α := ⟨stream.const (some a), λn a', id⟩ instance : has_coe α (computation α) := ⟨return⟩ /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : computation α) : computation α := ⟨none :: c.1, λn a h, by {cases n with n, contradiction, exact c.2 h}⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : computation α) : ℕ → computation α | 0 := c | (n+1) := think (thinkN n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = return a` or `none` if `c = think c'`. -/ def head (c : computation α) : option α := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = return a` or `c'` if `c = think c'`. -/ def tail (c : computation α) : computation α := ⟨c.1.tail, λ n a, let t := c.2 in t⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : computation α := ⟨stream.const none, λn a', id⟩ /-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def run_for : computation α → ℕ → option α := subtype.val /-- `destruct c` is the destructor for `computation α` as a coinductive type. It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/ def destruct (c : computation α) : α ⊕ computation α := match c.1 0 with | none := sum.inr (tail c) | some a := sum.inl a end /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ meta def run : computation α → α | c := match destruct c with | sum.inl a := a | sum.inr ca := run ca end theorem destruct_eq_ret {s : computation α} {a : α} : destruct s = sum.inl a → s = return a := begin dsimp [destruct], induction f0 : s.1 0; intro h, { contradiction }, { apply subtype.eq, funext n, induction n with n IH, { injection h with h', rwa h' at f0 }, { exact s.2 IH } } end theorem destruct_eq_think {s : computation α} {s'} : destruct s = sum.inr s' → s = think s' := begin dsimp [destruct], induction f0 : s.1 0 with a'; intro h, { injection h with h', rw ←h', cases s with f al, apply subtype.eq, dsimp [think, tail], rw ←f0, exact (stream.eta f).symm }, { contradiction } end @[simp] theorem destruct_ret (a : α) : destruct (return a) = sum.inl a := rfl @[simp] theorem destruct_think : ∀ s : computation α, destruct (think s) = sum.inr s | ⟨f, al⟩ := rfl @[simp] theorem destruct_empty : destruct (empty α) = sum.inr (empty α) := rfl @[simp] theorem head_ret (a : α) : head (return a) = some a := rfl @[simp] theorem head_think (s : computation α) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty α) = none := rfl @[simp] theorem tail_ret (a : α) : tail (return a) = return a := rfl @[simp] theorem tail_think (s : computation α) : tail (think s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, think]; rw [stream.tail_cons] @[simp] theorem tail_empty : tail (empty α) = empty α := rfl theorem think_empty : empty α = think (empty α) := destruct_eq_think destruct_empty def cases_on {C : computation α → Sort v} (s : computation α) (h1 : ∀ a, C (return a)) (h2 : ∀ s, C (think s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_ret H, apply h1 }, { cases v with a s', rw destruct_eq_think H, apply h2 } end def corec.F (f : β → α ⊕ β) : α ⊕ β → option α × (α ⊕ β) | (sum.inl a) := (some a, sum.inl a) | (sum.inr b) := (match f b with | sum.inl a := some a | sum.inr b' := none end, f b) /-- `corec f b` is the corecursor for `computation α` as a coinductive type. If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : β → α ⊕ β) (b : β) : computation α := begin refine ⟨stream.corec' (corec.F f) (sum.inr b), λn a' h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (sum.inr b)).2 n = some a', revert h, generalize : sum.inr b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = some a' → (corec.F f (corec.F f o).2).1 = some a', cases o with a b; intro h, { exact h }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with a b', { exact h }, { contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end /-- left map of `⊕` -/ def lmap (f : α → β) : α ⊕ γ → β ⊕ γ | (sum.inl a) := sum.inl (f a) | (sum.inr b) := sum.inr b /-- right map of `⊕` -/ def rmap (f : β → γ) : α ⊕ β → α ⊕ γ | (sum.inl a) := sum.inl a | (sum.inr b) := sum.inr (f b) attribute [simp] lmap rmap @[simp] def corec_eq (f : β → α ⊕ β) (b : β) : destruct (corec f b) = rmap (corec f) (f b) := begin dsimp [corec, destruct], change stream.corec' (corec.F f) (sum.inr b) 0 with corec.F._match_1 (f b), induction h : f b with a b', { refl }, dsimp [corec.F, destruct], apply congr_arg, apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h end section bisim variable (R : computation α → computation α → Prop) local infix ~ := R def bisim_o : α ⊕ computation α → α ⊕ computation α → Prop | (sum.inl a) (sum.inl a') := a = a' | (sum.inr s) (sum.inr s') := R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : computation α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, dsimp at this, rw this, assumption }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { simp at this, simp [*] } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. protected def mem (a : α) (s : computation α) := some a ∈ s.1 instance : has_mem α (computation α) := ⟨computation.mem⟩ theorem le_stable (s : computation α) {a m n} (h : m ≤ n) : s.1 m = some a → s.1 n = some a := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} theorem mem_unique : relator.left_unique ((∈) : α → computation α → Prop) := λa s b ⟨m, ha⟩ ⟨n, hb⟩, by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) /-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/ @[class] def terminates (s : computation α) : Prop := ∃ a, a ∈ s theorem terminates_of_mem {s : computation α} {a : α} : a ∈ s → terminates s := exists.intro a theorem terminates_def (s : computation α) : terminates s ↔ ∃ n, (s.1 n).is_some := ⟨λ⟨a, n, h⟩, ⟨n, by {dsimp [stream.nth] at h, rw ←h, exact rfl}⟩, λ⟨n, h⟩, ⟨option.get h, n, (option.eq_some_of_is_some h).symm⟩⟩ theorem ret_mem (a : α) : a ∈ return a := exists.intro 0 rfl theorem eq_of_ret_mem {a a' : α} (h : a' ∈ return a) : a' = a := mem_unique h (ret_mem _) instance ret_terminates (a : α) : terminates (return a) := terminates_of_mem (ret_mem _) theorem think_mem {s : computation α} {a} : a ∈ s → a ∈ think s | ⟨n, h⟩ := ⟨n+1, h⟩ instance think_terminates (s : computation α) : ∀ [terminates s], terminates (think s) | ⟨a, n, h⟩ := ⟨a, n+1, h⟩ theorem of_think_mem {s : computation α} {a} : a ∈ think s → a ∈ s | ⟨n, h⟩ := by {cases n with n', contradiction, exact ⟨n', h⟩} theorem of_think_terminates {s : computation α} : terminates (think s) → terminates s | ⟨a, h⟩ := ⟨a, of_think_mem h⟩ theorem not_mem_empty (a : α) : a ∉ empty α := λ ⟨n, h⟩, by clear _fun_match; contradiction theorem not_terminates_empty : ¬ terminates (empty α) := λ ⟨a, h⟩, not_mem_empty a h theorem eq_empty_of_not_terminates {s} (H : ¬ terminates s) : s = empty α := begin apply subtype.eq, funext n, induction h : s.val n, {refl}, refine absurd _ H, exact ⟨_, _, h.symm⟩ end theorem thinkN_mem {s : computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s | 0 := iff.rfl | (n+1) := iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : computation α) : ∀ [terminates s] n, terminates (thinkN s n) | ⟨a, h⟩ n := ⟨a, (thinkN_mem n).2 h⟩ theorem of_thinkN_terminates (s : computation α) (n) : terminates (thinkN s n) → terminates s | ⟨a, h⟩ := ⟨a, (thinkN_mem _).1 h⟩ /-- `promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def promises (s : computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a' infix ` ~> `:50 := promises theorem mem_promises {s : computation α} {a : α} : a ∈ s → s ~> a := λ h a', mem_unique h theorem empty_promises (a : α) : empty α ~> a := λ a' h, absurd h (not_mem_empty _) section get variables (s : computation α) [h : terminates s] include s h /-- `length s` gets the number of steps of a terminating computation -/ def length : ℕ := nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : α := option.get (nat.find_spec $ (terminates_def _).1 h) theorem get_mem : get s ∈ s := exists.intro (length s) (option.eq_some_of_is_some _).symm theorem get_eq_of_mem {a} : a ∈ s → get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a → a ∈ s := by intro h; rw ←h; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ $ let ⟨n, h⟩ := get_mem s in ⟨n+1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ $ (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := λ a, get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by unfreezeI; cases h with a' h; rw p h; exact h theorem get_eq_of_promises {a} : s ~> a → get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def results (s : computation α) (a : α) (n : ℕ) := ∃ (h : a ∈ s), @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : computation α) [T : terminates s] : results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : computation α) [T : terminates s] {a} (h : a ∈ s) : results s a (length s) := by rw ←get_eq_of_mem _ h; apply results_of_terminates theorem results.mem {s : computation α} {a n} : results s a n → a ∈ s | ⟨m, _⟩ := m theorem results.terminates {s : computation α} {a n} (h : results s a n) : terminates s := terminates_of_mem h.mem theorem results.length {s : computation α} {a n} [T : terminates s] : results s a n → length s = n | ⟨_, h⟩ := h theorem results.val_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : a = b := mem_unique h1.mem h2.mem theorem results.len_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [←h1.length, h2.length] theorem exists_results_of_mem {s : computation α} {a} (h : a ∈ s) : ∃ n, results s a n := by haveI := terminates_of_mem h; exact ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_ret (a : α) : get (return a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_ret (a : α) : length (return a) = 0 := let h := computation.ret_terminates a in nat.eq_zero_of_le_zero $ nat.find_min' ((terminates_def (return a)).1 h) rfl theorem results_ret (a : α) : results (return a) a 0 := ⟨_, length_ret _⟩ @[simp] theorem length_think (s : computation α) [h : terminates s] : length (think s) = length s + 1 := begin apply le_antisymm, { exact nat.find_min' _ (nat.find_spec ((terminates_def _).1 h)) }, { have : (option.is_some ((think s).val (length (think s))) : Prop) := nat.find_spec ((terminates_def _).1 s.think_terminates), cases length (think s) with n, { contradiction }, { apply nat.succ_le_succ, apply nat.find_min', apply this } } end theorem results_think {s : computation α} {a n} (h : results s a n) : results (think s) a (n + 1) := by haveI := h.terminates; exact ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : computation α} {a n} (h : results (think s) a n) : ∃ m, results s a m ∧ n = m + 1 := begin haveI := of_think_terminates h.terminates, have := results_of_terminates' _ (of_think_mem h.mem), exact ⟨_, this, results.len_unique h (results_think this)⟩, end @[simp] theorem results_think_iff {s : computation α} {a n} : results (think s) a (n + 1) ↔ results s a n := ⟨λ h, let ⟨n', r, e⟩ := of_results_think h in by injection e with h'; rwa h', results_think⟩ theorem results_thinkN {s : computation α} {a m} : ∀ n, results s a m → results (thinkN s n) a (m + n) | 0 h := h | (n+1) h := results_think (results_thinkN n h) theorem results_thinkN_ret (a : α) (n) : results (thinkN (return a) n) a n := by have := results_thinkN n (results_ret a); rwa zero_add at this @[simp] theorem length_thinkN (s : computation α) [h : terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : computation α} {a n} (h : results s a n) : s = thinkN (return a) n := begin revert s, induction n with n IH; intro s; apply cases_on s (λ a', _) (λ s, _); intro h, { rw ←eq_of_ret_mem h.mem, refl }, { cases of_results_think h with n h, cases h, contradiction }, { have := h.len_unique (results_ret _), contradiction }, { rw IH (results_think_iff.1 h), refl } end theorem eq_thinkN' (s : computation α) [h : terminates s] : s = thinkN (return (get s)) (length s) := eq_thinkN (results_of_terminates _) def mem_rec_on {C : computation α → Sort v} {a s} (M : a ∈ s) (h1 : C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := begin haveI T := terminates_of_mem M, rw [eq_thinkN' s, get_eq_of_mem s M], generalize : length s = n, induction n with n IH, exacts [h1, h2 _ IH] end def terminates_rec_on {C : computation α → Sort v} (s) [terminates s] (h1 : ∀ a, C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := mem_rec_on (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : α → β) : computation α → computation β | ⟨s, al⟩ := ⟨s.map (λo, option.cases_on o none (some ∘ f)), λn b, begin dsimp [stream.map, stream.nth], induction e : s n with a; intro h, { contradiction }, { rw [al e, ←h] } end⟩ def bind.G : β ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl b) := sum.inl b | (sum.inr cb') := sum.inr $ sum.inr cb' def bind.F (f : α → computation β) : computation α ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl ca) := match destruct ca with | sum.inl a := bind.G $ destruct (f a) | sum.inr ca' := sum.inr $ sum.inl ca' end | (sum.inr cb) := bind.G $ destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : computation α) (f : α → computation β) : computation β := corec (bind.F f) (sum.inl c) instance : has_bind computation := ⟨@bind⟩ theorem has_bind_eq_bind {β} (c : computation α) (f : α → computation β) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : computation (computation α)) : computation α := c >>= id @[simp] theorem map_ret (f : α → β) (a) : map f (return a) = return (f a) := rfl @[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [think, map]; rw stream.map_cons @[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by apply s.cases_on; intro; simp @[simp] theorem map_id : ∀ (s : computation α), map id s = s | ⟨f, al⟩ := begin apply subtype.eq; simp [map, function.comp], have e : (@option.rec α (λ_, option α) none some) = id, { funext x, cases x; refl }, simp [e, stream.map_id] end theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : computation α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), funext x, cases x with x; refl end @[simp] theorem ret_bind (a) (f : α → computation β) : bind (return a) f = f a := begin apply eq_of_bisim (λc₁ c₂, c₁ = bind (return a) f ∧ c₂ = f a ∨ c₁ = corec (bind.F f) (sum.inr c₂)), { intros c₁ c₂ h, exact match c₁, c₂, h with | ._, ._, or.inl ⟨rfl, rfl⟩ := begin simp [bind, bind.F], cases destruct (f a) with b cb; simp [bind.G] end | ._, c, or.inr rfl := begin simp [bind.F], cases destruct c with b cb; simp [bind.G] end end }, { simp } end @[simp] theorem think_bind (c) (f : α → computation β) : bind (think c) f = think (bind c f) := destruct_eq_think $ by simp [bind, bind.F] @[simp] theorem bind_ret (f : α → β) (s) : bind s (return ∘ f) = map f s := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind s (return ∘ f) ∧ c₂ = map f s), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := begin cases destruct c with b cb; simp end | _, _, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, exact or.inr ⟨s, rfl, rfl⟩ end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end @[simp] theorem bind_ret' (s : computation α) : bind s return = s := by rw bind_ret; change (λ x : α, x) with @id α; rw map_id @[simp] theorem bind_assoc (s : computation α) (f : α → computation β) (g : β → computation γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s (λ (x : α), bind (f x) g)), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := by cases destruct c with b cb; simp | ._, ._, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, { generalize : f s = fs, apply cases_on fs; intros t; simp, { cases destruct (g t) with b cb; simp } }, { exact or.inr ⟨s, rfl, rfl⟩ } end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end theorem results_bind {s : computation α} {f : α → computation β} {a b m n} (h1 : results s a m) (h2 : results (f a) b n) : results (bind s f) b (n + m) := begin have := h1.mem, revert m, apply mem_rec_on this _ (λ s IH, _); intros m h1, { rw [ret_bind], rw h1.len_unique (results_ret _), exact h2 }, { rw [think_bind], cases of_results_think h1 with m' h, cases h with h1 e, rw e, exact results_think (IH h1) } end theorem mem_bind {s : computation α} {f : α → computation β} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨m, h1⟩ := exists_results_of_mem h1, ⟨n, h2⟩ := exists_results_of_mem h2 in (results_bind h1 h2).mem instance terminates_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : computation α) (f : α → computation β) [T1 : terminates s] [T2 : terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique $ results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : computation α} {f : α → computation β} {b k} : results (bind s f) b k → ∃ a m n, results s a m ∧ results (f a) b n ∧ k = n + m := begin induction k with n IH generalizing s; apply cases_on s (λ a, _) (λ s', _); intro e, { simp [thinkN] at e, refine ⟨a, _, _, results_ret _, e, rfl⟩ }, { have := congr_arg head (eq_thinkN e), contradiction }, { simp at e, refine ⟨a, _, n+1, results_ret _, e, rfl⟩ }, { simp at e, exact let ⟨a, m, n', h1, h2, e'⟩ := IH e in by rw e'; exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ } end theorem exists_of_mem_bind {s : computation α} {f : α → computation β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨k, h⟩ := exists_results_of_mem h, ⟨a, m, n, h1, h2, e⟩ := of_results_bind h in ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : computation α} {f : α → computation β} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := λ b' bB, begin rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩, rw ←h1 a's at ba', exact h2 ba' end instance : monad computation := { map := @map, pure := @return, bind := @bind } instance : is_lawful_monad computation := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } theorem has_map_eq_map {β} (f : α → β) (c : computation α) : f <$> c = map f c := rfl @[simp] theorem return_def (a) : (_root_.return a : computation α) = return a := rfl @[simp] theorem map_ret' {α β} : ∀ (f : α → β) (a), f <$> return a = return (f a) := map_ret @[simp] theorem map_think' {α β} : ∀ (f : α → β) s, f <$> think s = think (f <$> s) := map_think theorem mem_map (f : α → β) {a} {s : computation α} (m : a ∈ s) : f a ∈ map f s := by rw ←bind_ret; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : α → β} {b : β} {s : computation α} (h : b ∈ map f s) : ∃ a, a ∈ s ∧ f a = b := by rw ←bind_ret at h; exact let ⟨a, as, fb⟩ := exists_of_mem_bind h in ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : α → β) (s : computation α) [terminates s] : terminates (map f s) := by rw ←bind_ret; apply_instance theorem terminates_map_iff (f : α → β) (s : computation α) : terminates (map f s) ↔ terminates s := ⟨λ⟨a, h⟩, let ⟨b, h1, _⟩ := exists_of_mem_map h in ⟨_, h1⟩, @computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning the first one that gives a result. -/ def orelse (c₁ c₂ : computation α) : computation α := @computation.corec α (computation α × computation α) (λ⟨c₁, c₂⟩, match destruct c₁ with | sum.inl a := sum.inl a | sum.inr c₁' := match destruct c₂ with | sum.inl a := sum.inl a | sum.inr c₂' := sum.inr (c₁', c₂') end end) (c₁, c₂) instance : alternative computation := { orelse := @orelse, failure := @empty, ..computation.monad } @[simp] theorem ret_orelse (a : α) (c₂ : computation α) : (return a <|> c₂) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_ret (c₁ : computation α) (a : α) : (think c₁ <|> return a) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_think (c₁ c₂ : computation α) : (think c₁ <|> think c₂) = think (c₁ <|> c₂) := destruct_eq_think $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem empty_orelse (c) : (empty α <|> c) = c := begin apply eq_of_bisim (λc₁ c₂, (empty α <|> c₂) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw ←think_empty, end @[simp] theorem orelse_empty (c : computation α) : (c <|> empty α) = c := begin apply eq_of_bisim (λc₁ c₂, (c₂ <|> empty α) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw←think_empty, end /-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result, or both loop forever. -/ def equiv (c₁ c₂ : computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂ infix ~ := equiv @[refl] theorem equiv.refl (s : computation α) : s ~ s := λ_, iff.rfl @[symm] theorem equiv.symm {s t : computation α} : s ~ t → t ~ s := λh a, (h a).symm @[trans] theorem equiv.trans {s t u : computation α} : s ~ t → t ~ u → s ~ u := λh1 h2 a, (h1 a).trans (h2 a) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ theorem equiv_of_mem {s t : computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := λa', ⟨λma, by rw mem_unique ma h1; exact h2, λma, by rw mem_unique ma h2; exact h1⟩ theorem terminates_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) : terminates c₁ ↔ terminates c₂ := exists_congr h theorem promises_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a := forall_congr (λa', imp_congr (h a') iff.rfl) theorem get_equiv {c₁ c₂ : computation α} (h : c₁ ~ c₂) [terminates c₁] [terminates c₂] : get c₁ = get c₂ := get_eq_of_mem _ $ (h _).2 $ get_mem _ theorem think_equiv (s : computation α) : think s ~ s := λ a, ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : computation α) (n) : thinkN s n ~ s := λ a, thinkN_mem n theorem bind_congr {s1 s2 : computation α} {f1 f2 : α → computation β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := λ b, ⟨λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_ret_of_mem {s : computation α} {a} (h : a ∈ s) : s ~ return a := equiv_of_mem h (ret_mem _) /-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def lift_rel (R : α → β → Prop) (ca : computation α) (cb : computation β) : Prop := (∀ {a}, a ∈ ca → ∃ {b}, b ∈ cb ∧ R a b) ∧ ∀ {b}, b ∈ cb → ∃ {a}, a ∈ ca ∧ R a b theorem lift_rel.swap (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel (function.swap R) cb ca ↔ lift_rel R ca cb := and_comm _ _ theorem lift_eq_iff_equiv (c₁ c₂ : computation α) : lift_rel (=) c₁ c₂ ↔ c₁ ~ c₂ := ⟨λ⟨h1, h2⟩ a, ⟨λ a1, let ⟨b, b2, ab⟩ := h1 a1 in by rwa ab, λ a2, let ⟨b, b1, ab⟩ := h2 a2 in by rwa ←ab⟩, λe, ⟨λ a a1, ⟨a, (e _).1 a1, rfl⟩, λ a a2, ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, ⟨λ a as, ⟨a, as, H a⟩, λ b bs, ⟨b, bs, H b⟩⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 ⟨l, r⟩, ⟨λ a a2, let ⟨b, b1, ab⟩ := r a2 in ⟨b, b1, H ab⟩, λ a a1, let ⟨b, b2, ab⟩ := l a1 in ⟨b, b2, H ab⟩⟩ theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s1 s2 s3 ⟨l1, r1⟩ ⟨l2, r2⟩, ⟨λ a a1, let ⟨b, b2, ab⟩ := l1 a1, ⟨c, c3, bc⟩ := l2 b2 in ⟨c, c3, H ab bc⟩, λ c c3, let ⟨b, b2, bc⟩ := r2 c3, ⟨a, a1, ab⟩ := r1 b2 in ⟨a, a1, H ab bc⟩⟩ theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ theorem lift_rel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) : lift_rel R s t → lift_rel S s t | ⟨l, r⟩ := ⟨λ a as, let ⟨b, bt, ab⟩ := l as in ⟨b, bt, H ab⟩, λ b bt, let ⟨a, as, ab⟩ := r bt in ⟨a, as, H ab⟩⟩ theorem terminates_of_lift_rel {R : α → β → Prop} {s t} : lift_rel R s t → (terminates s ↔ terminates t) | ⟨l, r⟩ := ⟨λ ⟨a, as⟩, let ⟨b, bt, ab⟩ := l as in ⟨b, bt⟩, λ ⟨b, bt⟩, let ⟨a, as, ab⟩ := r bt in ⟨a, as⟩⟩ theorem rel_of_lift_rel {R : α → β → Prop} {ca cb} : lift_rel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b | ⟨l, r⟩ a b ma mb := let ⟨b', mb', ab'⟩ := l ma in by rw mem_unique mb mb'; exact ab' theorem lift_rel_of_mem {R : α → β → Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : lift_rel R ca cb := ⟨λ a' ma', by rw mem_unique ma' ma; exact ⟨b, mb, ab⟩, λ b' mb', by rw mem_unique mb' mb; exact ⟨a, ma, ab⟩⟩ theorem exists_of_lift_rel_left {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {a} (h : a ∈ ca) : ∃ {b}, b ∈ cb ∧ R a b := H.left h theorem exists_of_lift_rel_right {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {b} (h : b ∈ cb) : ∃ {a}, a ∈ ca ∧ R a b := H.right h theorem lift_rel_def {R : α → β → Prop} {ca cb} : lift_rel R ca cb ↔ (terminates ca ↔ terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b := ⟨λh, ⟨terminates_of_lift_rel h, λ a b ma mb, let ⟨b', mb', ab⟩ := h.left ma in by rwa mem_unique mb mb'⟩, λ⟨l, r⟩, ⟨λ a ma, let ⟨b, mb⟩ := l.1 ⟨_, ma⟩ in ⟨b, mb, r ma mb⟩, λ b mb, let ⟨a, ma⟩ := l.2 ⟨_, mb⟩ in ⟨a, ma, r ma mb⟩⟩⟩ theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → computation γ} {f2 : β → computation δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 in ⟨λ c cB, let ⟨a, a1, c₁⟩ := exists_of_mem_bind cB, ⟨b, b2, ab⟩ := l1 a1, ⟨l2, r2⟩ := h2 ab, ⟨d, d2, cd⟩ := l2 c₁ in ⟨_, mem_bind b2 d2, cd⟩, λ d dB, let ⟨b, b1, d1⟩ := exists_of_mem_bind dB, ⟨a, a2, ab⟩ := r1 b1, ⟨l2, r2⟩ := h2 ab, ⟨c, c₂, cd⟩ := r2 d1 in ⟨_, mem_bind a2 c₂, cd⟩⟩ @[simp] theorem lift_rel_return_left (R : α → β → Prop) (a : α) (cb : computation β) : lift_rel R (return a) cb ↔ ∃ {b}, b ∈ cb ∧ R a b := ⟨λ⟨l, r⟩, l (ret_mem _), λ⟨b, mb, ab⟩, ⟨λ a' ma', by rw eq_of_ret_mem ma'; exact ⟨b, mb, ab⟩, λ b' mb', ⟨_, ret_mem _, by rw mem_unique mb' mb; exact ab⟩⟩⟩ @[simp] theorem lift_rel_return_right (R : α → β → Prop) (ca : computation α) (b : β) : lift_rel R ca (return b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [lift_rel.swap, lift_rel_return_left] @[simp] theorem lift_rel_return (R : α → β → Prop) (a : α) (b : β) : lift_rel R (return a) (return b) ↔ R a b := by rw [lift_rel_return_left]; exact ⟨λ⟨b', mb', ab'⟩, by rwa eq_of_ret_mem mb' at ab', λab, ⟨_, ret_mem _, ab⟩⟩ @[simp] theorem lift_rel_think_left (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R (think ca) cb ↔ lift_rel R ca cb := and_congr (forall_congr $ λb, imp_congr ⟨of_think_mem, think_mem⟩ iff.rfl) (forall_congr $ λb, imp_congr iff.rfl $ exists_congr $ λ b, and_congr ⟨of_think_mem, think_mem⟩ iff.rfl) @[simp] theorem lift_rel_think_right (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R ca (think cb) ↔ lift_rel R ca cb := by rw [←lift_rel.swap R, ←lift_rel.swap R]; apply lift_rel_think_left theorem lift_rel_mem_cases {R : α → β → Prop} {ca cb} (Ha : ∀ a ∈ ca, lift_rel R ca cb) (Hb : ∀ b ∈ cb, lift_rel R ca cb) : lift_rel R ca cb := ⟨λ a ma, (Ha _ ma).left ma, λ b mb, (Hb _ mb).right mb⟩ theorem lift_rel_congr {R : α → β → Prop} {ca ca' : computation α} {cb cb' : computation β} (ha : ca ~ ca') (hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' := and_congr (forall_congr $ λ a, imp_congr (ha _) $ exists_congr $ λ b, and_congr (hb _) iff.rfl) (forall_congr $ λ b, imp_congr (hb _) $ exists_congr $ λ a, and_congr (ha _) iff.rfl) theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := by rw [←bind_ret, ←bind_ret]; apply lift_rel_bind _ _ h1; simp; exact @h2 theorem map_congr (R : α → α → Prop) (S : β → β → Prop) {s1 s2 : computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [←lift_eq_iff_equiv]; exact lift_rel_map eq _ ((lift_eq_iff_equiv _ _).2 h1) (λ a b, congr_arg _) def lift_rel_aux (R : α → β → Prop) (C : computation α → computation β → Prop) : α ⊕ computation α → β ⊕ computation β → Prop | (sum.inl a) (sum.inl b) := R a b | (sum.inl a) (sum.inr cb) := ∃ {b}, b ∈ cb ∧ R a b | (sum.inr ca) (sum.inl b) := ∃ {a}, a ∈ ca ∧ R a b | (sum.inr ca) (sum.inr cb) := C ca cb attribute [simp] lift_rel_aux @[simp] def lift_rel_aux.ret_left (R : α → β → Prop) (C : computation α → computation β → Prop) (a cb) : lift_rel_aux R C (sum.inl a) (destruct cb) ↔ ∃ {b}, b ∈ cb ∧ R a b := begin apply cb.cases_on (λ b, _) (λ cb, _), { exact ⟨λ h, ⟨_, ret_mem _, h⟩, λ ⟨b', mb, h⟩, by rw [mem_unique (ret_mem _) mb]; exact h⟩ }, { rw [destruct_think], exact ⟨λ ⟨b, h, r⟩, ⟨b, think_mem h, r⟩, λ ⟨b, h, r⟩, ⟨b, of_think_mem h, r⟩⟩ } end theorem lift_rel_aux.swap (R : α → β → Prop) (C) (a b) : lift_rel_aux (function.swap R) (function.swap C) b a = lift_rel_aux R C a b := by cases a with a ca; cases b with b cb; simp only [lift_rel_aux] @[simp] def lift_rel_aux.ret_right (R : α → β → Prop) (C : computation α → computation β → Prop) (b ca) : lift_rel_aux R C (destruct ca) (sum.inl b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [←lift_rel_aux.swap, lift_rel_aux.ret_left] theorem lift_rel_rec.lem {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : lift_rel R ca cb := begin revert cb, refine mem_rec_on ha _ (λ ca' IH, _); intros cb Hc; have h := H Hc, { simp at h, simp [h] }, { have h := H Hc, simp, revert h, apply cb.cases_on (λ b, _) (λ cb', _); intro h; simp at h; simp [h], exact IH _ h } end theorem lift_rel_rec {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : lift_rel R ca cb := lift_rel_mem_cases (lift_rel_rec.lem C @H ca cb Hc) (λ b hb, (lift_rel.swap _ _ _).2 $ lift_rel_rec.lem (function.swap C) (λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h) cb ca Hc b hb) end computation
e1664096a21c5f7a8ca9f5713f659291ada0a28c
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/hw8/lecture notes/rules_of_reasoning.lean
109a5d8f12931557ec1f5ebbd08494c8b99972b1
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
3,706
lean
--import .prop_logic import .propositional_logic_syntax_and_semantics open pExp /- Here are three propositional variables, P, Q, and R. -/ def P := pVar (var.mk 0) def Q := pVar (var.mk 1) def R := pVar (var.mk 2) /- Below are 20+ formulae in propositional logic. Your job is to classify each as valid or not valid. To do this you will produe a truth table for each one. It is good that we have an automatic evaluator as that makes the job easy. For each of the formulae that is not valid, give an English language counterexample: some scenario that shows that the formula is not always true. To do this assignment, produce a truth table for each formula and use the result to tell if a formula is valid or not. Remember that each row of a truth table corresponds to one interpretation and gives the value of such a formula under that specific interpretation. Some of the formulae contain only one variable. We will always use P in these cases. You will need two interpretations in these cases. Call them Pt and Pf. Some formula have two variables, P and Q. You will need four interpretations in these cases. Call them PtQt, PtQf, etc. Finally some formula use three variables. Call the interpretations for these cases PtQtRt, etc. Define your interpretations, for formulae with one, two, and three variables, respectively, here. -/ -- Answer /- Beneath each formula, below, evaluate it under each of its possible interpretations. Hint: use pEval! The results will tell you whether the formula is valid or not. It'll also tell you under which of the interpretations, if any, it is not true. From the results, you can then decide whether each formula is valid or not. -/ def true_intro : pExp := pTrue -- truth table here (some number of pEvals) -- classification here (valid or not) def false_elim := pFalse > P -- answer here def true_imp := pTrue > P -- etc def and_intro := P > Q > (P ∧ Q) def and_elim_left := (P ∧ Q) > P def and_elim_right := (P ∧ Q) > Q def or_intro_left := P > (P ∨ Q) def or_intro_right := Q > (P ∨ Q) def or_elim := (P ∨ Q) > (P > R) > (Q > R) > R def iff_intro := (P > Q) > (Q > P) > (P ↔ Q) def iff_intro' := ((P > Q) ∧ (Q > P)) > (P ↔ Q) def iff_elim_left := (P ↔ Q) > (P > Q) def iff_elim_right := (P ↔ Q) > (Q > P) def arrow_elim := (P > Q) > (P > Q) def resolution := (P ∨ Q) > (¬ Q ∨ R) > (P ∨ R) def unit_resolution := (P ∨ Q) > ((¬ Q) > P) def syllogism := (P > Q) > (Q > R) > (P > R) def modus_tollens := (P > Q) > (¬ Q > ¬ P) def neg_elim := (¬ ¬ P) > P def excluded_middle := P ∨ (¬ P) def neg_intro := (P > pFalse) > (¬ P) def affirm_consequence := (P > Q) > (Q > P) -- not always true/ valid def affirm_disjunct := (P ∨ Q) > (P > ¬ Q) --not always true/ valid def deny_antecedent := (P > Q) > (¬ P > ¬ Q) axioms A B : Prop #check A ∨ B ∧ B ∨ A #check (A ∨ B) ∧ (B ∨ A) #check A ∨ (B ∧ B) ∨ A #check A ∨ B → B ∨ A #check (A ∨ B) → (B ∨ A) #check A ∨ (B → B) ∨ A #check A → B ↔ B → A #check (A → B) ↔ (B → A) #check A → (B ↔ B) → A #check A ↔ B ∨ B ↔ A #check (A ↔ B) ∨ (B ↔ A) #check A ↔ (B ∨ B) ↔ A #check A → B ∨ B → A #check (A → B) ∨ (B → A) #check A → (B ∨ B) → A /- Study the valid rules and learn their names. These rules, which, here, we are validating "semantically" (by the method of truth tables) will become fundamental "rules of inference", for reasoning "syntactically" when we get to predicate logic. There is not much memorizing in this class, but this is one case where you will find it important to learn the names and definitions of these rules. -/
ed01502692738eda3a48b059c6dc8a85cc17956d
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/analysis/calculus/deriv.lean
5a203d9cfef96582ac8ad394888a49d94efbb1c1
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
46,169
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 /-! # 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`. 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 - 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` - 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. ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. -/ universes u v w noncomputable theory open_locale classical topological_space open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) set_option class.instance_max_depth 100 variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] 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 (nhds_within x s) /-- `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) /-- 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] /-- 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 := by simp [has_deriv_within_at, has_deriv_at_filter, has_fderiv_within_at] /-- 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 /-- 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 := by simp [has_deriv_at, has_deriv_at_filter, has_fderiv_at] /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 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'∥) (nhds_within x s) (𝓝 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 /-- 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 ⊓ principal (-{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' _), rw mem_inf_principal, refine univ_mem_sets' (λ z hz, _), have : z ≠ x, by simpa [function.comp] using hz, simp only [mem_set_of_eq], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 this), 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)) (nhds_within x (s \ {x})) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, lattice.inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within 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 ∈ nhds_within x s) : 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 ∈ nhds_within x t) : 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 } section congr /-! ### Congruence properties of derivatives -/ theorem has_deriv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : {x | f₀ x = f₁ x} ∈ L) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr_of_mem_sets hx h₀ (by simp [h₁]) lemma has_deriv_at_filter.congr_of_mem_sets (h : has_deriv_at_filter f f' x L) (hL : {x | f₁ x = f x} ∈ L) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa has_deriv_at_filter_congr_of_mem_sets hx hL 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_mem_nhds_within (h : has_deriv_within_at f f' s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_mem_sets h h₁ hx lemma has_deriv_at.congr_of_mem_nhds (h : has_deriv_at f f' x) (h₁ : {y | f₁ y = f y} ∈ 𝓝 x) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma deriv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr_of_mem_nhds_within hs hL 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 deriv_congr_of_mem_nhds (hL : {y | f₁ y = f y} ∈ 𝓝 x) : deriv f₁ x = deriv f x := by { unfold deriv, rwa fderiv_congr_of_mem_nhds } 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 := (is_o_zero _ _).congr_left $ by simp 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 _ _ 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 lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := by { unfold deriv_within, rw fderiv_within_id, simp, assumption } 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 := (is_o_zero _ _).congr_left $ λ _, by simp [continuous_linear_map.zero_apply, sub_self] 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 := by { rw (differentiable_at_const _).deriv_within hxs, apply deriv_const } end const section is_linear_map /-! ### Derivative of linear maps -/ variables (s x L) [is_linear_map 𝕜 f] lemma is_linear_map.has_deriv_at_filter : has_deriv_at_filter f (f 1) x L := (is_o_zero _ _).congr_left begin intro y, simp [add_smul], rw ← is_linear_map.smul f x, rw ← is_linear_map.smul f y, simp end lemma is_linear_map.has_deriv_within_at : has_deriv_within_at f (f 1) s x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.has_deriv_at : has_deriv_at f (f 1) x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.differentiable_at : differentiable_at 𝕜 f x := (is_linear_map.has_deriv_at _).differentiable_at lemma is_linear_map.differentiable_within_at : differentiable_within_at 𝕜 f s x := (is_linear_map.differentiable_at _).differentiable_within_at @[simp] lemma is_linear_map.deriv : deriv f x = f 1 := has_deriv_at.deriv (is_linear_map.has_deriv_at _) lemma is_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f 1 := begin rw differentiable_at.deriv_within (is_linear_map.differentiable_at _) hxs, apply is_linear_map.deriv, assumption end lemma is_linear_map.differentiable : differentiable 𝕜 f := λ x, is_linear_map.differentiable_at _ lemma is_linear_map.differentiable_on : differentiable_on 𝕜 f s := is_linear_map.differentiable.differentiable_on end is_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 := (hf.add hg).congr_left $ by simp [add_smul, smul_add] 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 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) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv 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) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add 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 := begin show has_fderiv_within_at _ _ _ _, convert has_fderiv_within_at.smul hc hf, ext, simp [smul_add, (mul_smul _ _ _).symm, mul_comm] end 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 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 := h.neg.congr (by simp) (by simp) 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 lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv_neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv_neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv_neg end neg 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 := 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 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 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 := 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) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv 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 := 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) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv 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)) := has_fderiv_at_filter.tendsto_nhds hL h 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 lattice.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 valued function and a scalar function -/ variables {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.comp (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 := have (smul_right 1 g' : 𝕜 →L[𝕜] _).comp (smul_right 1 h' : 𝕜 →L[𝕜] _) = smul_right 1 (h' • g'), by { ext, simp [mul_smul] }, begin unfold has_deriv_at_filter, rw ← this, exact has_fderiv_at_filter.comp x hg hh, end theorem has_deriv_within_at.comp {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 := begin apply has_deriv_at_filter.comp _ (has_deriv_at_filter.mono hg _) hh, calc map h (nhds_within x s) ≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.comp (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).comp x hh theorem has_deriv_at.comp_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.comp x hg hh subset_preimage_univ end lemma deriv_within.comp (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.comp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.comp (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.comp x hg.has_deriv_at hh.has_deriv_at 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 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 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⁻¹` -/ lemma has_deriv_at_inv_one : has_deriv_at (λx, x⁻¹) (-1) (1 : 𝕜) := begin rw has_deriv_at_iff_is_o_nhds_zero, have : is_o (λ (h : 𝕜), h^2 * (1 + h)⁻¹) (λ (h : 𝕜), h * 1) (𝓝 0), { have : tendsto (λ (h : 𝕜), (1 + h)⁻¹) (𝓝 0) (𝓝 (1 + 0)⁻¹) := ((tendsto_const_nhds).add tendsto_id).inv' (by norm_num), exact is_o.mul_is_O (is_o_pow_id one_lt_two) (is_O_one_of_tendsto _ this) }, apply this.congr' _ _, { have : metric.ball (0 : 𝕜) 1 ∈ 𝓝 (0 : 𝕜), from metric.ball_mem_nhds 0 zero_lt_one, filter_upwards [this], assume h hx, have : 0 < ∥1 + h∥ := calc 0 < ∥(1:𝕜)∥ - ∥-h∥ : by rwa [norm_neg, sub_pos, ← dist_zero_right h, normed_field.norm_one] ... ≤ ∥1 - -h∥ : norm_sub_norm_le _ _ ... = ∥1 + h∥ : by simp, have : 1 + h ≠ 0 := (norm_pos_iff (1 + h)).mp this, simp only [mem_set_of_eq, smul_eq_mul, inv_one], field_simp [this, -add_comm], ring }, { exact univ_mem_sets' mul_one } end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := begin have A : has_deriv_at (λy, y⁻¹) (-1) (x⁻¹ * x : 𝕜), by { simp only [inv_mul_cancel x_ne_zero, has_deriv_at_inv_one] }, have B : has_deriv_at (λy, x⁻¹ * y) (x⁻¹) x, by simpa only [mul_one] using (has_deriv_at_id x).const_mul x⁻¹, convert (A.comp x B : _).const_mul x⁻¹, { ext y, rw [function.comp_apply, mul_inv', inv_inv', mul_comm, mul_assoc, mul_inv_cancel x_ne_zero, mul_one] }, { rw [pow_two, mul_inv', smul_eq_mul, mul_neg_one, neg_mul_eq_mul_neg] } end 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 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], 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 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) 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 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 end division namespace polynomial /-! ### Derivative of a polynomial -/ variable (p : polynomial 𝕜) /-- 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 := begin apply p.induction_on, { simp [has_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end 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 continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at 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 : ℕ` -/ variable {n : ℕ } lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C 1 * (polynomial.X)^n).has_deriv_at x, { simp }, { rw [polynomial.derivative_monomial], simp } end 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) := by rw [differentiable_at_pow.deriv_within hxs, deriv_pow] end pow
a1ac959ebfe4b773040c602284d4b60a467bb95e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/def14.lean
21866e3ad9af6f8ec9efd92a081a1b6b937d3be0
[ "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
383
lean
inductive Formula | eqf : Nat → Nat → Formula | impf : Formula → Formula → Formula def Formula.denote : Formula → Prop | eqf n1 n2 => n1 = n2 | impf f1 f2 => denote f1 → denote f2 theorem Formula.denote_eqf (n1 n2 : Nat) : denote (eqf n1 n2) = (n1 = n2) := rfl theorem Formula.denote_impf (f1 f2 : Formula) : denote (impf f1 f2) = (denote f1 → denote f2) := rfl
c02df8595d1a18cc65d80df1be86c5fc6e5830f5
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/meta/transfer.lean
4f7ce24bb4785ccafd7aba931e13ad2592992f1a
[ "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,619
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.tactic init.meta.match_tactic init.relator init.meta.mk_dec_eq_instance import init.data.list.instances namespace transfer open tactic expr list monad /- Transfer rules are of the shape: rel_t : {u} Πx, R t₁ t₂ where `u` is a list of universe parameters, `x` is a list of dependent variables, and `R` is a relation. Then this rule will translate `t₁` (depending on `u` and `x`) into `t₂`. `u` and `x` will be called parameters. When `R` is a relation on functions lifted from `S` and `R` the variables bound by `S` are called arguments. `R` is generally constructed using `⇒` (i.e. `relator.lift_fun`). As example: rel_eq : (R ⇒ R ⇒ iff) eq t transfer will match this rule when it sees: (@eq α a b) and transfer it to (t a b) Here `α` is a parameter and `a` and `b` are arguments. TODO: add trace statements TODO: currently the used relation must be fixed by the matched rule or through type class inference. Maybe we want to replace this by type inference similar to Isabelle's transfer. -/ private meta structure rel_data := (in_type : expr) (out_type : expr) (relation : expr) meta instance has_to_tactic_format_rel_data : has_to_tactic_format rel_data := ⟨λr, do R ← pp r.relation, α ← pp r.in_type, β ← pp r.out_type, return $ to_fmt "(" ++ R ++ ": rel (" ++ α ++ ") (" ++ β ++ "))" ⟩ private meta structure rule_data := (pr : expr) (uparams : list name) -- levels not in pat (params : list (expr × bool)) -- fst : local constant, snd = tt → param appears in pattern (uargs : list name) -- levels not in pat (args : list (expr × rel_data)) -- fst : local constant (pat : pattern) -- `R c` (out : expr) -- right-hand side `d` of rel equation `R c d` meta instance has_to_tactic_format_rule_data : has_to_tactic_format rule_data := ⟨λr, do pr ← pp r.pr, up ← pp r.uparams, mp ← pp r.params, ua ← pp r.uargs, ma ← pp r.args, pat ← pp r.pat.target, out ← pp r.out, return $ to_fmt "{ ⟨" ++ pat ++ "⟩ pr: " ++ pr ++ " → " ++ out ++ ", " ++ up ++ " " ++ mp ++ " " ++ ua ++ " " ++ ma ++ " }" ⟩ private meta def get_lift_fun : expr → tactic (list rel_data × expr) | e := do { guardb (is_constant_of (get_app_fn e) ``relator.lift_fun), [α, β, γ, δ, R, S] ← return $ get_app_args e, (ps, r) ← get_lift_fun S, return (rel_data.mk α β R :: ps, r)} <|> return ([], e) private meta def mark_occurences (e : expr) : list expr → list (expr × bool) | [] := [] | (h :: t) := let xs := mark_occurences t in (h, occurs h e || any xs (λ⟨e, oc⟩, oc && occurs h e)) :: xs private meta def analyse_rule (u' : list name) (pr : expr) : tactic rule_data := do t ← infer_type pr, (params, app (app r f) g) ← mk_local_pis t, (arg_rels, R) ← get_lift_fun r, args ← monad.for (enum arg_rels) (λ⟨n, a⟩, prod.mk <$> mk_local_def (mk_simple_name ("a_" ++ to_string n)) a.in_type <*> pure a), a_vars ← return $ prod.fst <$> args, p ← head_beta (app_of_list f a_vars), p_data ← return $ mark_occurences (app R p) params, p_vars ← return $ list.map prod.fst (list.filter (λx, ↑x.2) p_data), u ← return $ collect_univ_params (app R p) ∩ u', pat ← mk_pattern (level.param <$> u) (p_vars ++ a_vars) (app R p) (level.param <$> u) (p_vars ++ a_vars), return $ rule_data.mk pr (list.remove_all u' u) p_data u args pat g private meta def analyse_decls : list name → tactic (list rule_data) := monad.mapm (λn, do d ← get_decl n, c ← return d.univ_params.length, ls ← monad.for (range c) (λ_, mk_fresh_name), analyse_rule ls (const n (ls.map level.param))) private meta def split_params_args : list (expr × bool) → list expr → list (expr × option expr) × list expr | ((lc, tt) :: ps) (e :: es) := let (ps', es') := split_params_args ps es in ((lc, some e) :: ps', es') | ((lc, ff) :: ps) es := let (ps', es') := split_params_args ps es in ((lc, none) :: ps', es') | _ es := ([], es) private meta def param_substitutions (ctxt : list expr) : list (expr × option expr) → tactic (list (name × expr) × list expr) | (((local_const n _ bi t), s) :: ps) := do (e, m) ← match s with | (some e) := return (e, []) | none := let ctxt' := list.filter (λv, occurs v t) ctxt in let ty := pis ctxt' t in if bi = binder_info.inst_implicit then do guard (bi = binder_info.inst_implicit), e ← instantiate_mvars ty >>= mk_instance, return (e, []) else do mv ← mk_meta_var ty, return (app_of_list mv ctxt', [mv]) end, sb ← return $ instantiate_local n e, ps ← return $ (prod.map sb (has_map.map sb)) <$> ps, (ms, vs) ← param_substitutions ps, return ((n, e) :: ms, m ++ vs) | _ := return ([], []) /- input expression a type `R a`, it finds a type `b`, s.t. there is a proof of the type `R a b`. It return (`a`, pr : `R a b`) -/ meta def compute_transfer : list rule_data → list expr → expr → tactic (expr × expr × list expr) | rds ctxt e := do -- Select matching rule (i, ps, args, ms, rd) ← first (rds.for (λrd, do (l, m) ← match_pattern_core semireducible rd.pat e, level_map ← monad.for rd.uparams (λl, prod.mk l <$> mk_meta_univ), inst_univ ← return $ (λe, instantiate_univ_params e (level_map ++ zip rd.uargs l)), (ps, args) ← return $ split_params_args (list.map (prod.map inst_univ id) rd.params) m, (ps, ms) ← param_substitutions ctxt ps, /- this checks type class parameters -/ return (instantiate_locals ps ∘ inst_univ, ps, args, ms, rd))), (bs, hs, mss) ← monad.for (zip rd.args args) (λ⟨⟨_, d⟩, e⟩, do -- Argument has function type (args, r) ← get_lift_fun (i d.relation), ((a_vars, b_vars), (R_vars, bnds)) ← monad.for (enum args) (λ⟨n, arg⟩, do a ← mk_local_def (("a" ++ to_string n) : string) arg.in_type, b ← mk_local_def (("b" ++ to_string n) : string) arg.out_type, R ← mk_local_def (("R" ++ to_string n) : string) (arg.relation a b), return ((a, b), (R, [a, b, R]))) >>= (return ∘ prod.map unzip unzip ∘ unzip), rds' ← monad.for R_vars (analyse_rule []), -- Transfer argument a ← return $ i e, a' ← head_beta (app_of_list a a_vars), (b, pr, ms) ← compute_transfer (rds ++ rds') (ctxt ++ a_vars) (app r a'), b' ← head_eta (lambdas b_vars b), return (b', [a, b', lambdas (list.join bnds) pr], ms)) >>= (return ∘ prod.map id unzip ∘ unzip), -- Combine b ← head_beta (app_of_list (i rd.out) bs), pr ← return $ app_of_list (i rd.pr) (prod.snd <$> ps ++ list.join hs), return (b, pr, ms ++ list.join mss) meta def transfer (ds : list name) : tactic unit := do rds ← analyse_decls ds, tgt ← target, (guard (¬ tgt.has_meta_var) <|> fail "Target contains (universe) meta variables. This is not supported by transfer."), (new_tgt, pr, ms) ← compute_transfer rds [] ((const `iff [] : expr) tgt), new_pr ← mk_meta_var new_tgt, /- Setup final tactic state -/ exact ((const `iff.mpr [] : expr) tgt new_tgt pr new_pr), ms ← monad.for ms (λm, (get_assignment m >> return []) <|> return [m]), gs ← get_goals, set_goals (list.join ms ++ new_pr :: gs) end transfer
275ccbf53f662b5daad7530312236c8841aa4f9e
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/ring_theory/noetherian.lean
80a5e2db1ad0a4cc23c29186ef11dc079a6cdefb
[ "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
30,430
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 algebraic_geometry.prime_spectrum import data.multiset.finset_ops import linear_algebra.linear_independent import order.order_iso_nat import order.compactly_generated import ring_theory.ideal.operations /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_span {s : set M} (hs : finite s) : fg (span R s) := ⟨hs.to_finset, by rw [hs.coe_to_finset]⟩ theorem fg_span_singleton (x : M) : fg (R ∙ x) := fg_span (finite_singleton x) theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [semimodule R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- 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 {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end /-- The image of a finitely generated ideal is finitely generated. -/ lemma map_fg_of_fg {R S : Type*} [comm_ring R] [comm_ring S] (I : ideal R) (h : I.fg) (f : R →+* S) : (I.map f).fg := begin obtain ⟨X, hXfin, hXgen⟩ := fg_def.1 h, apply fg_def.2, refine ⟨set.image f X, finite.image ⇑f hXfin, _⟩, rw [ideal.map, ideal.span, ← hXgen], refine le_antisymm (submodule.span_mono (image_subset _ ideal.subset_span)) _, rw [submodule.span_le, image_subset_iff], intros i hi, refine submodule.span_induction hi (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _), { simp only [mem_coe, mem_preimage], suffices : f x ∈ f '' X, { exact ideal.subset_span this }, exact mem_image_of_mem ⇑f hx }, { simp only [mem_coe, ring_hom.map_zero, mem_preimage, zero_mem] }, { simp only [mem_coe, mem_preimage] at hx hy, simp only [ring_hom.map_add, mem_coe, mem_preimage], exact submodule.add_mem _ hx hy }, { simp only [mem_coe, mem_preimage] at hx, simp only [algebra.id.smul_eq_mul, mem_coe, mem_preimage, ring_hom.map_mul], exact submodule.smul_mem _ _ hx } end /-- The kernel of the composition of two linear maps is finitely generated if both kernels are and the first morphism is surjective. -/ lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin rw linear_map.ker_comp, apply fg_of_fg_map_of_fg_inf_ker f, { rwa [linear_map.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] }, { rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono (@bot_le _ _ g.ker))] } end lemma fg_restrict_scalars {R S M : Type*} [comm_ring R] [comm_ring S] [algebra R S] [add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M) (hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg := begin obtain ⟨X, rfl⟩ := hfin, use X, exact submodule.span_eq_restrict_scalars R S M X h end lemma fg_ker_ring_hom_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] (f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin letI : algebra R S := ring_hom.to_algebra f, letI : algebra R A := ring_hom.to_algebra (g.comp f), letI : algebra S A := ring_hom.to_algebra g, letI : is_scalar_tower R S A := is_scalar_tower.comap, let f₁ := algebra.linear_map R S, let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map, exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur end /-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [←finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [semimodule R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := begin rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3, exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩, end lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ class is_noetherian_ring (R) [ring R] extends is_noetherian R R : Prop theorem is_noetherian_ring_iff {R} [ring R] : is_noetherian_ring R ↔ is_noetherian R R := ⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩ @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R) 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 ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual 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 ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end section local attribute [instance] subset.comm_ring instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule section primes variables {R : Type*} [comm_ring R] [is_noetherian_ring R] /--In a noetherian ring, every ideal contains a product of prime ideals ([samuel, § 3.3, Lemma 3])-/ lemma exists_prime_spectrum_prod_le (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I := begin refine is_noetherian.induction (λ (M : ideal R) hgt, _) I, by_cases h_prM : M.is_prime, { use {⟨M, h_prM⟩}, rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact le_rfl }, by_cases htop : M = ⊤, { rw htop, exact ⟨0, le_top⟩ }, have lt_add : ∀ z ∉ M, M < M + span R {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop, obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx), obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], apply le_trans (submodule.mul_le_mul h_Wx h_Wy), rw add_mul, apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem], end variables {A : Type*} [integral_domain A] [is_noetherian_ring A] /--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product or prime ideals ([samuel, § 3.3, Lemma 3]) -/ lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A} (h_nzI: I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧ multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ := begin revert h_nzI, refine is_noetherian.induction (λ (M : ideal A) hgt, _) I, intro h_nzM, have hA_nont : nontrivial A, apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A), by_cases h_topM : M = ⊤, { rcases h_topM with rfl, obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime, { apply ring.not_is_field_iff_exists_prime.mp h_fA }, use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top], rwa [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk] }, by_cases h_prM : M.is_prime, { use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)), rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact ⟨le_rfl, h_nzM⟩ }, obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM, have lt_add : ∀ z ∉ M, M < M + span A {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)), obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩, { rw add_mul, apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] }, { rintro (hx | hy); contradiction }, end end primes
83991f364ae141e1a3cd42d36122184b3ce11dce
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/algebra/uniform_group.lean
266d60ae4e8358837595772f828f2a81d33154c9
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
19,595
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.uniform_space.uniform_embedding import topology.uniform_space.complete_separated import topology.algebra.group import tactic.abel /-! # Uniform structure on topological groups * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) * `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`. -/ noncomputable theory open_locale classical uniformity topological_space section uniform_add_group open filter set variables {α : Type*} {β : Type*} /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous (λp:α×α, p.1 + p.2)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩ variables [uniform_space α] [add_group α] [uniform_add_group α] lemma uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2) := uniform_add_group.uniform_continuous_sub lemma uniform_continuous.sub [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) := uniform_continuous_sub.comp (hf.prod_mk hg) lemma uniform_continuous.neg [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, - f x) := have uniform_continuous (λx, 0 - f x), from uniform_continuous_const.sub hf, by simp * at * lemma uniform_continuous_neg : uniform_continuous (λx:α, - x) := uniform_continuous_id.neg lemma uniform_continuous.add [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) := have uniform_continuous (λx, f x - - g x), from hf.sub hg.neg, by simp [*, sub_eq_add_neg] at * lemma uniform_continuous_add : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_fst.add uniform_continuous_snd @[priority 10] instance uniform_add_group.to_topological_add_group : topological_add_group α := { continuous_add := uniform_continuous_add.continuous, continuous_neg := uniform_continuous_neg.continuous } instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := ⟨((uniform_continuous_fst.comp uniform_continuous_fst).sub (uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk ((uniform_continuous_snd.comp uniform_continuous_fst).sub (uniform_continuous_snd.comp uniform_continuous_snd))⟩ lemma uniformity_translate (a : α) : (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) = 𝓤 α := le_antisymm (uniform_continuous_id.add uniform_continuous_const) (calc 𝓤 α = ((𝓤 α).map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) : filter.map_mono (uniform_continuous_id.add uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := { comap_uniformity := begin rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end, inj := add_left_injective a } section variables (α) lemma uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λx:α×α, x.2 - x.1) (𝓝 (0:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap_comp], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_sub hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_sets_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_add hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a } end end lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) := have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding, show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x - y ∈ closure ({0} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_nonempty, sub_eq_add_neg, add_assoc] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : tendsto f (𝓝 0) (𝓝 0)) : uniform_continuous f := begin have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)), { simp only [is_add_group_hom.map_sub f] }, rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β, tendsto_comap_iff, this], exact tendsto.comp h tendsto_comap end lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_zero $ suffices tendsto f (𝓝 0) (𝓝 (f 0)), by rwa [is_add_group_hom.map_zero f] at this, h.tendsto 0 end uniform_add_group section topological_add_comm_group universes u v w x open filter variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] variable (G) def topological_add_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 - p.1) (𝓝 0), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (𝓝 0)) (𝓝 (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp (tendsto.neg tendsto_id) tendsto_comap end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 - p.1) ⁻¹' V), have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)), by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp:G×G, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa [sub_eq_add_neg, add_comm, add_left_comm] using V_sum _ _ Hz1 Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)), rw [is_open_iff_mem_nhds], refine forall_congr (assume a, forall_congr (assume ha, _)), rw [← nhds_translation a, mem_comap_sets, mem_comap_sets], refine exists_congr (assume t, exists_congr (assume ht, _)), show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } section local attribute [instance] topological_add_group.to_uniform_space lemma uniformity_eq_comap_nhds_zero' : 𝓤 G = comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)) := rfl variable {G} lemma topological_add_group_is_uniform : uniform_add_group G := have tendsto ((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((𝓝 0).prod (𝓝 0))) (𝓝 (0 - 0)) := (tendsto_fst.sub tendsto_snd).comp tendsto_comap, begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘), sub_eq_add_neg, add_comm, add_left_comm] using this end end lemma to_uniform_space_eq {α : Type*} [u : uniform_space α] [add_comm_group α] [uniform_add_group α]: topological_add_group.to_uniform_space α = u := begin ext : 1, show @uniformity α (topological_add_group.to_uniform_space α) = 𝓤 α, rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α] end end topological_add_comm_group namespace add_comm_group section Z_bilin variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [add_comm_group α] [add_comm_group β] [add_comm_group γ] /- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin` by using `is_bilinear_map ℤ` from `tensor_product`. -/ class is_Z_bilin (f : α × β → γ) : Prop := (add_left [] : ∀ a a' b, f (a + a', b) = f (a, b) + f (a', b)) (add_right [] : ∀ a b b', f (a, b + b') = f (a, b) + f (a, b')) variables (f : α × β → γ) [is_Z_bilin f] lemma is_Z_bilin.comp_hom {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] : is_Z_bilin (g ∘ f) := by constructor; simp [(∘), is_Z_bilin.add_left f, is_Z_bilin.add_right f, is_add_hom.map_add g] instance is_Z_bilin.comp_swap : is_Z_bilin (f ∘ prod.swap) := ⟨λ a a' b, is_Z_bilin.add_right f b a a', λ a b b', is_Z_bilin.add_left f b b' a⟩ lemma is_Z_bilin.zero_left : ∀ b, f (0, b) = 0 := begin intro b, apply add_self_iff_eq_zero.1, rw ←is_Z_bilin.add_left f, simp end lemma is_Z_bilin.zero_right : ∀ a, f (a, 0) = 0 := is_Z_bilin.zero_left (f ∘ prod.swap) lemma is_Z_bilin.zero : f (0, 0) = 0 := is_Z_bilin.zero_left f 0 lemma is_Z_bilin.neg_left : ∀ a b, f (-a, b) = -f (a, b) := begin intros a b, apply eq_of_sub_eq_zero, rw [sub_eq_add_neg, neg_neg, ←is_Z_bilin.add_left f, neg_add_self, is_Z_bilin.zero_left f] end lemma is_Z_bilin.neg_right : ∀ a b, f (a, -b) = -f (a, b) := assume a b, is_Z_bilin.neg_left (f ∘ prod.swap) b a lemma is_Z_bilin.sub_left : ∀ a a' b, f (a - a', b) = f (a, b) - f (a', b) := begin intros, simp [sub_eq_add_neg], rw [is_Z_bilin.add_left f, is_Z_bilin.neg_left f] end lemma is_Z_bilin.sub_right : ∀ a b b', f (a, b - b') = f (a, b) - f (a,b') := assume a b b', is_Z_bilin.sub_left (f ∘ prod.swap) b b' a end Z_bilin end add_comm_group open add_comm_group filter set function section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} -- α, β and G are abelian topological groups, G is a uniform space variables [topological_space α] [add_comm_group α] variables [topological_space β] [add_comm_group β] variables {G : Type*} [uniform_space G] [add_comm_group G] variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ] include hψ ψbilin lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (𝓝 (x₁, 0)) (𝓝 0) := begin have := hψ.tendsto (x₁, 0), rwa [is_Z_bilin.zero_right ψ] at this end lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (𝓝 (0, y₁)) (𝓝 0) := begin have := hψ.tendsto (0, y₁), rwa [is_Z_bilin.zero_left ψ] at this end end section variables {α : Type*} {β : Type*} variables [topological_space α] [add_comm_group α] [topological_add_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [add_comm_group β] variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ 𝓝 (x₀, x₀)) (𝓝 0) := begin have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1), { ext t, change e t.2 - e t.1 = e (t.2 - t.1), rwa ← is_add_group_hom.map_sub e t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2-x.1) (𝓝 (x₀, x₀)) (𝓝 (e 0)), { have := (continuous_sub.comp continuous_swap).tendsto (x₀, x₀), simpa [-sub_eq_add_neg, sub_self, eq.symm (is_add_group_hom.map_zero e)] using this }, have := de.tendsto_comap_nhds_nhds lim comm, simp [-sub_eq_add_neg, this] end end namespace dense_inducing variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated_space G] [complete_space G] variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e) variables {f : δ → γ} [is_add_group_hom f] (df : dense_inducing f) variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ] include de df hφ bilin variables {W' : set G} (W'_nhd : W' ∈ 𝓝 (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (𝓝 x₀), ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' := begin let Nx := 𝓝 x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (filter.prod (comap e Nx) (comap e Nx)) (𝓝 (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ 𝓝 (x₀, x₀)) (𝓝 y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim := tendsto.comp (is_Z_bilin.tendsto_zero_right hφ y₁) lim1, rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd, end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (𝓝 x₀), ∃ V ∈ comap f (𝓝 y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' := begin let Nx := 𝓝 x₀, let Ny := 𝓝 y₀, let dp := dense_inducing.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto φ (𝓝 (0, 0)) (𝓝 0), { have := hφ.tendsto (0, 0), rwa [is_Z_bilin.zero φ] at this }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee $ 𝓝 (x₀, x₀)) (comap ff $ 𝓝 (y₀, y₀))) (𝓝 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee (𝓝 (x₀, x₀))) (comap ff (𝓝 (y₀, y₀)))) (filter.prod (𝓝 0) (𝓝 0)), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_φ lim_sub_sub }, rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (𝓝 x₀), ∃ V₁ ∈ comap f (𝓝 y₀), ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x' x_in x'_in y y' y_in y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, obtain ⟨x₁, x₁_in⟩ : U₁.nonempty := (forall_sets_nonempty_iff_ne_bot.2 de.comap_nhds_ne_bot U₁ U₁_nhd), obtain ⟨y₁, y₁_in⟩ : V₁.nonempty := (forall_sets_nonempty_iff_ne_bot.2 df.comap_nhds_ne_bot V₁ V₁_nhd), rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de (hφ.comp continuous_swap) W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem_sets U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem_sets V₁_nhd V₂_nhd], rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩, have key_formula : φ(x', y') - φ(x, y) = φ(x' - x, y₁) + φ(x' - x, y' - y₁) + φ(x₁, y' - y) + φ(x - x₁, y' - y), { repeat { rw is_Z_bilin.sub_left φ }, repeat { rw is_Z_bilin.sub_right φ }, apply eq_of_sub_eq_zero, simp [sub_eq_add_neg], abel }, rw key_formula, have h₁ := HU x x' xU₂ x'U₂, have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁, have h₃ := HV y y' yV₂ y'V₂, have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd open dense_inducing /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (de.prod df) φ) := begin refine continuous_extend_of_cauchy _ _, rintro ⟨x₀, y₀⟩, split, { apply map_ne_bot, apply comap_ne_bot, intros U h, rcases mem_closure_iff_nhds.1 ((de.prod df).dense (x₀, y₀)) U h with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), φ p.2 - φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (filter.prod (𝓝 (x₀, y₀)) (𝓝 (x₀, y₀)))) ≤ 𝓝 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap_sets at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap_sets at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap_sets, nhds_prod_eq], existsi set.prod (set.prod U' V') (set.prod U' V'), rw mem_prod_same_iff, simp only [exists_prop], split, { change U' ∈ 𝓝 x₀ at U'_nhd, change V' ∈ 𝓝 y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_inducing
6dc419041440f78db898e8f79e77a6da57819526
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/linear_algebra/finite_dimensional.lean
bbe38ceb8fc06ef59311467fce6f22629a9261ac
[ "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
47,055
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import linear_algebra.dimension import ring_theory.principal_ideal_domain /-! # Finite dimensional vector spaces Definition and basic properties of finite dimensional vector spaces, of their dimensions, and of linear maps on such spaces. ## Main definitions Assume `V` is a vector space over a field `K`. There are (at least) three equivalent definitions of finite-dimensionality of `V`: - it admits a finite basis. - it is finitely generated. - it is noetherian, i.e., every subspace is finitely generated. We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of proof, it is defined using the third point of view, i.e., as `is_noetherian`. However, we prove that all these points of view are equivalent, with the following lemmas (in the namespace `finite_dimensional`): - `exists_is_basis_finite` states that a finite-dimensional vector space has a finite basis - `of_finite_basis` states that the existence of a finite basis implies finite-dimensionality - `iff_fg` states that the space is finite-dimensional if and only if it is finitely generated Also defined is `findim`, the dimension of a finite dimensional space, returning a `nat`, as opposed to `dim`, which returns a `cardinal`. When the space has infinite dimension, its `findim` is by convention set to `0`. Preservation of finite-dimensionality and formulas for the dimension are given for - submodules - quotients (for the dimension of a quotient, see `findim_quotient_add_findim`) - linear equivs, in `linear_equiv.finite_dimensional` and `linear_equiv.findim_eq` - image under a linear map (the rank-nullity formula is in `findim_range_add_findim_ker`) Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`, and the equivalence between left-inverse and right-inverse in `mul_eq_one_comm` and `comp_eq_id_comm`. ## Implementation notes Most results are deduced from the corresponding results for the general dimension (as a cardinal), in `dimension.lean`. Not all results have been ported yet. One of the characterizations of finite-dimensionality is in terms of finite generation. This property is currently defined only for submodules, so we express it through the fact that the maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is not very convenient to use, although there are some helper functions. However, this becomes very convenient when speaking of submodules which are finite-dimensional, as this notion coincides with the fact that the submodule is finitely generated (as a submodule of the whole space). This equivalence is proved in `submodule.fg_iff_finite_dimensional`. -/ universes u v v' w open_locale classical open vector_space cardinal submodule module function variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {V₂ : Type v'} [add_comm_group V₂] [vector_space K V₂] /-- `finite_dimensional` vector spaces are defined to be noetherian modules. Use `finite_dimensional.iff_fg` or `finite_dimensional.of_finite_basis` to prove finite dimension from a conventional definition. -/ @[reducible] def finite_dimensional (K V : Type*) [field K] [add_comm_group V] [vector_space K V] := is_noetherian K V namespace finite_dimensional open is_noetherian /-- A vector space is finite-dimensional if and only if its dimension (as a cardinal) is strictly less than the first infinite cardinal `omega`. -/ lemma finite_dimensional_iff_dim_lt_omega : finite_dimensional K V ↔ dim K V < omega.{v} := begin cases exists_is_basis K V with b hb, have := is_basis.mk_eq_dim hb, simp only [lift_id] at this, rw [← this, lt_omega_iff_fintype, ← @set.set_of_mem_eq _ b, ← subtype.range_coe_subtype], split, { intro, resetI, convert finite_of_linear_independent hb.1, simp }, { assume hbfinite, refine @is_noetherian_of_linear_equiv K (⊤ : submodule K V) V _ _ _ _ _ (linear_equiv.of_top _ rfl) (id _), refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩, rw [set.finite.coe_to_finset, ← hb.2], refl } end /-- The dimension of a finite-dimensional vector space, as a cardinal, is strictly less than the first infinite cardinal `omega`. -/ lemma dim_lt_omega (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ∀ [finite_dimensional K V], dim K V < omega.{v} := finite_dimensional_iff_dim_lt_omega.1 /-- In a finite dimensional space, there exists a finite basis. A basis is in general given as a function from an arbitrary type to the vector space. Here, we think of a basis as a set (instead of a function), and use as parametrizing type this set (and as a function the coercion `coe : s → V`). -/ variables (K V) lemma exists_is_basis_finite [finite_dimensional K V] : ∃ s : set V, (is_basis K (coe : s → V)) ∧ s.finite := begin cases exists_is_basis K V with s hs, exact ⟨s, hs, finite_of_linear_independent hs.1⟩ end /-- In a finite dimensional space, there exists a finite basis. Provides the basis as a finset. This is in contrast to `exists_is_basis_finite`, which provides a set and a `set.finite`. -/ lemma exists_is_basis_finset [finite_dimensional K V] : ∃ b : finset V, is_basis K (coe : (↑b : set V) → V) := begin obtain ⟨s, s_basis, s_finite⟩ := exists_is_basis_finite K V, refine ⟨s_finite.to_finset, _⟩, rw set.finite.coe_to_finset, exact s_basis, end variables {K V} /-- A vector space is finite-dimensional if and only if it is finitely generated. As the finitely-generated property is a property of submodules, we formulate this in terms of the maximal submodule, equal to the whole space as a set by definition.-/ lemma iff_fg : finite_dimensional K V ↔ (⊤ : submodule K V).fg := begin split, { introI h, rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, exact ⟨s_finite.to_finset, by { convert s_basis.2, simp }⟩ }, { rintros ⟨s, hs⟩, rw [finite_dimensional_iff_dim_lt_omega, ← dim_top, ← hs], exact lt_of_le_of_lt (dim_span_le _) (lt_omega_iff_finite.2 (set.finite_mem_finset s)) } end /-- If a vector space has a finite basis, then it is finite-dimensional. -/ lemma of_finite_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : finite_dimensional K V := iff_fg.2 $ ⟨finset.univ.image b, by {convert h.2, simp} ⟩ /-- If a vector space has a finite basis, then it is finite-dimensional, finset style. -/ lemma of_finset_basis {b : finset V} (h : is_basis K (coe : (↑b : set V) -> V)) : finite_dimensional K V := iff_fg.2 $ ⟨b, by {convert h.2, simp} ⟩ /-- A subspace of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) : finite_dimensional K S := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_omega K V)) /-- A quotient of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) : finite_dimensional K (quotient S) := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_quotient_le _) (dim_lt_omega K V)) /-- The dimension of a finite-dimensional vector space as a natural number. Defined by convention to be `0` if the space is infinite-dimensional. -/ noncomputable def findim (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ℕ := if h : dim K V < omega.{v} then classical.some (lt_omega.1 h) else 0 /-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its `findim`. -/ lemma findim_eq_dim (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : (findim K V : cardinal.{v}) = dim K V := begin have : findim K V = classical.some (lt_omega.1 (dim_lt_omega K V)) := dif_pos (dim_lt_omega K V), rw this, exact (classical.some_spec (lt_omega.1 (dim_lt_omega K V))).symm end /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : dim K V = fintype.card ι := by rw [←h.mk_range_eq_dim, cardinal.fintype_card, set.card_range_of_injective h.injective] /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. -/ lemma findim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : findim K V = fintype.card ι := begin haveI : finite_dimensional K V := of_finite_basis h, have := dim_eq_card_basis h, rw ← findim_eq_dim at this, exact_mod_cast this end /-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its `findim`. -/ lemma findim_eq_card_basis' [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : is_basis K b) : (findim K V : cardinal.{w}) = cardinal.mk ι := begin rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, letI: fintype s := s_finite.fintype, have A : cardinal.mk s = fintype.card s := fintype_card _, have B : findim K V = fintype.card s := findim_eq_card_basis s_basis, have C : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (cardinal.mk s) := mk_eq_mk_of_basis h s_basis, rw [A, ← B, lift_nat_cast] at C, have : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{w v} (findim K V), by { simp, exact C }, exact (lift_inj.mp this).symm end /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. This lemma uses a `finset` instead of indexed types. -/ lemma findim_eq_card_finset_basis {b : finset V} (h : is_basis K (subtype.val : (↑b : set V) -> V)) : findim K V = finset.card b := by { rw [findim_eq_card_basis h, fintype.subtype_card], intros x, refl } lemma equiv_fin {ι : Type*} [finite_dimensional K V] {v : ι → V} (hv : is_basis K v) : ∃ g : fin (findim K V) ≃ ι, is_basis K (v ∘ g) := begin have : (cardinal.mk (fin $ findim K V)).lift = (cardinal.mk ι).lift, { simp [cardinal.mk_fin (findim K V), ← findim_eq_card_basis' hv] }, rcases cardinal.lift_mk_eq.mp this with ⟨g⟩, exact ⟨g, hv.comp _ g.bijective⟩ end variables (K V) lemma fin_basis [finite_dimensional K V] : ∃ v : fin (findim K V) → V, is_basis K v := let ⟨B, hB, B_fin⟩ := exists_is_basis_finite K V, ⟨g, hg⟩ := finite_dimensional.equiv_fin hB in ⟨coe ∘ g, hg⟩ variables {K V} lemma cardinal_mk_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : linear_independent K b) : cardinal.mk ι ≤ findim K V := begin rw ← lift_le.{_ (max v w)}, simpa [← findim_eq_dim K V] using cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max v w)} h end lemma fintype_card_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type*} [fintype ι] {b : ι → V} (h : linear_independent K b) : fintype.card ι ≤ findim K V := by simpa [fintype_card] using cardinal_mk_le_findim_of_linear_independent h lemma finset_card_le_findim_of_linear_independent [finite_dimensional K V] {b : finset V} (h : linear_independent K (λ x, x : (↑b : set V) → V)) : b.card ≤ findim K V := begin rw ←fintype.card_coe, exact fintype_card_le_findim_of_linear_independent h, end lemma lt_omega_of_linear_independent {ι : Type w} [finite_dimensional K V] {v : ι → V} (h : linear_independent K v) : cardinal.mk ι < cardinal.omega := begin apply cardinal.lift_lt.1, apply lt_of_le_of_lt, apply linear_independent_le_dim h, rw [←findim_eq_dim, cardinal.lift_omega, cardinal.lift_nat_cast], apply cardinal.nat_lt_omega, end lemma not_linear_independent_of_infinite {ι : Type w} [inf : infinite ι] [finite_dimensional K V] (v : ι → V) : ¬ linear_independent K v := begin intro h_lin_indep, have : ¬ omega ≤ mk ι := not_le.mpr (lt_omega_of_linear_independent h_lin_indep), have : omega ≤ mk ι := infinite_iff.mp inf, contradiction end /-- A finite dimensional space has positive `findim` iff it has a nonzero element. -/ lemma findim_pos_iff_exists_ne_zero [finite_dimensional K V] : 0 < findim K V ↔ ∃ x : V, x ≠ 0 := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_exists_ne_zero K V _ _ _) /-- A finite dimensional space has positive `findim` iff it is nontrivial. -/ lemma findim_pos_iff [finite_dimensional K V] : 0 < findim K V ↔ nontrivial V := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_nontrivial K V _ _ _) /-- A nontrivial finite dimensional space has positive `findim`. -/ lemma findim_pos [finite_dimensional K V] [h : nontrivial V] : 0 < findim K V := findim_pos_iff.mpr h section open_locale big_operators open finset /-- If a finset has cardinality larger than the dimension of the space, then there is a nontrivial linear relation amongst its elements. -/ lemma exists_nontrivial_relation_of_dim_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin have := mt finset_card_le_findim_of_linear_independent (by { simpa using h }), rw linear_dependent_iff at this, obtain ⟨s, g, sum, z, zm, nonzero⟩ := this, -- Now we have to extend `g` to all of `t`, then to all of `V`. let f : V → K := λ x, if h : x ∈ t then if (⟨x, h⟩ : (↑t : set V)) ∈ s then g ⟨x, h⟩ else 0 else 0, -- and finally clean up the mess caused by the extension. refine ⟨f, _, _⟩, { dsimp [f], rw ← sum, fapply sum_bij_ne_zero (λ v hvt _, (⟨v, hvt⟩ : {v // v ∈ t})), { intros v hvt H, dsimp, rw [dif_pos hvt] at H, contrapose! H, rw [if_neg H, zero_smul], }, { intros _ _ _ _ _ _, exact subtype.mk.inj, }, { intros b hbs hb, use b, simpa only [hbs, exists_prop, dif_pos, mk_coe, and_true, if_true, finset.coe_mem, eq_self_iff_true, exists_prop_of_true, ne.def] using hb, }, { intros a h₁, dsimp, rw [dif_pos h₁], intro h₂, rw [if_pos], contrapose! h₂, rw [if_neg h₂, zero_smul], }, }, { refine ⟨z, z.2, _⟩, dsimp only [f], erw [dif_pos z.2, if_pos]; rwa [subtype.coe_eta] }, end /-- If a finset has cardinality larger than `findim + 1`, then there is a nontrivial linear relation amongst its elements, such that the coefficients of the relation sum to zero. -/ lemma exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V + 1 < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin -- Pick an element x₀ ∈ t, have card_pos : 0 < t.card := lt_trans (nat.succ_pos _) h, obtain ⟨x₀, m⟩ := (finset.card_pos.1 card_pos).bex, -- and apply the previous lemma to the {xᵢ - x₀} let shift : V ↪ V := ⟨λ x, x - x₀, add_left_injective (-x₀)⟩, let t' := (t.erase x₀).map shift, have h' : findim K V < t'.card, { simp only [t', card_map, finset.card_erase_of_mem m], exact nat.lt_pred_iff.mpr h, }, -- to obtain a function `g`. obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_dim_lt_card h', -- Then obtain `f` by translating back by `x₀`, -- and setting the value of `f` at `x₀` to ensure `∑ e in t, f e = 0`. let f : V → K := λ z, if z = x₀ then - ∑ z in (t.erase x₀), g (z - x₀) else g (z - x₀), refine ⟨f, _ ,_ ,_⟩, -- After this, it's a matter of verifiying the properties, -- based on the corresponding properties for `g`. { show ∑ (e : V) in t, f e • e = 0, -- We prove this by splitting off the `x₀` term of the sum, -- which is itself a sum over `t.erase x₀`, -- combining the two sums, and -- observing that after reindexing we have exactly -- ∑ (x : V) in t', g x • x = 0. simp only [f], conv_lhs { apply_congr, skip, rw [ite_smul], }, rw [finset.sum_ite], conv { congr, congr, apply_congr, simp [filter_eq', m], }, conv { congr, congr, skip, apply_congr, simp [filter_ne'], }, rw [sum_singleton, neg_smul, add_comm, ←sub_eq_add_neg, sum_smul, ←sum_sub_distrib], simp only [←smul_sub], -- At the end we have to reindex the sum, so we use `change` to -- express the summand using `shift`. change (∑ (x : V) in t.erase x₀, (λ e, g e • e) (shift x)) = 0, rw ←sum_map _ shift, exact gsum, }, { show ∑ (e : V) in t, f e = 0, -- Again we split off the `x₀` term, -- observing that it exactly cancels the other terms. rw [← insert_erase m, sum_insert (not_mem_erase x₀ t)], dsimp [f], rw [if_pos rfl], conv_lhs { congr, skip, apply_congr, skip, rw if_neg (show x ≠ x₀, from (mem_erase.mp H).1), }, exact neg_add_self _, }, { show ∃ (x : V) (H : x ∈ t), f x ≠ 0, -- We can use x₁ + x₀. refine ⟨x₁ + x₀, _, _⟩, { rw finset.mem_map at x₁_mem, rcases x₁_mem with ⟨x₁, x₁_mem, rfl⟩, rw mem_erase at x₁_mem, simp only [x₁_mem, sub_add_cancel, function.embedding.coe_fn_mk], }, { dsimp only [f], rwa [if_neg, add_sub_cancel], rw [add_left_eq_self], rintro rfl, simpa only [sub_eq_zero, exists_prop, finset.mem_map, embedding.coe_fn_mk, eq_self_iff_true, mem_erase, not_true, exists_eq_right, ne.def, false_and] using x₁_mem, } }, end section variables {L : Type*} [discrete_linear_ordered_field L] variables {W : Type v} [add_comm_group W] [vector_space L W] /-- A slight strengthening of `exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card` available when working over an ordered field: we can ensure a positive coefficient, not just a nonzero coefficient. -/ lemma exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card [finite_dimensional L W] {t : finset W} (h : findim L W + 1 < t.card) : ∃ f : W → L, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, 0 < f x := begin obtain ⟨f, sum, total, nonzero⟩ := exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card h, exact ⟨f, sum, total, exists_pos_of_sum_zero_of_exists_nonzero f total nonzero⟩, end end end /-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the whole space. -/ lemma eq_top_of_findim_eq [finite_dimensional K V] {S : submodule K V} (h : findim K S = findim K V) : S = ⊤ := begin cases exists_is_basis K S with bS hbS, have : linear_independent K (subtype.val : (subtype.val '' bS : set V) → V), from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ (submodule.subtype S) hbS.1 (by simp), cases exists_subset_is_basis this with b hb, letI : fintype b := classical.choice (finite_of_linear_independent hb.2.1), letI : fintype (subtype.val '' bS) := classical.choice (finite_of_linear_independent this), letI : fintype bS := classical.choice (finite_of_linear_independent hbS.1), have : subtype.val '' bS = b, from set.eq_of_subset_of_card_le hb.1 (by rw [set.card_image_of_injective _ subtype.val_injective, ← findim_eq_card_basis hbS, ← findim_eq_card_basis hb.2, h]; apply_instance), erw [← hb.2.2, subtype.range_coe, ← this, ← subtype_eq_val, span_image], have := hbS.2, erw [subtype.range_coe] at this, rw [this, map_top (submodule.subtype S), range_subtype], end variable (K) /-- A field is one-dimensional as a vector space over itself. -/ @[simp] lemma findim_of_field : findim K K = 1 := begin have := dim_of_field K, rw [← findim_eq_dim] at this, exact_mod_cast this end /-- The vector space of functions on a fintype has finite dimension. -/ instance finite_dimensional_fintype_fun {ι : Type*} [fintype ι] : finite_dimensional K (ι → K) := by { rw [finite_dimensional_iff_dim_lt_omega, dim_fun'], exact nat_lt_omega _ } /-- The vector space of functions on a fintype ι has findim equal to the cardinality of ι. -/ @[simp] lemma findim_fintype_fun_eq_card {ι : Type v} [fintype ι] : findim K (ι → K) = fintype.card ι := begin have : vector_space.dim K (ι → K) = fintype.card ι := dim_fun', rwa [← findim_eq_dim, nat_cast_inj] at this, end /-- The vector space of functions on `fin n` has findim equal to `n`. -/ @[simp] lemma findim_fin_fun {n : ℕ} : findim K (fin n → K) = n := by simp /-- The submodule generated by a finite set is finite-dimensional. -/ theorem span_of_finite {A : set V} (hA : set.finite A) : finite_dimensional K (submodule.span K A) := is_noetherian_span_of_finite K hA /-- The submodule generated by a single element is finite-dimensional. -/ instance (x : V) : finite_dimensional K (submodule.span K ({x} : set V)) := by {apply span_of_finite, simp} end finite_dimensional section zero_dim open vector_space finite_dimensional lemma finite_dimensional_of_dim_eq_zero (h : vector_space.dim K V = 0) : finite_dimensional K V := by rw [finite_dimensional_iff_dim_lt_omega, h]; exact cardinal.omega_pos lemma findim_eq_zero_of_dim_eq_zero [finite_dimensional K V] (h : vector_space.dim K V = 0) : findim K V = 0 := begin convert findim_eq_dim K V, rw h, norm_cast end variables (K V) lemma finite_dimensional_bot : finite_dimensional K (⊥ : submodule K V) := finite_dimensional_of_dim_eq_zero $ by simp @[simp] lemma findim_bot : findim K (⊥ : submodule K V) = 0 := begin haveI := finite_dimensional_bot K V, convert findim_eq_dim K (⊥ : submodule K V), rw dim_bot, norm_cast end variables {K V} lemma bot_eq_top_of_dim_eq_zero (h : vector_space.dim K V = 0) : (⊥ : submodule K V) = ⊤ := begin haveI := finite_dimensional_of_dim_eq_zero h, apply eq_top_of_findim_eq, rw [findim_bot, findim_eq_zero_of_dim_eq_zero h] end @[simp] theorem dim_eq_zero {S : submodule K V} : dim K S = 0 ↔ S = ⊥ := ⟨λ h, (submodule.eq_bot_iff _).2 $ λ x hx, congr_arg subtype.val $ ((submodule.eq_bot_iff _).1 $ eq.symm $ bot_eq_top_of_dim_eq_zero h) ⟨x, hx⟩ submodule.mem_top, λ h, by rw [h, dim_bot]⟩ @[simp] theorem findim_eq_zero {S : submodule K V} [finite_dimensional K S] : findim K S = 0 ↔ S = ⊥ := by rw [← dim_eq_zero, ← findim_eq_dim, ← @nat.cast_zero cardinal, cardinal.nat_cast_inj] end zero_dim namespace submodule open finite_dimensional /-- A submodule is finitely generated if and only if it is finite-dimensional -/ theorem fg_iff_finite_dimensional (s : submodule K V) : s.fg ↔ finite_dimensional K s := ⟨λh, is_noetherian_of_fg_of_noetherian s h, λh, by { rw ← map_subtype_top s, exact fg_map (iff_fg.1 h) }⟩ /-- A submodule contained in a finite-dimensional submodule is finite-dimensional. -/ lemma finite_dimensional_of_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (h : S₁ ≤ S₂) : finite_dimensional K S₁ := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_le_of_submodule _ _ h) (dim_lt_omega K S₂)) /-- The inf of two submodules, the first finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_left (S₁ S₂ : submodule K V) [finite_dimensional K S₁] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_left /-- The inf of two submodules, the second finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_right (S₁ S₂ : submodule K V) [finite_dimensional K S₂] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_right /-- The sup of two finite-dimensional submodules is finite-dimensional. -/ instance finite_dimensional_sup (S₁ S₂ : submodule K V) [h₁ : finite_dimensional K S₁] [h₂ : finite_dimensional K S₂] : finite_dimensional K (S₁ ⊔ S₂ : submodule K V) := begin rw ←submodule.fg_iff_finite_dimensional at *, exact submodule.fg_sup h₁ h₂ end /-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding quotient add up to the dimension of the space. -/ theorem findim_quotient_add_findim [finite_dimensional K V] (s : submodule K V) : findim K s.quotient + findim K s = findim K V := begin have := dim_quotient_add_dim s, rw [← findim_eq_dim, ← findim_eq_dim, ← findim_eq_dim] at this, exact_mod_cast this end /-- The dimension of a submodule is bounded by the dimension of the ambient space. -/ lemma findim_le [finite_dimensional K V] (s : submodule K V) : findim K s ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_left _ _ } /-- The dimension of a strict submodule is strictly bounded by the dimension of the ambient space. -/ lemma findim_lt [finite_dimensional K V] {s : submodule K V} (h : s < ⊤) : findim K s < findim K V := begin rw [← s.findim_quotient_add_findim, add_comm], exact nat.lt_add_of_zero_lt_left _ _ (findim_pos_iff.mpr (quotient.nontrivial_of_lt_top _ h)) end /-- The dimension of a quotient is bounded by the dimension of the ambient space. -/ lemma findim_quotient_le [finite_dimensional K V] (s : submodule K V) : findim K s.quotient ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_right _ _ } /-- The sum of the dimensions of s + t and s ∩ t is the sum of the dimensions of s and t -/ theorem dim_sup_add_dim_inf_eq (s t : submodule K V) [finite_dimensional K s] [finite_dimensional K t] : findim K ↥(s ⊔ t) + findim K ↥(s ⊓ t) = findim K ↥s + findim K ↥t := begin have key : dim K ↥(s ⊔ t) + dim K ↥(s ⊓ t) = dim K s + dim K t := dim_sup_add_dim_inf_eq s t, repeat { rw ←findim_eq_dim at key }, norm_cast at key, exact key end lemma eq_top_of_disjoint [finite_dimensional K V] (s t : submodule K V) (hdim : findim K s + findim K t = findim K V) (hdisjoint : disjoint s t) : s ⊔ t = ⊤ := begin have h_findim_inf : findim K ↥(s ⊓ t) = 0, { rw [disjoint, le_bot_iff] at hdisjoint, rw [hdisjoint, findim_bot] }, apply eq_top_of_findim_eq, rw ←hdim, convert s.dim_sup_add_dim_inf_eq t, rw h_findim_inf, refl, end end submodule namespace linear_equiv open finite_dimensional /-- Finite dimensionality is preserved under linear equivalence. -/ protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : finite_dimensional K V₂ := is_noetherian_of_linear_equiv f /-- The dimension of a finite dimensional space is preserved under linear equivalence. -/ theorem findim_eq (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : findim K V = findim K V₂ := begin haveI : finite_dimensional K V₂ := f.finite_dimensional, rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, letI : fintype s := s_finite.fintype, have A : findim K V = fintype.card s := findim_eq_card_basis s_basis, have : is_basis K (λx:s, f (subtype.val x)) := f.is_basis s_basis, have B : findim K V₂ = fintype.card s := findim_eq_card_basis this, rw [A, B] end end linear_equiv namespace finite_dimensional /-- If a submodule is less than or equal to a finite-dimensional submodule with the same dimension, they are equal. -/ lemma eq_of_le_of_findim_eq {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : findim K S₁ = findim K S₂) : S₁ = S₂ := begin rw ←linear_equiv.findim_eq (submodule.comap_subtype_equiv_of_le hle) at hd, exact le_antisymm hle (submodule.comap_subtype_eq_top.1 (eq_top_of_findim_eq hd)) end end finite_dimensional namespace linear_map open finite_dimensional /-- On a finite-dimensional space, an injective linear map is surjective. -/ lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V} (hinj : injective f) : surjective f := begin have h := dim_eq_of_injective _ hinj, rw [← findim_eq_dim, ← findim_eq_dim, nat_cast_inj] at h, exact range_eq_top.1 (eq_top_of_findim_eq h.symm) end /-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/ lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} : injective f ↔ surjective f := ⟨surjective_of_injective, λ hsurj, let ⟨g, hg⟩ := f.exists_right_inverse_of_surjective (range_eq_top.2 hsurj) in have function.right_inverse g f, from linear_map.ext_iff.1 hg, (left_inverse_of_surjective_of_right_inverse (surjective_of_injective this.injective) this).injective⟩ lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} : f.ker = ⊥ ↔ f.range = ⊤ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective] /-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they are also inverse to each other on the other side. -/ lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) : g * f = 1 := have ginj : injective g, from has_left_inverse.injective ⟨f, (λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl)⟩, let ⟨i, hi⟩ := g.exists_right_inverse_of_surjective (range_eq_top.2 (injective_iff_surjective.1 ginj)) in have f * (g * i) = f * 1, from congr_arg _ hi, by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 := ⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩ /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id := mul_eq_one_comm /-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/ lemma finite_dimensional_of_surjective [h : finite_dimensional K V] (f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ := is_noetherian_of_surjective V f hf /-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_range [h : finite_dimensional K V] (f : V →ₗ[K] V₂) : finite_dimensional K f.range := f.quot_ker_equiv_range.finite_dimensional /-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to the dimension of the source space. -/ theorem findim_range_add_findim_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) : findim K f.range + findim K f.ker = findim K V := by { rw [← f.quot_ker_equiv_range.findim_eq], exact submodule.findim_quotient_add_findim _ } end linear_map namespace linear_equiv open finite_dimensional variables [finite_dimensional K V] /-- The linear equivalence corresponging to an injective endomorphism. -/ noncomputable def of_injective_endo (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : V ≃ₗ[K] V := (linear_equiv.of_injective f h_inj).trans (linear_equiv.of_top _ (linear_map.ker_eq_bot_iff_range_eq_top.1 h_inj)) lemma of_injective_endo_to_fun (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : (of_injective_endo f h_inj).to_fun = f := rfl lemma of_injective_endo_right_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : f * (of_injective_endo f h_inj).symm = 1 := begin ext, simp only [linear_map.one_app, linear_map.mul_app], change f ((of_injective_endo f h_inj).symm x) = x, rw ← linear_equiv.inv_fun_apply (of_injective_endo f h_inj), apply (of_injective_endo f h_inj).right_inv, end lemma of_injective_endo_left_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : ((of_injective_endo f h_inj).symm : V →ₗ[K] V) * f = 1 := begin ext, simp only [linear_map.one_app, linear_map.mul_app], change (of_injective_endo f h_inj).symm (f x) = x, rw ← linear_equiv.inv_fun_apply (of_injective_endo f h_inj), apply (of_injective_endo f h_inj).left_inv, end end linear_equiv namespace linear_map lemma is_unit_iff [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.ker = ⊥ := begin split, { intro h_is_unit, rcases h_is_unit with ⟨u, hu⟩, rw [←hu, linear_map.ker_eq_bot'], intros x hx, change (1 : V →ₗ[K] V) x = 0, rw ← u.inv_val, change u.inv (u x) = 0, simp [hx] }, { intro h_inj, use ⟨f, (linear_equiv.of_injective_endo f h_inj).symm.to_linear_map, linear_equiv.of_injective_endo_right_inv f h_inj, linear_equiv.of_injective_endo_left_inv f h_inj⟩, refl } end end linear_map open vector_space finite_dimensional section top @[simp] theorem findim_top [finite_dimensional K V] : findim K (⊤ : submodule K V) = findim K V := linear_equiv.findim_eq $ linear_equiv.of_top ⊤ rfl end top namespace linear_map theorem injective_iff_surjective_of_findim_eq_findim [finite_dimensional K V] [finite_dimensional K V₂] (H : findim K V = findim K V₂) {f : V →ₗ[K] V₂} : function.injective f ↔ function.surjective f := begin have := findim_range_add_findim_ker f, rw [← ker_eq_bot, ← range_eq_top], refine ⟨λ h, _, λ h, _⟩, { rw [h, findim_bot, add_zero, H] at this, exact eq_top_of_findim_eq this }, { rw [h, findim_top, H] at this, exact findim_eq_zero.1 (add_right_injective _ this) } end theorem findim_le_findim_of_injective [finite_dimensional K V] [finite_dimensional K V₂] {f : V →ₗ[K] V₂} (hf : function.injective f) : findim K V ≤ findim K V₂ := calc findim K V = findim K f.range + findim K f.ker : (findim_range_add_findim_ker f).symm ... = findim K f.range : by rw [ker_eq_bot.2 hf, findim_bot, add_zero] ... ≤ findim K V₂ : submodule.findim_le _ end linear_map section /-- An integral domain that is module-finite as an algebra over a field is a field. -/ noncomputable def field_of_finite_dimensional (F K : Type*) [field F] [integral_domain K] [algebra F K] [finite_dimensional F K] : field K := { inv := λ x, if H : x = 0 then 0 else classical.some $ (show function.surjective (algebra.lmul_left F K x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' H).1) 1, mul_inv_cancel := λ x hx, show x * dite _ _ _ = _, by { rw dif_neg hx, exact classical.some_spec ((show function.surjective (algebra.lmul_left F K x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' hx).1) 1) }, inv_zero := dif_pos rfl, .. ‹integral_domain K› } end namespace submodule lemma findim_mono [finite_dimensional K V] : monotone (λ (s : submodule K V), findim K s) := λ s t hst, calc findim K s = findim K (comap t.subtype s) : linear_equiv.findim_eq (comap_subtype_equiv_of_le hst).symm ... ≤ findim K t : submodule.findim_le _ lemma lt_of_le_of_findim_lt_findim {s t : submodule K V} (le : s ≤ t) (lt : findim K s < findim K t) : s < t := lt_of_le_of_ne le (λ h, ne_of_lt lt (by rw h)) lemma lt_top_of_findim_lt_findim {s : submodule K V} (lt : findim K s < findim K V) : s < ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, rw ← @findim_top K V at lt, exact lt_of_le_of_findim_lt_findim le_top lt }, { exfalso, have : findim K V = 0 := dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin), rw this at lt, exact nat.not_lt_zero _ lt } end lemma findim_lt_findim_of_lt [finite_dimensional K V] {s t : submodule K V} (hst : s < t) : findim K s < findim K t := begin rw linear_equiv.findim_eq (comap_subtype_equiv_of_le (le_of_lt hst)).symm, refine findim_lt (lt_of_le_of_ne le_top _), intro h_eq_top, rw comap_subtype_eq_top at h_eq_top, apply not_le_of_lt hst h_eq_top, end end submodule section span open submodule lemma findim_span_le_card (s : set V) [fin : fintype s] : findim K (span K s) ≤ s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) ≤ (mk s : cardinal) := dim_span_le s, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma findim_span_eq_card {ι : Type*} [fintype ι] {b : ι → V} (hb : linear_independent K b) : findim K (span K (set.range b)) = fintype.card ι := begin haveI : finite_dimensional K (span K (set.range b)) := span_of_finite K (set.finite_range b), have : dim K (span K (set.range b)) = (mk (set.range b) : cardinal) := dim_span hb, rwa [←findim_eq_dim, ←lift_inj, mk_range_eq_of_injective hb.injective, cardinal.fintype_card, lift_nat_cast, lift_nat_cast, nat_cast_inj] at this, end lemma findim_span_set_eq_card (s : set V) [fin : fintype s] (hs : linear_independent K (coe : s → V)) : findim K (span K s) = s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) = (mk s : cardinal) := dim_span_set hs, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma span_lt_of_subset_of_card_lt_findim {s : set V} [fintype s] {t : submodule K V} (subset : s ⊆ t) (card_lt : s.to_finset.card < findim K t) : span K s < t := lt_of_le_of_findim_lt_findim (span_le.mpr subset) (lt_of_le_of_lt (findim_span_le_card _) card_lt) lemma span_lt_top_of_card_lt_findim {s : set V} [fintype s] (card_lt : s.to_finset.card < findim K V) : span K s < ⊤ := lt_top_of_findim_lt_findim (lt_of_le_of_lt (findim_span_le_card _) card_lt) end span section is_basis lemma linear_independent_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : linear_independent K b := linear_independent_iff'.mpr $ λ s g dependent i i_mem_s, begin by_contra gx_ne_zero, -- We'll derive a contradiction by showing `b '' (univ \ {i})` of cardinality `n - 1` -- spans a vector space of dimension `n`. refine ne_of_lt (span_lt_top_of_card_lt_findim (show (b '' (set.univ \ {i})).to_finset.card < findim K V, from _)) _, { calc (b '' (set.univ \ {i})).to_finset.card = ((set.univ \ {i}).to_finset.image b).card : by rw [set.to_finset_card, fintype.card_of_finset] ... ≤ (set.univ \ {i}).to_finset.card : finset.card_image_le ... = (finset.univ.erase i).card : congr_arg finset.card (finset.ext (by simp [and_comm])) ... < finset.univ.card : finset.card_erase_lt_of_mem (finset.mem_univ i) ... = findim K V : card_eq }, -- We already have that `b '' univ` spans the whole space, -- so we only need to show that the span of `b '' (univ \ {i})` contains each `b j`. refine trans (le_antisymm (span_mono (set.image_subset_range _ _)) (span_le.mpr _)) span_eq, rintros _ ⟨j, rfl, rfl⟩, -- The case that `j ≠ i` is easy because `b j ∈ b '' (univ \ {i})`. by_cases j_eq : j = i, swap, { refine subset_span ⟨j, (set.mem_diff _).mpr ⟨set.mem_univ _, _⟩, rfl⟩, exact mt set.mem_singleton_iff.mp j_eq }, -- To show `b i ∈ span (b '' (univ \ {i}))`, we use that it's a weighted sum -- of the other `b j`s. rw [j_eq, mem_coe, show b i = -((g i)⁻¹ • (s.erase i).sum (λ j, g j • b j)), from _], { refine submodule.neg_mem _ (smul_mem _ _ (sum_mem _ (λ k hk, _))), obtain ⟨k_ne_i, k_mem⟩ := finset.mem_erase.mp hk, refine smul_mem _ _ (subset_span ⟨k, _, rfl⟩), simpa using k_mem }, -- To show `b i` is a weighted sum of the other `b j`s, we'll rewrite this sum -- to have the form of the assumption `dependent`. apply eq_neg_of_add_eq_zero, calc b i + (g i)⁻¹ • (s.erase i).sum (λ j, g j • b j) = (g i)⁻¹ • (g i • b i + (s.erase i).sum (λ j, g j • b j)) : by rw [smul_add, ←mul_smul, inv_mul_cancel gx_ne_zero, one_smul] ... = (g i)⁻¹ • 0 : congr_arg _ _ ... = 0 : smul_zero _, -- And then it's just a bit of manipulation with finite sums. rwa [← finset.insert_erase i_mem_s, finset.sum_insert (finset.not_mem_erase _ _)] at dependent end /-- A finite family of vectors is linearly independent if and only if its cardinality equals the dimension of its span. -/ lemma linear_independent_iff_card_eq_findim_span {ι : Type*} [fintype ι] {b : ι → V} : linear_independent K b ↔ fintype.card ι = findim K (span K (set.range b)) := begin split, { intro h, exact (findim_span_eq_card h).symm }, { intro hc, let f := (submodule.subtype (span K (set.range b))), let b' : ι → span K (set.range b) := λ i, ⟨b i, mem_span.2 (λ p hp, hp (set.mem_range_self _))⟩, have hs : span K (set.range b') = ⊤, { rw eq_top_iff', intro x, have h : span K (f '' (set.range b')) = map f (span K (set.range b')) := span_image f, have hf : f '' (set.range b') = set.range b, { ext x, simp [set.mem_image, set.mem_range] }, rw hf at h, have hx : (x : V) ∈ span K (set.range b) := x.property, conv at hx { congr, skip, rw h }, simpa [mem_map] using hx }, have hi : disjoint (span K (set.range b')) f.ker, by simp, convert (linear_independent_of_span_eq_top_of_card_eq_findim hs hc).image hi } end lemma is_basis_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨linear_independent_of_span_eq_top_of_card_eq_findim span_eq card_eq, span_eq⟩ lemma finset_is_basis_of_span_eq_top_of_card_eq_findim {s : finset V} (span_eq : span K (↑s : set V) = ⊤) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ (λ x, x ∈ s)).symm ▸ span_eq) (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_span_eq_top_of_card_eq_findim {s : set V} [fintype s] (span_eq : span K s = ⊤) (card_eq : s.to_finset.card = findim K V) : is_basis K (λ (x : s), (x : V)) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ s).symm ▸ span_eq) (trans s.to_finset_card.symm card_eq) lemma span_eq_top_of_linear_independent_of_card_eq_findim {ι : Type*} [hι : nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : span K (set.range b) = ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, by_contra ne_top, have lt_top : span K (set.range b) < ⊤ := lt_of_le_of_ne le_top ne_top, exact ne_of_lt (submodule.findim_lt lt_top) (trans (findim_span_eq_card lin_ind) card_eq) }, { exfalso, apply ne_of_lt (fintype.card_pos_iff.mpr hι), symmetry, calc fintype.card ι = findim K V : card_eq ... = 0 : dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin) } end lemma is_basis_of_linear_independent_of_card_eq_findim {ι : Type*} [nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨lin_ind, span_eq_top_of_linear_independent_of_card_eq_findim lin_ind card_eq⟩ lemma finset_is_basis_of_linear_independent_of_card_eq_findim {s : finset V} (hs : s.nonempty) (lin_ind : linear_independent K (coe : (↑s : set V) → V)) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := @is_basis_of_linear_independent_of_card_eq_findim _ _ _ _ _ _ ⟨(⟨hs.some, hs.some_spec⟩ : (↑s : set V))⟩ _ _ lin_ind (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_linear_independent_of_card_eq_findim {s : set V} [nonempty s] [fintype s] (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = findim K V) : is_basis K (coe : s → V) := is_basis_of_linear_independent_of_card_eq_findim lin_ind (trans s.to_finset_card.symm card_eq) end is_basis namespace module namespace End lemma exists_ker_pow_eq_ker_pow_succ [finite_dimensional K V] (f : End K V) : ∃ (k : ℕ), k ≤ findim K V ∧ (f ^ k).ker = (f ^ k.succ).ker := begin classical, by_contradiction h_contra, simp_rw [not_exists, not_and] at h_contra, have h_le_ker_pow : ∀ (n : ℕ), n ≤ (findim K V).succ → n ≤ findim K (f ^ n).ker, { intros n hn, induction n with n ih, { exact zero_le (findim _ _) }, { have h_ker_lt_ker : (f ^ n).ker < (f ^ n.succ).ker, { refine lt_of_le_of_ne _ (h_contra n (nat.le_of_succ_le_succ hn)), rw pow_succ, apply linear_map.ker_le_ker_comp }, have h_findim_lt_findim : findim K (f ^ n).ker < findim K (f ^ n.succ).ker, { apply submodule.findim_lt_findim_of_lt h_ker_lt_ker }, calc n.succ ≤ (findim K ↥(linear_map.ker (f ^ n))).succ : nat.succ_le_succ (ih (nat.le_of_succ_le hn)) ... ≤ findim K ↥(linear_map.ker (f ^ n.succ)) : nat.succ_le_of_lt h_findim_lt_findim } }, have h_le_findim_V : ∀ n, findim K (f ^ n).ker ≤ findim K V := λ n, submodule.findim_le _, have h_any_n_lt: ∀ n, n ≤ (findim K V).succ → n ≤ findim K V := λ n hn, (h_le_ker_pow n hn).trans (h_le_findim_V n), show false, from nat.not_succ_le_self _ (h_any_n_lt (findim K V).succ (findim K V).succ.le_refl), end lemma ker_pow_constant {f : End K V} {k : ℕ} (h : (f ^ k).ker = (f ^ k.succ).ker) : ∀ m, (f ^ k).ker = (f ^ (k + m)).ker | 0 := by simp | (m + 1) := begin apply le_antisymm, { rw [add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_constant m, add_comm m 1, ←add_assoc, pow_add, pow_add f k m], change linear_map.ker ((f ^ (k + 1)).comp (f ^ m)) ≤ linear_map.ker ((f ^ k).comp (f ^ m)), rw [linear_map.ker_comp, linear_map.ker_comp, h, nat.add_one], exact le_refl _, } end lemma ker_pow_eq_ker_pow_findim_of_le [finite_dimensional K V] {f : End K V} {m : ℕ} (hm : findim K V ≤ m) : (f ^ m).ker = (f ^ findim K V).ker := begin obtain ⟨k, h_k_le, hk⟩ : ∃ k, k ≤ findim K V ∧ linear_map.ker (f ^ k) = linear_map.ker (f ^ k.succ) := exists_ker_pow_eq_ker_pow_succ f, calc (f ^ m).ker = (f ^ (k + (m - k))).ker : by rw nat.add_sub_of_le (h_k_le.trans hm) ... = (f ^ k).ker : by rw ker_pow_constant hk _ ... = (f ^ (k + (findim K V - k))).ker : ker_pow_constant hk (findim K V - k) ... = (f ^ findim K V).ker : by rw nat.add_sub_of_le h_k_le end lemma ker_pow_le_ker_pow_findim [finite_dimensional K V] (f : End K V) (m : ℕ) : (f ^ m).ker ≤ (f ^ findim K V).ker := begin by_cases h_cases: m < findim K V, { rw [←nat.add_sub_of_le (nat.le_of_lt h_cases), add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_eq_ker_pow_findim_of_le (le_of_not_lt h_cases)], exact le_refl _ } end end End end module
0a1ecf04b40901944166f91ae882ff7034ed3453
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/category/Quiv.lean
774f1ec9c4fa48078c7ae285581985ddd55ddcbc
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,065
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.path_category import category_theory.category.Cat /-! # The category of quivers The category of (bundled) quivers, and the free/forgetful adjunction between `Cat` and `Quiv`. -/ universes v u namespace category_theory /-- Category of quivers. -/ def Quiv := bundled quiver.{(v+1) u} namespace Quiv instance : has_coe_to_sort Quiv := { S := Type u, coe := bundled.α } instance str (C : Quiv.{v u}) : quiver.{(v+1) u} C := C.str /-- Construct a bundled `Quiv` from the underlying type and the typeclass. -/ def of (C : Type u) [quiver.{v+1} C] : Quiv.{v u} := bundled.of C instance : inhabited Quiv := ⟨Quiv.of (quiver.empty pempty)⟩ /-- Category structure on `Quiv` -/ instance category : large_category.{max v u} Quiv.{v u} := { hom := λ C D, prefunctor C D, id := λ C, prefunctor.id C, comp := λ C D E F G, prefunctor.comp F G, id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- The forgetful functor from categories to quivers. -/ @[simps] def forget : Cat.{v u} ⥤ Quiv.{v u} := { obj := λ C, Quiv.of C, map := λ C D F, F.to_prefunctor, } end Quiv namespace Cat /-- The functor sending each quiver to its path category. -/ @[simps] def free : Quiv.{v u} ⥤ Cat.{(max u v) u} := { obj := λ V, Cat.of (paths V), map := λ V W F, { obj := λ X, F.obj X, map := λ X Y f, F.map_path f, map_comp' := λ X Y Z f g, F.map_path_comp f g, }, map_id' := λ V, by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl }, map_comp' := λ U V W F G, by { change (show paths U ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } } end Cat namespace Quiv /-- Any prefunctor into a category lifts to a functor from the path category. -/ @[simps] def lift {V : Type u} [quiver.{v+1} V] {C : Type u} [category.{v} C] (F : prefunctor V C) : paths V ⥤ C := { obj := λ X, F.obj X, map := λ X Y f, compose_path (F.map_path f), } -- We might construct `of_lift_iso_self : paths.of ⋙ lift F ≅ F` -- (and then show that `lift F` is initial amongst such functors) -- but it would require lifting quite a bit of machinery to quivers! /-- The adjunction between forming the free category on a quiver, and forgetting a category to a quiver. -/ def adj : Cat.free ⊣ Quiv.forget := adjunction.mk_of_hom_equiv { hom_equiv := λ V C, { to_fun := λ F, paths.of.comp F.to_prefunctor, inv_fun := λ F, lift F, left_inv := λ F, by { ext, { erw (eq_conj_eq_to_hom _).symm, apply category.id_comp }, refl }, right_inv := begin rintro ⟨obj,map⟩, dsimp only [prefunctor.comp], congr, ext X Y f, exact category.id_comp _, end, }, hom_equiv_naturality_left_symm' := λ V W C f g, by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } } end Quiv end category_theory
a6fb0002c6d1ecdfb54425cf70a3adc41f16e798
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Meta/InferType.lean
2e0632a459bba5d506f8a375afeb1808722f0f93
[ "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
14,787
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.Data.LBool import Lean.Meta.Basic namespace Lean.Meta def throwFunctionExpected {α} (f : Expr) : MetaM α := throwError! "function expected{indentExpr f}" private def inferAppType (f : Expr) (args : Array Expr) : MetaM Expr := do let mut fType ← inferType f let mut j := 0 for i in [:args.size] do match fType with | Expr.forallE _ _ b _ => fType := b | _ => match (← whnf $ fType.instantiateRevRange j i args) with | Expr.forallE _ _ b _ => j := i; fType := b | _ => throwFunctionExpected $ mkAppRange f 0 (i+1) args pure $ fType.instantiateRevRange j args.size args def throwIncorrectNumberOfLevels {α} (constName : Name) (us : List Level) : MetaM α := throwError! "incorrect number of universe levels {mkConst constName us}" private def inferConstType (c : Name) (us : List Level) : MetaM Expr := do let cinfo ← getConstInfo c if cinfo.lparams.length == us.length then pure $ cinfo.instantiateTypeLevelParams us else throwIncorrectNumberOfLevels c us private def inferProjType (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do let failed {α} : Unit → MetaM α := fun _ => throwError! "invalide projection{indentExpr (mkProj structName idx e)}" let structType ← inferType e let structType ← whnf structType matchConstStruct structType.getAppFn failed fun structVal structLvls ctorVal => let n := structVal.nparams let structParams := structType.getAppArgs if n != structParams.size then failed () else do let mut ctorType ← inferAppType (mkConst ctorVal.name structLvls) structParams for i in [:idx] do ctorType ← whnf ctorType match ctorType with | Expr.forallE _ _ body _ => if body.hasLooseBVars then ctorType := body.instantiate1 $ mkProj structName i e else ctorType := body | _ => failed () ctorType ← whnf ctorType match ctorType with | Expr.forallE _ d _ _ => pure d | _ => failed () def throwTypeExcepted {α} (type : Expr) : MetaM α := throwError! "type expected{indentExpr type}" variables {m : Type → Type} [MonadLiftT MetaM m] private def getLevelImp (type : Expr) : MetaM Level := do let typeType ← inferType type let typeType ← whnfD typeType match typeType with | Expr.sort lvl _ => pure lvl | Expr.mvar mvarId _ => if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then throwTypeExcepted type else let lvl ← mkFreshLevelMVar assignExprMVar mvarId (mkSort lvl) pure lvl | _ => throwTypeExcepted type def getLevel (type : Expr) : m Level := liftMetaM $ getLevelImp type private def inferForallType (e : Expr) : MetaM Expr := forallTelescope e fun xs e => do let lvl ← getLevel e let lvl ← xs.foldrM (init := lvl) fun x lvl => do let xType ← inferType x let xTypeLvl ← getLevel xType pure $ mkLevelIMax xTypeLvl lvl pure $ mkSort lvl.normalize /- Infer type of lambda and let expressions -/ private def inferLambdaType (e : Expr) : MetaM Expr := lambdaLetTelescope e fun xs e => do let type ← inferType e mkForallFVars xs type @[inline] private def withLocalDecl' {α} (name : Name) (bi : BinderInfo) (type : Expr) (x : Expr → MetaM α) : MetaM α := savingCache do let fvarId ← mkFreshId withReader (fun ctx => { ctx with lctx := ctx.lctx.mkLocalDecl fvarId name type bi }) do x (mkFVar fvarId) def throwUnknownMVar {α} (mvarId : MVarId) : MetaM α := throwError! "unknown metavariable '{mkMVar mvarId}'" private def inferMVarType (mvarId : MVarId) : MetaM Expr := do match (← getMCtx).findDecl? mvarId with | some d => pure d.type | none => throwUnknownMVar mvarId private def inferFVarType (fvarId : FVarId) : MetaM Expr := do match (← getLCtx).find? fvarId with | some d => pure d.type | none => throwUnknownFVar fvarId @[inline] private def checkInferTypeCache (e : Expr) (inferType : MetaM Expr) : MetaM Expr := do match (← get).cache.inferType.find? e with | some type => pure type | none => let type ← inferType modify fun s => { s with cache := { s.cache with inferType := s.cache.inferType.insert e type } } pure type def inferTypeImp (e : Expr) : MetaM Expr := let rec infer : Expr → MetaM Expr | Expr.const c lvls _ => inferConstType c lvls | e@(Expr.proj n i s _) => checkInferTypeCache e (inferProjType n i s) | e@(Expr.app f _ _) => checkInferTypeCache e (inferAppType f.getAppFn e.getAppArgs) | Expr.mvar mvarId _ => inferMVarType mvarId | Expr.fvar fvarId _ => inferFVarType fvarId | Expr.bvar bidx _ => throwError! "unexpected bound variable {mkBVar bidx}" | Expr.mdata _ e _ => infer e | Expr.lit v _ => pure v.type | Expr.sort lvl _ => pure $ mkSort (mkLevelSucc lvl) | e@(Expr.forallE _ _ _ _) => checkInferTypeCache e (inferForallType e) | e@(Expr.lam _ _ _ _) => checkInferTypeCache e (inferLambdaType e) | e@(Expr.letE _ _ _ _ _) => checkInferTypeCache e (inferLambdaType e) withTransparency TransparencyMode.default (infer e) @[builtinInit] def setInferTypeRef : IO Unit := inferTypeRef.set inferTypeImp /-- Return `LBool.true` if given level is always equivalent to universe level zero. It is used to implement `isProp`. -/ private def isAlwaysZero : Level → Bool | Level.zero _ => true | Level.mvar _ _ => false | Level.param _ _ => false | Level.succ _ _ => false | Level.max u v _ => isAlwaysZero u && isAlwaysZero v | Level.imax _ u _ => isAlwaysZero u /-- `isArrowProp type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Prop`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProp : Expr → Nat → MetaM LBool | Expr.sort u _, 0 => return isAlwaysZero (← instantiateLevelMVars u) $.toLBool | Expr.forallE _ _ _ _, 0 => pure LBool.false | Expr.forallE _ _ b _, n+1 => isArrowProp b n | Expr.letE _ _ _ b _, n => isArrowProp b n | Expr.mdata _ e _, n => isArrowProp e n | _, _ => pure LBool.undef /-- `isPropQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proposition. -/ private partial def isPropQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowProp constType arity | Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType arity | Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType arity | Expr.app f _ _, arity => isPropQuickApp f (arity+1) | Expr.mdata _ e _, arity => isPropQuickApp e arity | Expr.letE _ _ _ b _, arity => isPropQuickApp b arity | Expr.lam _ _ _ _, 0 => pure LBool.false | Expr.lam _ _ b _, arity+1 => isPropQuickApp b arity | _, _ => pure LBool.undef /-- `isPropQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proposition. -/ partial def isPropQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.false | Expr.lam _ _ _ _ => pure LBool.false | Expr.letE _ _ _ b _ => isPropQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => isPropQuick b | Expr.mdata _ e _ => isPropQuick e | Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowProp constType 0 | Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType 0 | Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType 0 | Expr.app f _ _ => isPropQuickApp f 1 /-- `isProp whnf e` return `true` if `e` is a proposition. If `e` contains metavariables, it may not be possible to decide whether is a proposition or not. We return `false` in this case. We considered using `LBool` and retuning `LBool.undef`, but we have no applications for it. -/ private def isPropImp (e : Expr) : MetaM Bool := do let r ← isPropQuick e match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => let type ← inferType e let type ← whnfD type match type with | Expr.sort u _ => return isAlwaysZero (← instantiateLevelMVars u) | _ => pure false def isProp (e : Expr) : m Bool := liftMetaM $ isPropImp e /-- `isArrowProposition type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> B`, where `B` is a proposition. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProposition : Expr → Nat → MetaM LBool | Expr.forallE _ _ b _, n+1 => isArrowProposition b n | Expr.letE _ _ _ b _, n => isArrowProposition b n | Expr.mdata _ e _, n => isArrowProposition e n | type, 0 => isPropQuick type | _, _ => pure LBool.undef mutual /-- `isProofQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proof. -/ private partial def isProofQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowProposition constType arity | Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType arity | Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType arity | Expr.app f _ _, arity => isProofQuickApp f (arity+1) | Expr.mdata _ e _, arity => isProofQuickApp e arity | Expr.letE _ _ _ b _, arity => isProofQuickApp b arity | Expr.lam _ _ b _, 0 => isProofQuick b | Expr.lam _ _ b _, arity+1 => isProofQuickApp b arity | _, _ => pure LBool.undef /-- `isProofQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proof. -/ partial def isProofQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.false | Expr.lam _ _ b _ => isProofQuick b | Expr.letE _ _ _ b _ => isProofQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => pure LBool.false | Expr.mdata _ e _ => isProofQuick e | Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowProposition constType 0 | Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType 0 | Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType 0 | Expr.app f _ _ => isProofQuickApp f 1 end private def isProofImp (e : Expr) : MetaM Bool := do let r ← isProofQuick e match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => do let type ← inferType e Meta.isProp type def isProof (e : Expr) : m Bool := liftMetaM $ isProofImp e /-- `isArrowType type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Sort _`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowType : Expr → Nat → MetaM LBool | Expr.sort u _, 0 => pure LBool.true | Expr.forallE _ _ _ _, 0 => pure LBool.false | Expr.forallE _ _ b _, n+1 => isArrowType b n | Expr.letE _ _ _ b _, n => isArrowType b n | Expr.mdata _ e _, n => isArrowType e n | _, _ => pure LBool.undef /-- `isTypeQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a type. -/ private partial def isTypeQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowType constType arity | Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowType fvarType arity | Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowType mvarType arity | Expr.app f _ _, arity => isTypeQuickApp f (arity+1) | Expr.mdata _ e _, arity => isTypeQuickApp e arity | Expr.letE _ _ _ b _, arity => isTypeQuickApp b arity | Expr.lam _ _ _ _, 0 => pure LBool.false | Expr.lam _ _ b _, arity+1 => isTypeQuickApp b arity | _, _ => pure LBool.undef /-- `isTypeQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a type. -/ partial def isTypeQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.true | Expr.lam _ _ _ _ => pure LBool.false | Expr.letE _ _ _ b _ => isTypeQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => pure LBool.true | Expr.mdata _ e _ => isTypeQuick e | Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowType constType 0 | Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowType fvarType 0 | Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowType mvarType 0 | Expr.app f _ _ => isTypeQuickApp f 1 private def isTypeImp (e : Expr) : m Bool := liftMetaM do let r ← isTypeQuick e match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => let type ← inferType e let type ← whnfD type match type with | Expr.sort _ _ => pure true | _ => pure false def isType (e : Expr) : m Bool := liftMetaM $ isTypeImp e private partial def isTypeFormerTypeImp (type : Expr) : MetaM Bool := do let type ← whnfD type match type with | Expr.sort _ _ => pure true | Expr.forallE n d b c => withLocalDecl' n c.binderInfo d fun fvar => isTypeFormerTypeImp (b.instantiate1 fvar) | _ => pure false def isTypeFormerType (e : Expr) : m Bool := liftMetaM $ isTypeFormerTypeImp e /-- Return true iff `e : Sort _` or `e : (forall As, Sort _)`. Remark: it subsumes `isType` -/ def isTypeFormer (e : Expr) : m Bool := liftMetaM do let type ← inferType e isTypeFormerType type end Lean.Meta
0ed7baf791bed7f3e56081cd27bf6655595ebceb
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/monoidal/End.lean
cc4bbe18d6e7f333bc0ee20786d412cdac45fe21
[ "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
2,515
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.functor /-! # Endofunctors as a monoidal category. We give the monoidal category structure on `C ⥤ C`, and show that when `C` itself is monoidal, it embeds via a monoidal functor into `C ⥤ C`. ## TODO Can we use this to show coherence results, e.g. a cheap proof that `λ_ (𝟙_ C) = ρ_ (𝟙_ C)`? I suspect this is harder than is usually made out. -/ universes v u namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of endofunctors of any category is a monoidal category, with tensor product given by composition of functors (and horizontal composition of natural transformations). -/ def endofunctor_monoidal_category : monoidal_category (C ⥤ C) := { tensor_obj := λ F G, F ⋙ G, tensor_hom := λ F G F' G' α β, α ◫ β, tensor_unit := 𝟭 C, associator := λ F G H, functor.associator F G H, left_unitor := λ F, functor.left_unitor F, right_unitor := λ F, functor.right_unitor F, }. open category_theory.monoidal_category variables [monoidal_category.{v} C] local attribute [instance] endofunctor_monoidal_category local attribute [reducible] endofunctor_monoidal_category /-- Tensoring on the right gives a monoidal functor from `C` into endofunctors of `C`. -/ @[simps] def tensoring_right_monoidal : monoidal_functor C (C ⥤ C) := { ε := (right_unitor_nat_iso C).inv, μ := λ X Y, { app := λ Z, (α_ Z X Y).hom, naturality' := λ Z Z' f, by { dsimp, rw associator_naturality, simp, } }, μ_natural' := λ X Y X' Y' f g, by { ext Z, dsimp, simp [associator_naturality], }, associativity' := λ X Y Z, by { ext W, dsimp, simp [pentagon], }, left_unitality' := λ X, by { ext Y, dsimp, rw [category.id_comp, triangle, ←tensor_comp], simp, }, right_unitality' := λ X, begin ext Y, dsimp, rw [tensor_id, category.comp_id, right_unitor_tensor_inv, category.assoc, iso.inv_hom_id_assoc, ←id_tensor_comp, iso.inv_hom_id, tensor_id], end, ε_is_iso := by apply_instance, μ_is_iso := λ X Y, { inv := -- We could avoid needing to do this explicitly by -- constructing a partially applied analogue of `associator_nat_iso`. { app := λ Z, (α_ Z X Y).inv, naturality' := λ Z Z' f, by { dsimp, rw ←associator_inv_naturality, simp, } }, }, ..tensoring_right C }. end category_theory
17c298c1951abb0afb14190478e9ec957fa1d99a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/valuation/integral.lean
4969e3647a99a06cc4df1fb6b31adcac9373102c
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,100
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 ring_theory.integrally_closed import ring_theory.valuation.integers /-! # Integral elements over the ring of integers of a valution The ring of integers is integrally closed inside the original ring. -/ universes u v w open_locale big_operators namespace valuation namespace integers section comm_ring variables {R : Type u} {Γ₀ : Type v} [comm_ring R] [linear_ordered_comm_group_with_zero Γ₀] variables {v : valuation R Γ₀} {O : Type w} [comm_ring O] [algebra O R] (hv : integers v O) include hv open polynomial lemma mem_of_integral {x : R} (hx : is_integral O x) : x ∈ v.integer := let ⟨p, hpm, hpx⟩ := hx in le_of_not_lt $ λ (hvx : 1 < v x), begin rw [hpm.as_sum, eval₂_add, eval₂_pow, eval₂_X, eval₂_finset_sum, add_eq_zero_iff_eq_neg] at hpx, replace hpx := congr_arg v hpx, refine ne_of_gt _ hpx, rw [v.map_neg, v.map_pow], refine v.map_sum_lt' (zero_lt_one.trans_le (one_le_pow_of_one_le' hvx.le _)) (λ i hi, _), rw [eval₂_mul, eval₂_pow, eval₂_C, eval₂_X, v.map_mul, v.map_pow, ← one_mul (v x ^ p.nat_degree)], cases (hv.2 $ p.coeff i).lt_or_eq with hvpi hvpi, { exact mul_lt_mul₀ hvpi (pow_lt_pow₀ hvx $ finset.mem_range.1 hi) }, { erw hvpi, rw [one_mul, one_mul], exact pow_lt_pow₀ hvx (finset.mem_range.1 hi) } end protected lemma integral_closure : integral_closure O R = ⊥ := bot_unique $ λ r hr, let ⟨x, hx⟩ := hv.3 (hv.mem_of_integral hr) in algebra.mem_bot.2 ⟨x, hx⟩ end comm_ring section fraction_field variables {K : Type u} {Γ₀ : Type v} [field K] [linear_ordered_comm_group_with_zero Γ₀] variables {v : valuation K Γ₀} {O : Type w} [comm_ring O] [is_domain O] variables [algebra O K] [is_fraction_ring O K] variables (hv : integers v O) lemma integrally_closed : is_integrally_closed O := (is_integrally_closed.integral_closure_eq_bot_iff K).mp (valuation.integers.integral_closure hv) end fraction_field end integers end valuation
418fcbbbbdb5e65ac7b172e8568ab0ee3adb1607
63abd62053d479eae5abf4951554e1064a4c45b4
/src/group_theory/group_action.lean
ad3d5a85b2233a12ff303de6bd5db4134f5cfb7e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
16,407
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.coset universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale big_operators open function /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[protect_proj] class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) section variables [monoid α] [mul_action α β] theorem mul_smul (a₁ a₂ : α) (b : β) : (a₁ * a₂) • b = a₁ • a₂ • b := mul_action.mul_smul _ _ _ lemma smul_smul (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm lemma smul_comm {α : Type u} {β : Type v} [comm_monoid α] [mul_action α β] (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = a₂ • a₁ • b := by rw [←mul_smul, ←mul_smul, mul_comm] variable (α) @[simp] theorem one_smul (b : β) : (1 : α) • b = b := mul_action.one_smul _ variables {α} @[simp] lemma units.inv_smul_smul (u : units α) (x : β) : (↑u⁻¹:α) • (u:α) • x = x := by rw [smul_smul, u.inv_mul, one_smul] @[simp] lemma units.smul_inv_smul (u : units α) (x : β) : (u:α) • (↑u⁻¹:α) • x = x := by rw [smul_smul, u.mul_inv, one_smul] /-- If a monoid `α` acts on `β`, then each `u : units α` defines a permutation of `β`. -/ def units.smul_perm_hom : units α →* equiv.perm β := { to_fun := λ u, ⟨λ x, (u:α) • x, λ x, (↑u⁻¹:α) • x, u.inv_smul_smul, u.smul_inv_smul⟩, map_one' := equiv.ext $ one_smul α, map_mul' := λ u₁ u₂, equiv.ext $ mul_smul (u₁:α) u₂ } @[simp] lemma units.smul_left_cancel (u : units α) {x y : β} : (u:α) • x = (u:α) • y ↔ x = y := u.smul_perm_hom.apply_eq_iff_eq lemma units.smul_eq_iff_eq_inv_smul (u : units α) {x y : β} : (u:α) • x = y ↔ x = (↑u⁻¹:α) • y := u.smul_perm_hom.apply_eq_iff_eq_symm_apply lemma is_unit.smul_left_cancel {a : α} (ha : is_unit a) {x y : β} : a • x = a • y ↔ x = y := let ⟨u, hu⟩ := ha in hu ▸ u.smul_left_cancel /-- Pullback a multiplicative action along an injective map respecting `•`. -/ protected def function.injective.mul_action [has_scalar α γ] (f : γ → β) (hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : mul_action α γ := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. -/ protected def function.surjective.mul_action [has_scalar α γ] (f : β → γ) (hf : surjective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : mul_action α γ := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } section gwz variables {G : Type*} [group_with_zero G] [mul_action G β] @[simp] lemma inv_smul_smul' {c : G} (hc : c ≠ 0) (x : β) : c⁻¹ • c • x = x := (units.mk0 c hc).inv_smul_smul x @[simp] lemma smul_inv_smul' {c : G} (hc : c ≠ 0) (x : β) : c • c⁻¹ • x = x := (units.mk0 c hc).smul_inv_smul x lemma inv_smul_eq_iff {a : G} (ha : a ≠ 0) {x y : β} : a⁻¹ • x = y ↔ x = a • y := by { split; intro h, rw [← h, smul_inv_smul' ha], rw [h, inv_smul_smul' ha] } lemma eq_inv_smul_iff {a : G} (ha : a ≠ 0) {x y : β} : x = a⁻¹ • y ↔ a • x = y := by { split; intro h, rw [h, smul_inv_smul' ha], rw [← h, inv_smul_smul' ha] } end gwz variables (p : Prop) [decidable p] lemma ite_smul (a₁ a₂ : α) (b : β) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl lemma smul_ite (a : α) (b₁ b₂ : β) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end section compatible_scalar variables (R M N : Type*) [has_scalar R M] [has_scalar M N] [has_scalar R N] /-- An instance of `is_scalar_tower R M N` states that the multiplicative action of `R` on `N` is determined by the multiplicative actions of `R` on `M` and `M` on `N`. -/ class is_scalar_tower : Prop := (smul_assoc : ∀ (x : R) (y : M) (z : N), (x • y) • z = x • (y • z)) variables {R M N} @[simp] lemma smul_assoc [is_scalar_tower R M N] (x : R) (y : M) (z : N) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z end compatible_scalar namespace mul_action variables (α) [monoid α] /-- The regular action of a monoid on itself by left multiplication. -/ def regular : mul_action α α := { smul := λ a₁ a₂, a₁ * a₂, one_smul := λ a, one_mul a, mul_smul := λ a₁ a₂ a₃, mul_assoc _ _ _, } variables [mul_action α β] section regular local attribute [instance] regular instance is_scalar_tower.left : is_scalar_tower α α β := ⟨λ x y z, mul_smul x y z⟩ end regular /-- The orbit of an element under an action. -/ def orbit (b : β) := set.range (λ x : α, x • b) variable {α} lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ variable (α) /-- The stabilizer of an element under an action, i.e. what sends the element to itself. Note that this is a set: for the group stabilizer see `stabilizer`. -/ def stabilizer_carrier (b : β) : set α := {x : α | x • b = b} variable {α} @[simp] lemma mem_stabilizer_iff {b : β} {x : α} : x ∈ stabilizer_carrier α b ↔ x • b = b := iff.rfl variables (α) (β) /-- The set of elements fixed under the whole action. -/ def fixed_points : set β := {b : β | ∀ x : α, x • b = b} /-- `fixed_by g` is the subfield of elements fixed by `g`. -/ def fixed_by (g : α) : set β := { x | g • x = x } theorem fixed_eq_Inter_fixed_by : fixed_points α β = ⋂ g : α, fixed_by α β g := set.ext $ λ x, ⟨λ hx, set.mem_Inter.2 $ λ g, hx g, λ hx g, by exact (set.mem_Inter.1 hx g : _)⟩ variables {α} (β) @[simp] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl @[simp] lemma mem_fixed_by {g : α} {b : β} : b ∈ fixed_by α β g ↔ g • b = b := iff.rfl lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _))⟩ /-- An action of `α` on `β` and a monoid homomorphism `γ → α` induce an action of `γ` on `β`. -/ def comp_hom [monoid γ] (g : γ →* α) : mul_action γ β := { smul := λ x b, (g x) • b, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } variables (α) {β} /-- The stabilizer of a point `b` as a submonoid of `α`. -/ def stabilizer.submonoid (b : β) : submonoid α := { carrier := stabilizer_carrier α b, one_mem' := one_smul _ b, mul_mem' := λ a a' (ha : a • b = b) (hb : a' • b = b), by rw [mem_stabilizer_iff, ←smul_smul, hb, ha] } variables (α β) /-- Embedding induced by action. -/ def to_fun : β ↪ (α → β) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul α y₁ ▸ one_smul α y₂ ▸ by convert congr_fun H 1⟩ variables {α β} @[simp] lemma to_fun_apply (x : α) (y : β) : mul_action.to_fun α β y x = x • y := rfl end mul_action namespace mul_action variables [group α] [mul_action α β] section open mul_action quotient_group @[simp] lemma inv_smul_smul (c : α) (x : β) : c⁻¹ • c • x = x := (to_units c).inv_smul_smul x @[simp] lemma smul_inv_smul (c : α) (x : β) : c • c⁻¹ • x = x := (to_units c).smul_inv_smul x lemma inv_smul_eq_iff {a : α} {x y : β} : a⁻¹ • x = y ↔ x = a • y := begin split; rintro rfl, {rw smul_inv_smul}, {rw inv_smul_smul}, end lemma eq_inv_smul_iff {a : α} {x y : β} : x = a⁻¹ • y ↔ a • x = y := begin split; rintro rfl, {rw smul_inv_smul}, {rw inv_smul_smul}, end variable (α) /-- The stabilizer of an element under an action, i.e. what sends the element to itself. A subgroup.-/ def stabilizer (b : β) : subgroup α := { inv_mem' := λ a (ha : a • b = b), show a⁻¹ • b = b, by rw [inv_smul_eq_iff, ha] ..stabilizer.submonoid α b } variable (β) /-- Given an action of a group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/ def to_perm : α →* equiv.perm β := units.smul_perm_hom.comp to_units.to_monoid_hom variables {α} {β} protected lemma bijective (g : α) : bijective (λ b : β, g • b) := (to_perm α β g).bijective lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x, show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩, λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹, show (y * x⁻¹) • a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_action.mul_smul, hx]}⟩⟩)⟩ variables (α) {β} /-- The stabilizer of a point `b` as a subgroup of `α`. -/ def stabilizer.subgroup (b : β) : subgroup α := { inv_mem' := λ x (hx : x • b = b), show x⁻¹ • b = b, by rw [← hx, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul, hx], ..stabilizer.submonoid α b } variables {β} @[simp] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) := ⟨g⁻¹, by simp⟩ @[simp] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) := ⟨g * h⁻¹, by simp [mul_smul]⟩ variables (α) (β) /-- The relation "in the same orbit". -/ def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } variables {α β} open quotient_group mul_action /-- Action on left cosets. -/ def mul_left_cosets (H : subgroup α) (x : α) (y : quotient H) : quotient H := quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y)) (λ a b (hab : _ ∈ H), quotient_group.eq.2 (by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance quotient (H : subgroup α) : mul_action α (quotient H) := { smul := mul_left_cosets H, one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [subgroup.one_mem])), mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [mul_inv_rev, subgroup.one_mem, mul_assoc])) } instance mul_left_cosets_comp_subtype_val (H I : subgroup α) : mul_action I (quotient H) := mul_action.comp_hom (quotient H) (subgroup.subtype I) variables (α) {β} (x : β) /-- The canonical map from the quotient of the stabilizer to the set. -/ def of_quotient_stabilizer (g : quotient (mul_action.stabilizer α x)) : β := quotient.lift_on' g (•x) $ λ g1 g2 H, calc g1 • x = g1 • (g1⁻¹ * g2) • x : congr_arg _ H.symm ... = g2 • x : by rw [smul_smul, mul_inv_cancel_left] @[simp] theorem of_quotient_stabilizer_mk (g : α) : of_quotient_stabilizer α x (quotient_group.mk g) = g • x := rfl theorem of_quotient_stabilizer_mem_orbit (g) : of_quotient_stabilizer α x g ∈ orbit α x := quotient.induction_on' g $ λ g, ⟨g, rfl⟩ theorem of_quotient_stabilizer_smul (g : α) (g' : quotient (mul_action.stabilizer α x)) : of_quotient_stabilizer α x (g • g') = g • of_quotient_stabilizer α x g' := quotient.induction_on' g' $ λ _, mul_smul _ _ _ theorem injective_of_quotient_stabilizer : function.injective (of_quotient_stabilizer α x) := λ y₁ y₂, quotient.induction_on₂' y₁ y₂ $ λ g₁ g₂ (H : g₁ • x = g₂ • x), quotient.sound' $ show (g₁⁻¹ * g₂) • x = x, by rw [mul_smul, ← H, mul_action.inv_smul_smul] /-- Orbit-stabilizer theorem. -/ noncomputable def orbit_equiv_quotient_stabilizer (b : β) : orbit α b ≃ quotient (stabilizer α b) := equiv.symm $ equiv.of_bijective (λ g, ⟨of_quotient_stabilizer α b g, of_quotient_stabilizer_mem_orbit α b g⟩) ⟨λ x y hxy, injective_of_quotient_stabilizer α b (by convert congr_arg subtype.val hxy), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩ @[simp] theorem orbit_equiv_quotient_stabilizer_symm_apply (b : β) (a : α) : ((orbit_equiv_quotient_stabilizer α b).symm a : β) = a • b := rfl end end mul_action /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : α), r • (0 : β) = 0) section variables [monoid α] [add_monoid β] [distrib_mul_action α β] theorem smul_add (a : α) (b₁ b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : α) : a • (0 : β) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. -/ protected def function.injective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : γ →+ β) (hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : distrib_mul_action α γ := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism.-/ protected def function.surjective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : β →+ γ) (hf : surjective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : distrib_mul_action α γ := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } theorem units.smul_eq_zero (u : units α) {x : β} : (u : α) • x = 0 ↔ x = 0 := ⟨λ h, by rw [← u.inv_smul_smul x, h, smul_zero], λ h, h.symm ▸ smul_zero _⟩ theorem units.smul_ne_zero (u : units α) {x : β} : (u : α) • x ≠ 0 ↔ x ≠ 0 := not_congr u.smul_eq_zero @[simp] theorem is_unit.smul_eq_zero {u : α} (hu : is_unit u) {x : β} : u • x = 0 ↔ x = 0 := exists.elim hu $ λ u hu, hu ▸ u.smul_eq_zero variable (β) /-- Scalar multiplication by `r` as an `add_monoid_hom`. -/ def const_smul_hom (r : α) : β →+ β := { to_fun := (•) r, map_zero' := smul_zero r, map_add' := smul_add r } variable {β} @[simp] lemma const_smul_hom_apply (r : α) (x : β) : const_smul_hom β r x = r • x := rfl lemma list.smul_sum {r : α} {l : list β} : r • l.sum = (l.map ((•) r)).sum := (const_smul_hom β r).map_list_sum l end section variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β] lemma multiset.smul_sum {r : α} {s : multiset β} : r • s.sum = (s.map ((•) r)).sum := (const_smul_hom β r).map_multiset_sum s lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} : r • ∑ x in s, f x = ∑ x in s, r • f x := (const_smul_hom β r).map_sum f s end section variables [monoid α] [add_group β] [distrib_mul_action α β] @[simp] theorem smul_neg (r : α) (x : β) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end
b6b186b85cf43933928ee1b6da62a2eec4d85b8a
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/library/algebra/ordered_field.lean
d89bf112fcbc574674efb02091c01be9b19e12c0
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,360
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis -/ import algebra.ordered_ring algebra.field open eq eq.ops structure linear_ordered_field [class] (A : Type) extends linear_ordered_ring A, field A section linear_ordered_field variable {A : Type} variables [s : linear_ordered_field A] {a b c d : A} include s -- helpers for following theorem mul_zero_lt_mul_inv_of_pos (H : 0 < a) : a * 0 < a * (1 / a) := calc a * 0 = 0 : mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : mul_inv_cancel (ne.symm (ne_of_lt H)) ... = a * (1 / a) : inv_eq_one_div theorem mul_zero_lt_mul_inv_of_neg (H : a < 0) : a * 0 < a * (1 / a) := calc a * 0 = 0 : mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : mul_inv_cancel (ne_of_lt H) ... = a * (1 / a) : inv_eq_one_div theorem one_div_pos_of_pos (H : 0 < a) : 0 < 1 / a := lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos H) (le_of_lt H) theorem one_div_neg_of_neg (H : a < 0) : 1 / a < 0 := gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg H) (le_of_lt H) theorem le_mul_of_ge_one_right (Hb : b ≥ 0) (H : a ≥ 1) : b ≤ b * a := mul_one _ ▸ (mul_le_mul_of_nonneg_left H Hb) theorem lt_mul_of_gt_one_right (Hb : b > 0) (H : a > 1) : b < b * a := mul_one _ ▸ (mul_lt_mul_of_pos_left H Hb) theorem one_le_div_iff_le (a : A) {b : A} (Hb : b > 0) : 1 ≤ a / b ↔ b ≤ a := have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb), iff.intro (assume H : 1 ≤ a / b, calc b = b : refl ... ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt Hb) H ... = a : mul_div_cancel' Hb') (assume H : b ≤ a, have Hbinv : 1 / b > 0, from one_div_pos_of_pos Hb, calc 1 = b * (1 / b) : mul_one_div_cancel Hb' ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt Hbinv) ... = a / b : div_eq_mul_one_div) theorem le_of_one_le_div (Hb : b > 0) (H : 1 ≤ a / b) : b ≤ a := (iff.mp (!one_le_div_iff_le Hb)) H theorem one_le_div_of_le (Hb : b > 0) (H : b ≤ a) : 1 ≤ a / b := (iff.mpr (!one_le_div_iff_le Hb)) H theorem one_lt_div_iff_lt (a : A) {b : A} (Hb : b > 0) : 1 < a / b ↔ b < a := have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb), iff.intro (assume H : 1 < a / b, calc b < b * (a / b) : lt_mul_of_gt_one_right Hb H ... = a : mul_div_cancel' Hb') (assume H : b < a, have Hbinv : 1 / b > 0, from one_div_pos_of_pos Hb, calc 1 = b * (1 / b) : mul_one_div_cancel Hb' ... < a * (1 / b) : mul_lt_mul_of_pos_right H Hbinv ... = a / b : div_eq_mul_one_div) theorem lt_of_one_lt_div (Hb : b > 0) (H : 1 < a / b) : b < a := (iff.mp (!one_lt_div_iff_lt Hb)) H theorem one_lt_div_of_lt (Hb : b > 0) (H : b < a) : 1 < a / b := (iff.mpr (!one_lt_div_iff_lt Hb)) H theorem exists_lt (a : A) : ∃ x, x < a := have H : a - 1 < a, from add_lt_of_le_of_neg (le.refl _) zero_gt_neg_one, exists.intro _ H theorem exists_gt (a : A) : ∃ x, x > a := have H : a + 1 > a, from lt_add_of_le_of_pos (le.refl _) zero_lt_one, exists.intro _ H -- the following theorems amount to four iffs, for <, ≤, ≥, >. theorem mul_le_of_le_div (Hc : 0 < c) (H : a ≤ b / c) : a * c ≤ b := !div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_le_mul_of_nonneg_right H (le_of_lt Hc) theorem le_div_of_mul_le (Hc : 0 < c) (H : a * c ≤ b) : a ≤ b / c := calc a = a * c * (1 / c) : !mul_mul_div (ne.symm (ne_of_lt Hc)) ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hc)) ... = b / c : div_eq_mul_one_div theorem mul_lt_of_lt_div (Hc : 0 < c) (H : a < b / c) : a * c < b := !div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_lt_mul_of_pos_right H Hc theorem lt_div_of_mul_lt (Hc : 0 < c) (H : a * c < b) : a < b / c := calc a = a * c * (1 / c) : !mul_mul_div (ne.symm (ne_of_lt Hc)) ... < b * (1 / c) : mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc) ... = b / c : div_eq_mul_one_div theorem mul_le_of_div_le_of_neg (Hc : c < 0) (H : b / c ≤ a) : a * c ≤ b := !div_mul_cancel (ne_of_lt Hc) ▸ mul_le_mul_of_nonpos_right H (le_of_lt Hc) theorem div_le_of_mul_le_of_neg (Hc : c < 0) (H : a * c ≤ b) : b / c ≤ a := calc a = a * c * (1 / c) : !mul_mul_div (ne_of_lt Hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right H (le_of_lt (one_div_neg_of_neg Hc)) ... = b / c : div_eq_mul_one_div theorem mul_lt_of_gt_div_of_neg (Hc : c < 0) (H : a > b / c) : a * c < b := !div_mul_cancel (ne_of_lt Hc) ▸ mul_lt_mul_of_neg_right H Hc theorem div_lt_of_mul_lt_of_pos (Hc : c > 0) (H : b < a * c) : b / c < a := calc a = a * c * (1 / c) : !mul_mul_div (ne_of_gt Hc) ... > b * (1 / c) : mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc) ... = b / c : div_eq_mul_one_div theorem div_lt_of_mul_gt_of_neg (Hc : c < 0) (H : a * c < b) : b / c < a := calc a = a * c * (1 / c) : !mul_mul_div (ne_of_lt Hc) ... > b * (1 / c) : mul_lt_mul_of_neg_right H (one_div_neg_of_neg Hc) ... = b / c : div_eq_mul_one_div theorem div_le_of_le_mul (Hb : b > 0) (H : a ≤ b * c) : a / b ≤ c := calc a / b = a * (1 / b) : div_eq_mul_one_div ... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hb)) ... = (b * c) / b : div_eq_mul_one_div ... = c : mul_div_cancel_left (ne.symm (ne_of_lt Hb)) theorem le_mul_of_div_le (Hc : c > 0) (H : a / c ≤ b) : a ≤ b * c := calc a = a / c * c : !div_mul_cancel (ne.symm (ne_of_lt Hc)) ... ≤ b * c : mul_le_mul_of_nonneg_right H (le_of_lt Hc) -- following these in the isabelle file, there are 8 biconditionals for the above with - signs -- skipping for now theorem mul_sub_mul_div_mul_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c < b / d) : (a * d - b * c) / (c * d) < 0 := have H1 : a / c - b / d < 0, from calc a / c - b / d < b / d - b / d : sub_lt_sub_right H ... = 0 : sub_self, calc 0 > a / c - b / d : H1 ... = (a * d - c * b) / (c * d) : !div_sub_div Hc Hd ... = (a * d - b * c) / (c * d) : mul.comm theorem mul_sub_mul_div_mul_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c ≤ b / d) : (a * d - b * c) / (c * d) ≤ 0 := have H1 : a / c - b / d ≤ 0, from calc a / c - b / d ≤ b / d - b / d : sub_le_sub_right H ... = 0 : sub_self, calc 0 ≥ a / c - b / d : H1 ... = (a * d - c * b) / (c * d) : !div_sub_div Hc Hd ... = (a * d - b * c) / (c * d) : mul.comm theorem div_lt_div_of_mul_sub_mul_div_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : (a * d - b * c) / (c * d) < 0) : a / c < b / d := assert H1 : (a * d - c * b) / (c * d) < 0, by rewrite [mul.comm c b]; exact H, assert H2 : a / c - b / d < 0, by rewrite [!div_sub_div Hc Hd]; exact H1, assert H3 : a / c - b / d + b / d < 0 + b / d, from add_lt_add_right H2 _, begin rewrite [zero_add at H3, sub_eq_add_neg at H3, neg_add_cancel_right at H3], exact H3 end theorem div_le_div_of_mul_sub_mul_div_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d := assert H1 : (a * d - c * b) / (c * d) ≤ 0, by rewrite [mul.comm c b]; exact H, assert H2 : a / c - b / d ≤ 0, by rewrite [!div_sub_div Hc Hd]; exact H1, assert H3 : a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right H2 _, begin rewrite [zero_add at H3, sub_eq_add_neg at H3, neg_add_cancel_right at H3], exact H3 end theorem div_pos_of_pos_of_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a / b := begin rewrite div_eq_mul_one_div, apply mul_pos, exact Ha, apply one_div_pos_of_pos, exact Hb end theorem div_nonneg_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 ≤ a / b := begin rewrite div_eq_mul_one_div, apply mul_nonneg, exact Ha, apply le_of_lt, apply one_div_pos_of_pos, exact Hb end theorem div_neg_of_neg_of_pos (Ha : a < 0) (Hb : 0 < b) : a / b < 0:= begin rewrite div_eq_mul_one_div, apply mul_neg_of_neg_of_pos, exact Ha, apply one_div_pos_of_pos, exact Hb end theorem div_nonpos_of_nonpos_of_pos (Ha : a ≤ 0) (Hb : 0 < b) : a / b ≤ 0 := begin rewrite div_eq_mul_one_div, apply mul_nonpos_of_nonpos_of_nonneg, exact Ha, apply le_of_lt, apply one_div_pos_of_pos, exact Hb end theorem div_neg_of_pos_of_neg (Ha : 0 < a) (Hb : b < 0) : a / b < 0 := begin rewrite div_eq_mul_one_div, apply mul_neg_of_pos_of_neg, exact Ha, apply one_div_neg_of_neg, exact Hb end theorem div_nonpos_of_nonneg_of_neg (Ha : 0 ≤ a) (Hb : b < 0) : a / b ≤ 0 := begin rewrite div_eq_mul_one_div, apply mul_nonpos_of_nonneg_of_nonpos, exact Ha, apply le_of_lt, apply one_div_neg_of_neg, exact Hb end theorem div_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a / b := begin rewrite div_eq_mul_one_div, apply mul_pos_of_neg_of_neg, exact Ha, apply one_div_neg_of_neg, exact Hb end theorem div_nonneg_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : 0 ≤ a / b := begin rewrite div_eq_mul_one_div, apply mul_nonneg_of_nonpos_of_nonpos, exact Ha, apply le_of_lt, apply one_div_neg_of_neg, exact Hb end theorem div_lt_div_of_lt_of_pos (H : a < b) (Hc : 0 < c) : a / c < b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc) end theorem div_le_div_of_le_of_pos (H : a ≤ b) (Hc : 0 < c) : a / c ≤ b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hc)) end theorem div_lt_div_of_lt_of_neg (H : b < a) (Hc : c < 0) : a / c < b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_lt_mul_of_neg_right H (one_div_neg_of_neg Hc) end theorem div_le_div_of_le_of_neg (H : b ≤ a) (Hc : c < 0) : a / c ≤ b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_le_mul_of_nonpos_right H (le_of_lt (one_div_neg_of_neg Hc)) end theorem two_pos : (1 : A) + 1 > 0 := add_pos zero_lt_one zero_lt_one theorem one_add_one_ne_zero : 1 + 1 ≠ (0:A) := ne.symm (ne_of_lt two_pos) theorem two_ne_zero : 2 ≠ (0:A) := by unfold bit0; apply one_add_one_ne_zero theorem add_halves (a : A) : a / 2 + a / 2 = a := calc a / 2 + a / 2 = (a + a) / 2 : by rewrite div_add_div_same ... = (a * 1 + a * 1) / 2 : by rewrite mul_one ... = (a * (1 + 1)) / 2 : by rewrite left_distrib ... = (a * 2) / 2 : by rewrite one_add_one_eq_two ... = a : by rewrite [@mul_div_cancel A _ _ _ two_ne_zero] theorem sub_self_div_two (a : A) : a - a / 2 = a / 2 := by rewrite [-{a}add_halves at {1}, add_sub_cancel] theorem add_midpoint {a b : A} (H : a < b) : a + (b - a) / 2 < b := begin rewrite [-div_sub_div_same, sub_eq_add_neg, {b / 2 + _}add.comm, -add.assoc, -sub_eq_add_neg], apply add_lt_of_lt_sub_right, rewrite *sub_self_div_two, apply div_lt_div_of_lt_of_pos H two_pos end theorem div_two_sub_self (a : A) : a / 2 - a = - (a / 2) := by rewrite [-{a}add_halves at {2}, sub_add_eq_sub_sub, sub_self, zero_sub] theorem add_self_div_two (a : A) : (a + a) / 2 = a := symm (iff.mpr (!eq_div_iff_mul_eq (ne_of_gt (add_pos zero_lt_one zero_lt_one))) (by krewrite [left_distrib, *mul_one])) theorem two_gt_one : (2:A) > 1 := calc (2:A) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one ... = 1 : add_zero theorem two_ge_one : (2:A) ≥ 1 := le_of_lt two_gt_one theorem four_pos : (4 : A) > 0 := add_pos two_pos two_pos theorem mul_le_mul_of_mul_div_le (H : a * (b / c) ≤ d) (Hc : c > 0) : b * a ≤ d * c := begin rewrite [-mul_div_assoc at H, mul.comm b], apply le_mul_of_div_le Hc H end theorem div_two_lt_of_pos (H : a > 0) : a / (1 + 1) < a := have Ha : a / (1 + 1) > 0, from div_pos_of_pos_of_pos H (add_pos zero_lt_one zero_lt_one), calc a / (1 + 1) < a / (1 + 1) + a / (1 + 1) : lt_add_of_pos_left Ha ... = a : add_halves theorem div_mul_le_div_mul_of_div_le_div_pos {e : A} (Hb : b ≠ 0) (Hd : d ≠ 0) (H : a / b ≤ c / d) (He : e > 0) : a / (b * e) ≤ c / (d * e) := begin rewrite [!field.div_mul_eq_div_mul_one_div Hb (ne_of_gt He), !field.div_mul_eq_div_mul_one_div Hd (ne_of_gt He)], apply mul_le_mul_of_nonneg_right H, apply le_of_lt, apply one_div_pos_of_pos He end theorem exists_add_lt_and_pos_of_lt (H : b < a) : ∃ c : A, b + c < a ∧ c > 0 := exists.intro ((a - b) / (1 + 1)) (and.intro (assert H2 : a + a > (b + b) + (a - b), from calc a + a > b + a : add_lt_add_right H ... = b + a + b - b : add_sub_cancel ... = b + b + a - b : add.right_comm ... = (b + b) + (a - b) : add_sub, assert H3 : (a + a) / 2 > ((b + b) + (a - b)) / 2, from div_lt_div_of_lt_of_pos H2 two_pos, by rewrite [one_add_one_eq_two, sub_eq_add_neg, add_self_div_two at H3, -div_add_div_same at H3, add_self_div_two at H3]; exact H3) (div_pos_of_pos_of_pos (iff.mpr !sub_pos_iff_lt H) two_pos)) theorem ge_of_forall_ge_sub {a b : A} (H : ∀ ε : A, ε > 0 → a ≥ b - ε) : a ≥ b := begin apply le_of_not_gt, intro Hb, cases exists_add_lt_and_pos_of_lt Hb with [c, Hc], let Hc' := H c (and.right Hc), apply (not_le_of_gt (and.left Hc)) (iff.mpr !le_add_iff_sub_right_le Hc') end end linear_ordered_field structure discrete_linear_ordered_field [class] (A : Type) extends linear_ordered_field A, decidable_linear_ordered_comm_ring A := (inv_zero : inv zero = zero) section discrete_linear_ordered_field variable {A : Type} variables [s : discrete_linear_ordered_field A] {a b c : A} include s definition dec_eq_of_dec_lt : ∀ x y : A, decidable (x = y) := take x y, decidable.by_cases (assume H : x < y, decidable.inr (ne_of_lt H)) (assume H : ¬ x < y, decidable.by_cases (assume H' : y < x, decidable.inr (ne.symm (ne_of_lt H'))) (assume H' : ¬ y < x, decidable.inl (le.antisymm (le_of_not_gt H') (le_of_not_gt H)))) definition discrete_linear_ordered_field.to_discrete_field [trans_instance] [reducible] : discrete_field A := ⦃ discrete_field, s, has_decidable_eq := dec_eq_of_dec_lt⦄ theorem pos_of_one_div_pos (H : 0 < 1 / a) : 0 < a := have H1 : 0 < 1 / (1 / a), from one_div_pos_of_pos H, have H2 : 1 / a ≠ 0, from (assume H3 : 1 / a = 0, have H4 : 1 / (1 / a) = 0, from H3⁻¹ ▸ !div_zero, absurd H4 (ne.symm (ne_of_lt H1))), (division_ring.one_div_one_div (ne_zero_of_one_div_ne_zero H2)) ▸ H1 theorem neg_of_one_div_neg (H : 1 / a < 0) : a < 0 := have H1 : 0 < - (1 / a), from neg_pos_of_neg H, have Ha : a ≠ 0, from ne_zero_of_one_div_ne_zero (ne_of_lt H), have H2 : 0 < 1 / (-a), from (division_ring.one_div_neg_eq_neg_one_div Ha)⁻¹ ▸ H1, have H3 : 0 < -a, from pos_of_one_div_pos H2, neg_of_neg_pos H3 theorem le_of_one_div_le_one_div (H : 0 < a) (Hl : 1 / a ≤ 1 / b) : b ≤ a := have Hb : 0 < b, from pos_of_one_div_pos (calc 0 < 1 / a : one_div_pos_of_pos H ... ≤ 1 / b : Hl), have H' : 1 ≤ a / b, from (calc 1 = a / a : div_self (ne.symm (ne_of_lt H)) ... = a * (1 / a) : div_eq_mul_one_div ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_left Hl (le_of_lt H) ... = a / b : div_eq_mul_one_div ), le_of_one_le_div Hb H' theorem le_of_one_div_le_one_div_of_neg (H : b < 0) (Hl : 1 / a ≤ 1 / b) : b ≤ a := assert Ha : a ≠ 0, from ne_of_lt (neg_of_one_div_neg (calc 1 / a ≤ 1 / b : Hl ... < 0 : one_div_neg_of_neg H)), have H' : -b > 0, from neg_pos_of_neg H, have Hl' : - (1 / b) ≤ - (1 / a), from neg_le_neg Hl, have Hl'' : 1 / - b ≤ 1 / - a, from calc 1 / -b = - (1 / b) : by rewrite [division_ring.one_div_neg_eq_neg_one_div (ne_of_lt H)] ... ≤ - (1 / a) : Hl' ... = 1 / -a : by rewrite [division_ring.one_div_neg_eq_neg_one_div Ha], le_of_neg_le_neg (le_of_one_div_le_one_div H' Hl'') theorem lt_of_one_div_lt_one_div (H : 0 < a) (Hl : 1 / a < 1 / b) : b < a := have Hb : 0 < b, from pos_of_one_div_pos (calc 0 < 1 / a : one_div_pos_of_pos H ... < 1 / b : Hl), have H : 1 < a / b, from (calc 1 = a / a : div_self (ne.symm (ne_of_lt H)) ... = a * (1 / a) : div_eq_mul_one_div ... < a * (1 / b) : mul_lt_mul_of_pos_left Hl H ... = a / b : div_eq_mul_one_div), lt_of_one_lt_div Hb H theorem lt_of_one_div_lt_one_div_of_neg (H : b < 0) (Hl : 1 / a < 1 / b) : b < a := have H1 : b ≤ a, from le_of_one_div_le_one_div_of_neg H (le_of_lt Hl), have Hn : b ≠ a, from (assume Hn' : b = a, have Hl' : 1 / a = 1 / b, from Hn' ▸ refl _, absurd Hl' (ne_of_lt Hl)), lt_of_le_of_ne H1 Hn theorem one_div_lt_one_div_of_lt (Ha : 0 < a) (H : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume H', absurd H (not_lt_of_ge (le_of_one_div_le_one_div Ha H'))) theorem one_div_le_one_div_of_le (Ha : 0 < a) (H : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume H', absurd H (not_le_of_gt (lt_of_one_div_lt_one_div Ha H'))) theorem one_div_lt_one_div_of_lt_of_neg (Hb : b < 0) (H : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume H', absurd H (not_lt_of_ge (le_of_one_div_le_one_div_of_neg Hb H'))) theorem one_div_le_one_div_of_le_of_neg (Hb : b < 0) (H : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume H', absurd H (not_le_of_gt (lt_of_one_div_lt_one_div_of_neg Hb H'))) theorem one_div_le_of_one_div_le_of_pos (Ha : a > 0) (H : 1 / a ≤ b) : 1 / b ≤ a := begin rewrite -(one_div_one_div a), apply one_div_le_one_div_of_le, apply one_div_pos_of_pos, repeat assumption end theorem one_div_le_of_one_div_le_of_neg (Ha : b < 0) (H : 1 / a ≤ b) : 1 / b ≤ a := begin rewrite -(one_div_one_div a), apply one_div_le_one_div_of_le_of_neg, repeat assumption end theorem one_lt_one_div (H1 : 0 < a) (H2 : a < 1) : 1 < 1 / a := one_div_one ▸ one_div_lt_one_div_of_lt H1 H2 theorem one_le_one_div (H1 : 0 < a) (H2 : a ≤ 1) : 1 ≤ 1 / a := one_div_one ▸ one_div_le_one_div_of_le H1 H2 theorem one_div_lt_neg_one (H1 : a < 0) (H2 : -1 < a) : 1 / a < -1 := one_div_neg_one_eq_neg_one ▸ one_div_lt_one_div_of_lt_of_neg H1 H2 theorem one_div_le_neg_one (H1 : a < 0) (H2 : -1 ≤ a) : 1 / a ≤ -1 := one_div_neg_one_eq_neg_one ▸ one_div_le_one_div_of_le_of_neg H1 H2 theorem div_lt_div_of_pos_of_lt_of_pos (Hb : 0 < b) (H : b < a) (Hc : 0 < c) : c / a < c / b := begin apply iff.mp !sub_neg_iff_lt, rewrite [div_eq_mul_one_div, {c / b}div_eq_mul_one_div, -mul_sub_left_distrib], apply mul_neg_of_pos_of_neg, exact Hc, apply iff.mpr !sub_neg_iff_lt, apply one_div_lt_one_div_of_lt, repeat assumption end theorem div_mul_le_div_mul_of_div_le_div_pos' {d e : A} (H : a / b ≤ c / d) (He : e > 0) : a / (b * e) ≤ c / (d * e) := begin rewrite [2 div_mul_eq_div_mul_one_div], apply mul_le_mul_of_nonneg_right H, apply le_of_lt, apply one_div_pos_of_pos He end theorem abs_div (a b : A) : abs (a / b) = abs a / abs b := decidable.by_cases (suppose b = 0, by rewrite [this, abs_zero, *div_zero, abs_zero]) (suppose b ≠ 0, have abs b ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H), eq_div_of_mul_eq _ _ this (show abs (a / b) * abs b = abs a, by rewrite [-abs_mul, div_mul_cancel _ `b ≠ 0`])) theorem abs_one_div (a : A) : abs (1 / a) = 1 / abs a := by rewrite [abs_div, abs_of_nonneg (zero_le_one : 1 ≥ (0 : A))] theorem sign_eq_div_abs (a : A) : sign a = a / (abs a) := decidable.by_cases (suppose a = 0, by subst a; rewrite [zero_div, sign_zero]) (suppose a ≠ 0, have abs a ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H), !eq_div_of_mul_eq this !eq_sign_mul_abs⁻¹) theorem add_quarters (a : A) : a / 4 + a / 4 = a / 2 := have H4 [visible] : (4 : A) = 2 * 2, by norm_num, calc a / 4 + a / 4 = (a + a) / (2 * 2) : by rewrite [-H4, div_add_div_same] ... = (a * 1 + a * 1) / (2 * 2) : by rewrite mul_one ... = (a * (1 + 1)) / (2 * 2) : by rewrite left_distrib ... = (a * 2) / (2 * 2) : rfl ... = ((a * 2) / 2) / 2 : by rewrite -div_div_eq_div_mul ... = a / 2 : by rewrite (mul_div_cancel a two_ne_zero) lemma div_two_add_div_four_lt {a : A} (H : a > 0) : a / 2 + a / 4 < a := begin replace (4 : A) with (2 : A) + 2, have Hne : (2 + 2 : A) ≠ 0, from ne_of_gt four_pos, krewrite (div_add_div _ _ two_ne_zero Hne), have Hnum : (2 + 2 + 2) / (2 * (2 + 2)) = (3 : A) / 4, by norm_num, rewrite [{2 * a}mul.comm, -left_distrib, mul_div_assoc, -mul_one a at {2}], krewrite Hnum, apply mul_lt_mul_of_pos_left, apply div_lt_of_mul_lt_of_pos, apply four_pos, rewrite one_mul, replace (3 : A) with (2 : A) + 1, replace (4 : A) with (2 : A) + 2, apply add_lt_add_left, apply two_gt_one, exact H end end discrete_linear_ordered_field
fd765b8f699c7c44c27a75ec625239acf78affd3
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Prelude.lean
90f42feaf6f601e19bdb151d0d15d2244aaf2ee6
[ "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
78,823
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude universe u v w @[inline] def id {α : Sort u} (a : α) : α := a @[inline] def Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) @[inline] def Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a set_option checkBinderAnnotations false in @[reducible] def inferInstance {α : Sort u} [i : α] : α := i set_option checkBinderAnnotations false in @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type set_option bootstrap.inductiveCheckResultingUniverse false in inductive PEmpty : Sort u where def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a @[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] protected def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b theorem Or.intro_left (b : Prop) (h : a) : Or a b := Or.inl h theorem Or.intro_right (a : Prop) (h : b) : Or a b := Or.inr h theorem Or.elim {c : Prop} (h : Or a b) (left : a → c) (right : b → c) : c := match h with | Or.inl h => left h | Or.inr h => right h inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eq_false_of_ne_true : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eq_true_of_ne_false : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem ne_false_of_eq_true : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem ne_true_of_eq_false : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) attribute [nospecialize] Inhabited constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary deriving instance Inhabited for Bool /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.up_down {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.down_up {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.up_down {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.down_up {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decide_eq_true : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decide_eq_false : [s : Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse h, _ => rfl theorem of_decide_eq_true [s : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (ne_true_of_eq_false (decide_eq_false h₁)) theorem of_decide_eq_false [s : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) s with | isTrue h₁ => absurd h (ne_false_of_eq_true (decide_eq_true h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class LE (α : Type u) where le : α → α → Prop class LT (α : Type u) where lt : α → α → Prop @[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a @[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a @[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α := ite (LT.lt b a) a b @[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α := ite (LE.le a b) a b /-- Transitive chaining of proofs, used e.g. by `calc`. -/ class Trans (r : α → β → Prop) (s : β → γ → Prop) (t : outParam (α → γ → Prop)) where trans : r a b → s b c → t a c export Trans (trans) instance (r : α → γ → Prop) : Trans Eq r r where trans heq h' := heq ▸ h' instance (r : α → β → Prop) : Trans r Eq r where trans h' heq := heq ▸ h' class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → (Unit → β) → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → (Unit → β) → γ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAnd : α → β → γ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where hXor : α → β → γ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOr : α → β → γ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftLeft : α → β → γ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftRight : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) (β : Type v) where pow : α → β → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → (Unit → α) → α class AndThen (α : Type u) where andThen : α → (Unit → α) → α class AndOp (α : Type u) where and : α → α → α class Xor (α : Type u) where xor : α → α → α class OrOp (α : Type u) where or : α → α → α class Complement (α : Type u) where complement : α → α class ShiftLeft (α : Type u) where shiftLeft : α → α → α class ShiftRight (α : Type u) where shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α β] : HPow α β α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eq_of_beq_eq_true : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : Eq (beq n m) true := h have : Eq n m := eq_of_beq_eq_true this this ▸ rfl theorem Nat.ne_of_beq_eq_false : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have : Eq (beq n m) false := h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (ne_of_beq_eq_false this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eq_of_beq_eq_true h) | false => isFalse (ne_of_beq_eq_false h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected inductive Nat.le (n : Nat) : Nat → Prop | refl : Nat.le n n | step {m} : Nat.le n m → Nat.le n (succ m) instance : LE Nat where le := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : LT Nat where lt := Nat.lt theorem Nat.not_succ_le_zero : ∀ (n : Nat), LE.le (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) := not_succ_le_zero n theorem Nat.zero_le : (n : Nat) → LE.le 0 n | zero => Nat.le.refl | succ n => Nat.le.step (zero_le n) theorem Nat.succ_le_succ : LE.le n m → LE.le (succ n) (succ m) | Nat.le.refl => Nat.le.refl | Nat.le.step h => Nat.le.step (succ_le_succ h) theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) := succ_le_succ (zero_le n) theorem Nat.le_step (h : LE.le n m) : LE.le n (succ m) := Nat.le.step h protected theorem Nat.le_trans {n m k : Nat} : LE.le n m → LE.le m k → LE.le n k | h, Nat.le.refl => h | h₁, Nat.le.step h₂ => Nat.le.step (Nat.le_trans h₁ h₂) protected theorem Nat.lt_trans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k := Nat.le_trans (le_step h₁) theorem Nat.le_succ (n : Nat) : LE.le n (succ n) := Nat.le.step Nat.le.refl theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) := Nat.le_trans h (le_succ m) protected theorem Nat.le_refl (n : Nat) : LE.le n n := Nat.le.refl theorem Nat.succ_pos (n : Nat) : LT.lt 0 (succ n) := zero_lt_succ n set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a theorem Nat.pred_le_pred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m) | _, _, Nat.le.refl => Nat.le.refl | 0, succ m, Nat.le.step h => h | succ n, succ m, Nat.le.step h => Nat.le_trans (le_succ _) h theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m := pred_le_pred theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) → LE.le m n := le_of_succ_le_succ protected theorem Nat.eq_or_lt_of_le : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (Nat.succ_le_succ (Nat.zero_le _)) | succ n, zero, h => absurd h (not_succ_le_zero _) | succ n, succ m, h => have : LE.le n m := Nat.le_of_succ_le_succ h match Nat.eq_or_lt_of_le this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succ_le_succ h) protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) := match m with | zero => Or.inr (zero_le n) | succ m => match Nat.lt_or_ge n m with | Or.inl h => Or.inl (le_succ_of_le h) | Or.inr h => match Nat.eq_or_lt_of_le h with | Or.inl h1 => Or.inl (h1 ▸ Nat.le_refl _) | Or.inr h1 => Or.inr h1 theorem Nat.not_succ_le_self : (n : Nat) → Not (LE.le (succ n) n) | 0 => not_succ_le_zero _ | succ n => fun h => absurd (le_of_succ_le_succ h) (not_succ_le_self n) protected theorem Nat.lt_irrefl (n : Nat) : Not (LT.lt n n) := Nat.not_succ_le_self n protected theorem Nat.lt_of_le_of_lt {n m k : Nat} (h₁ : LE.le n m) (h₂ : LT.lt m k) : LT.lt n k := Nat.le_trans (Nat.succ_le_succ h₁) h₂ protected theorem Nat.le_antisymm {n m : Nat} (h₁ : LE.le n m) (h₂ : LE.le m n) : Eq n m := match h₁ with | Nat.le.refl => rfl | Nat.le.step h => absurd (Nat.lt_of_le_of_lt h h₂) (Nat.lt_irrefl n) protected theorem Nat.lt_of_le_of_ne {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m := match Nat.lt_or_ge n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.le_antisymm h₁ h₃) h₂ theorem Nat.le_of_ble_eq_true (h : Eq (Nat.ble n m) true) : LE.le n m := match n, m with | 0, _ => Nat.zero_le _ | succ _, succ _ => Nat.succ_le_succ (le_of_ble_eq_true h) theorem Nat.ble_self_eq_true : (n : Nat) → Eq (Nat.ble n n) true | 0 => rfl | succ n => ble_self_eq_true n theorem Nat.ble_succ_eq_true : {n m : Nat} → Eq (Nat.ble n m) true → Eq (Nat.ble n (succ m)) true | 0, _, _ => rfl | succ n, succ m, h => ble_succ_eq_true (n := n) h theorem Nat.ble_eq_true_of_le (h : LE.le n m) : Eq (Nat.ble n m) true := match h with | Nat.le.refl => Nat.ble_self_eq_true n | Nat.le.step h => Nat.ble_succ_eq_true (ble_eq_true_of_le h) theorem Nat.not_le_of_not_ble_eq_true (h : Not (Eq (Nat.ble n m) true)) : Not (LE.le n m) := fun h' => absurd (Nat.ble_eq_true_of_le h') h @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) := dite (Eq (Nat.ble n m) true) (fun h => isTrue (Nat.le_of_ble_eq_true h)) (fun h => isFalse (Nat.not_le_of_not_ble_eq_true h)) @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) := decLe (succ n) m set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : LT.lt val n theorem Fin.eq_of_val_eq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (val_eq_of_eq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eq_of_val_eq h) | isFalse h => isFalse (Fin.ne_of_val_ne h) instance {n} : LT (Fin n) where lt a b := LT.lt a.val b.val instance {n} : LE (Fin n) where le a b := LE.le a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_uint8_dec_eq"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_uint16_dec_eq"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern "lean_uint32_dec_eq"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : LT UInt32 where lt a b := LT.lt a.val b.val instance : LE UInt32 where le a b := LE.le a.val b.val set_option bootstrap.genMatcherCode false in @[extern "lean_uint32_dec_lt"] def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m)) set_option bootstrap.genMatcherCode false in @[extern "lean_uint32_dec_le"] def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m)) instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_uint64_dec_eq"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) def USize.size : Nat := hPow 2 System.Platform.numBits theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBits_eq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_usize_dec_eq"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usize_size_eq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := { val := { val := n isLt := match USize.size, usize_size_eq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.lt_trans h (by decide) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size := match h with | Or.inl h => Nat.lt_trans h (by decide) | Or.inr ⟨_, h⟩ => Nat.lt_trans h (by decide) @[extern "lean_uint32_of_nat"] def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := isValidChar_UInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eq_of_val_eq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.val_eq_of_eq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (val_eq_of_eq h') h theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eq_of_val_eq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eq_of_val_eq h) | isFalse h => isFalse (Char.ne_of_val_ne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LE.le v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none @[macroInline] def Option.getD : Option α → α → α | some x, _ => x | none, e => e inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.length : List α → Nat | nil => 0 | cons a as => HAdd.hAdd (length as) 1 def List.lengthTRAux : List α → Nat → Nat | nil, n => n | cons a as, n => lengthTRAux as (Nat.succ n) def List.lengthTR (as : List α) : Nat := lengthTRAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := rfl def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → LT.lt i as.length → α | nil, i, h => absurd h (Nat.not_lt_zero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have : LT.lt i.succ as.length.succ := length_cons .. ▸ h get as i (Nat.le_of_succ_le_succ this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos instance : Inhabited Substring where default := ⟨"", 0, 0⟩ @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s startPos := 0 stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panicCore {α : Type u} [Inhabited α] (msg : String) : α /-- This is workaround for `panic` occurring in monadic code. See issue #695. The `panicCore` definition cannot be specialized since it is an extern. When `panic` occurs in monadic code, the `Inhabited α` parameter depends on a `[inst : Monad m]` instance. The `inst` parameter will not be eliminated during specialization if it occurs inside of a binder (to avoid work duplication), and will prevent the the actual monad from being "copied" to the code being specialized. When we reimplement the specializer, we may consider copying `inst` if it also occurs outside binders or if it is an instance. -/ @[noinline, neverExtract] def panic {α : Type u} [Inhabited α] (msg : String) : α := panicCore msg /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (LT.lt j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | nil, r => r | cons a as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | nil => 0 | cons _ as => as.redLength.succ @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α β : Type u} → f α → (Unit → f β) → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {α β : Type u} → f α → (Unit → f β) → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) fun _ => y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y (x ()) seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a) seqRight x y := bind x fun _ => y () instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (LT.lt j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orElse [MonadExcept ε m] {α : Type v} (t₁ : m α) (t₂ : Unit → m α) : m α := tryCatch t₁ fun _ => t₂ () instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orElse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ : EStateM ε σ α) (x₂ : Unit → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ () (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ α) (y : Unit → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y () s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Sort u) where hash : α → UInt64 export Hashable (hash) @[extern "lean_uint64_to_usize"] constant UInt64.toUSize (u : UInt64) : USize @[extern "lean_usize_to_uint64"] constant USize.toUInt64 (u : USize) : UInt64 @[extern "lean_uint64_mix_hash"] constant mixHash (u₁ u₂ : UInt64) : UInt64 @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : UInt64 instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → UInt64 → Name | num : Name → Nat → UInt64 → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → UInt64 | Name.anonymous => UInt64.ofNatCore 1723 (by decide) | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide)))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ /-- Syntax objects used by the parser, macro expander, delaborator, etc. -/ inductive Syntax where | missing : Syntax | /-- Node in the syntax tree. The `info` field is used by the delaborator to store the position of the subexpression corresponding to this node. The parser sets the `info` field to `none`. (Remark: the `node` constructor did not have an `info` field in previous versions. This caused a bug in the interactive widgets, where the popup for `a + b` was the same as for `a`. The delaborator used to associate subexpressions with pretty-printed syntax by setting the (string) position of the first atom/identifier to the (expression) position of the subexpression. For example, both `a` and `a + b` have the same first identifier, and so their infos got mixed up.) -/ node (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def groupKind : SyntaxNodeKind := `group def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node _ k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node info _ args => Syntax.node info k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ _ args => args.size | _ => 0 def isMissing : Syntax → Bool | Syntax.missing => true | _ => false def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def matchesNull (stx : Syntax) (n : Nat) : Bool := isNodeOf stx nullKind n def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId id) def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node info k _ => node info k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node info k args => node info k (args.setD i arg) | stx => stx /-- Retrieve the left-most node or leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node SourceInfo.none _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | node info _ _ => some info | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node (SourceInfo.original (endPos := pos) ..) .., _ => some pos | node (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom (SourceInfo.fromRef src) val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ private constant MethodsRefPointed : PointedType.{0} private def MethodsRef : Type := MethodsRefPointed.type structure Context where methods : MethodsRef mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception structure State where macroScope : MacroScope traceMsgs : List (Prod Name String) := List.nil deriving Inhabited end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope structure Methods where expandMacro? : Syntax → MacroM (Option Syntax) getCurrNamespace : MacroM Name hasDecl : Name → MacroM Bool resolveNamespace? : Name → MacroM (Option Name) resolveGlobalName : Name → MacroM (List (Prod Name (List String))) deriving Inhabited unsafe def mkMethodsImp (methods : Methods) : MethodsRef := unsafeCast methods @[implementedBy mkMethodsImp] constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val instance : Inhabited MethodsRef where default := mkMethods arbitrary unsafe def getMethodsImp : MacroM Methods := bind read fun ctx => pure (unsafeCast (ctx.methods)) @[implementedBy getMethodsImp] constant getMethods : MacroM Methods /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do (← getMethods).expandMacro? stx /-- Return `true` if the environment contains a declaration with name `declName` -/ def hasDecl (declName : Name) : MacroM Bool := do (← getMethods).hasDecl declName def getCurrNamespace : MacroM Name := do (← getMethods).getCurrNamespace def resolveNamespace? (n : Name) : MacroM (Option Name) := do (← getMethods).resolveNamespace? n def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do (← getMethods).resolveGlobalName n def trace (clsName : Name) (msg : String) : MacroM Unit := do modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs } end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
283ae939dd85c542bf9ab932cac8aea6a3002cb5
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/Server/FileWorker/RequestHandling.lean
965b357c06e9d15be033f0ef65b06c474eb689d0
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,617
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.DeclarationRange import Lean.Data.Json import Lean.Data.Lsp import Lean.Server.FileWorker.Utils import Lean.Server.Requests import Lean.Server.Completion import Lean.Widget.InteractiveGoal namespace Lean.Server.FileWorker open Lsp open RequestM open Snapshots partial def handleCompletion (p : CompletionParams) : RequestM (RequestTask CompletionList) := do let doc ← readDoc let text := doc.meta.text let pos := text.lspPosToUtf8Pos p.position -- dbg_trace ">> handleCompletion invoked {pos}" -- NOTE: use `>=` since the cursor can be *after* the input withWaitFindSnap doc (fun s => s.endPos >= pos) (notFoundX := pure { items := #[], isIncomplete := true }) fun snap => do if let some r ← Completion.find? doc.meta.text pos snap.infoTree then return r return { items := #[ ], isIncomplete := true } open Elab in partial def handleHover (p : HoverParams) : RequestM (RequestTask (Option Hover)) := do let doc ← readDoc let text := doc.meta.text let mkHover (s : String) (f : String.Pos) (t : String.Pos) : Hover := { contents := { kind := MarkupKind.markdown value := s } range? := some { start := text.utf8PosToLspPos f «end» := text.utf8PosToLspPos t } } let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure none) fun snap => do if let some (ci, i) := snap.infoTree.hoverableInfoAt? hoverPos then if let some hoverFmt ← i.fmtHover? ci then return some <| mkHover (toString hoverFmt) i.pos?.get! i.tailPos?.get! return none inductive GoToKind | declaration | definition | type deriving BEq open Elab GoToKind in partial def handleDefinition (kind : GoToKind) (p : TextDocumentPositionParams) : RequestM (RequestTask (Array LocationLink)) := do let rc ← read let doc ← readDoc let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position let locationLinksFromDecl (i : Elab.Info) (n : Name) := do let mod? ← findModuleOf? n let modUri? ← match mod? with | some modName => let modFname? ← rc.srcSearchPath.findWithExt "lean" modName pure <| modFname?.map toFileUri | none => pure <| some doc.meta.uri let ranges? ← findDeclarationRanges? n if let (some ranges, some modUri) := (ranges?, modUri?) then let declRangeToLspRange (r : DeclarationRange) : Lsp.Range := { start := ⟨r.pos.line - 1, r.charUtf16⟩ «end» := ⟨r.endPos.line - 1, r.endCharUtf16⟩ } let ll : LocationLink := { originSelectionRange? := (·.toLspRange text) <$> i.range? targetUri := modUri targetRange := declRangeToLspRange ranges.range targetSelectionRange := declRangeToLspRange ranges.selectionRange } return #[ll] return #[] let locationLinksFromBinder (t : InfoTree) (i : Elab.Info) (id : FVarId) := do if let some i' := t.findInfo? fun | Info.ofTermInfo { isBinder := true, expr := Expr.fvar id' .., .. } => id' == id | _ => false then if let some r := i'.range? then let r := r.toLspRange text let ll : LocationLink := { originSelectionRange? := (·.toLspRange text) <$> i.range? targetUri := p.textDocument.uri targetRange := r targetSelectionRange := r } return #[ll] return #[] withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure #[]) fun snap => do if let some (ci, i) := snap.infoTree.hoverableInfoAt? hoverPos then if let Info.ofTermInfo ti := i then let mut expr := ti.expr if kind == type then expr ← ci.runMetaM i.lctx do Expr.getAppFn (← Meta.instantiateMVars (← Meta.inferType expr)) match expr with | Expr.const n .. => return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n | Expr.fvar id .. => return ← ci.runMetaM i.lctx <| locationLinksFromBinder snap.infoTree i id | _ => pure () if let Info.ofFieldInfo fi := i then if kind == type then let expr ← ci.runMetaM i.lctx do Meta.instantiateMVars (← Meta.inferType fi.val) if let some n := expr.getAppFn.constName? then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n else return ← ci.runMetaM i.lctx <| locationLinksFromDecl i fi.projName -- If other go-tos fail, we try to show the elaborator or parser if let some ei := i.toElabInfo? then if kind == declaration && ci.env.contains ei.stx.getKind then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.stx.getKind if kind == definition && ci.env.contains ei.elaborator then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.elaborator return #[] open RequestM in def getInteractiveGoals (p : Lsp.PlainGoalParams) : RequestM (RequestTask (Option Widget.InteractiveGoals)) := do let doc ← readDoc let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position -- NOTE: use `>=` since the cursor can be *after* the input withWaitFindSnap doc (fun s => s.endPos >= hoverPos) (notFoundX := return none) fun snap => do if let rs@(_ :: _) := snap.infoTree.goalsAt? doc.meta.text hoverPos then let goals ← List.join <$> rs.mapM fun { ctxInfo := ci, tacticInfo := ti, useAfter := useAfter } => let ci := if useAfter then { ci with mctx := ti.mctxAfter } else { ci with mctx := ti.mctxBefore } let goals := if useAfter then ti.goalsAfter else ti.goalsBefore ci.runMetaM {} <| goals.mapM (fun g => Meta.withPPInaccessibleNames (Widget.goalToInteractive g)) return some { goals := goals.toArray } else return none open Elab in partial def handlePlainGoal (p : PlainGoalParams) : RequestM (RequestTask (Option PlainGoal)) := do let t ← getInteractiveGoals p t.map <| Except.map <| Option.map <| fun ⟨goals⟩ => if goals.isEmpty then { goals := #[], rendered := "no goals" } else let goalStrs := goals.map (toString ·.pretty) let goalBlocks := goalStrs.map fun goal => s!"```lean {goal} ```" let md := String.intercalate "\n---\n" goalBlocks.toList { goals := goalStrs, rendered := md } partial def getInteractiveTermGoal (p : Lsp.PlainTermGoalParams) : RequestM (RequestTask (Option Widget.InteractiveTermGoal)) := do let doc ← readDoc let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure none) fun snap => do if let some (ci, i@(Elab.Info.ofTermInfo ti)) := snap.infoTree.termGoalAt? hoverPos then let ty ← ci.runMetaM i.lctx do Meta.instantiateMVars <| ti.expectedType?.getD (← Meta.inferType ti.expr) -- for binders, hide the last hypothesis (the binder itself) let lctx' := if ti.isBinder then i.lctx.pop else i.lctx let goal ← ci.runMetaM lctx' do Meta.withPPInaccessibleNames <| Widget.goalToInteractive (← Meta.mkFreshExprMVar ty).mvarId! let range := if let some r := i.range? then r.toLspRange text else ⟨p.position, p.position⟩ return some { goal with range } else return none def handlePlainTermGoal (p : PlainTermGoalParams) : RequestM (RequestTask (Option PlainTermGoal)) := do let t ← getInteractiveTermGoal p t.map <| Except.map <| Option.map fun goal => { goal := toString goal.toInteractiveGoal.pretty range := goal.range } partial def handleDocumentHighlight (p : DocumentHighlightParams) : RequestM (RequestTask (Array DocumentHighlight)) := do let doc ← readDoc let text := doc.meta.text let pos := text.lspPosToUtf8Pos p.position let rec highlightReturn? (doRange? : Option Range) : Syntax → Option DocumentHighlight | stx@`(doElem|return%$i $e) => do if let some range := i.getRange? then if range.contains pos then return some { range := doRange?.getD (range.toLspRange text), kind? := DocumentHighlightKind.text } highlightReturn? doRange? e | `(do%$i $elems) => highlightReturn? (i.getRange?.get!.toLspRange text) elems | stx => stx.getArgs.findSome? (highlightReturn? doRange?) withWaitFindSnap doc (fun s => s.endPos > pos) (notFoundX := pure #[]) fun snap => do if let some hi := highlightReturn? none snap.stx then return #[hi] return #[] section -- TODO https://github.com/leanprover/lean4/issues/529 open Parser.Command partial def handleDocumentSymbol (p : DocumentSymbolParams) : RequestM (RequestTask DocumentSymbolResult) := do let doc ← readDoc asTask do let ⟨cmdSnaps, e?⟩ ← doc.cmdSnaps.updateFinishedPrefix let mut stxs := cmdSnaps.finishedPrefix.map (·.stx) match e? with | some ElabTaskError.aborted => throw RequestError.fileChanged | some (ElabTaskError.ioError e) => throwThe IO.Error e | _ => () let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList let (syms, _) := toDocumentSymbols doc.meta.text stxs return { syms := syms.toArray } where toDocumentSymbols (text : FileMap) | [] => ([], []) | stx::stxs => match stx with | `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id | `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx) | `(end $(id)?) => ([], stx::stxs) | _ => do let (syms, stxs') := toDocumentSymbols text stxs unless stx.isOfKind ``Lean.Parser.Command.declaration do return (syms, stxs') if let some stxRange := stx.getRange? then let (name, selection) := match stx with | `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) => ((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig) | _ => match stx[1][1] with | `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id) | _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0]) if let some selRange := selection.getRange? then return (DocumentSymbol.mk { name := name kind := SymbolKind.method range := stxRange.toLspRange text selectionRange := selRange.toLspRange text } :: syms, stxs') return (syms, stxs') sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) := let (syms, stxs') := toDocumentSymbols text stxs -- discard `end` let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1) let endStx := match stxs' with | endStx::_ => endStx | [] => (stx::stxs').getLast! -- we can assume that commands always have at least one position (see `parseCommand`) let range := (mkNullNode #[stx, endStx]).getRange?.get!.toLspRange text (DocumentSymbol.mk { name kind range selectionRange := selection.getRange? |>.map (·.toLspRange text) |>.getD range children? := syms.toArray } :: syms', stxs'') end def noHighlightKinds : Array SyntaxNodeKind := #[ -- usually have special highlighting by the client ``Lean.Parser.Term.sorry, ``Lean.Parser.Term.type, ``Lean.Parser.Term.prop, -- not really keywords `antiquotName, ``Lean.Parser.Command.docComment] structure SemanticTokensContext where beginPos : String.Pos endPos : String.Pos text : FileMap snap : Snapshot structure SemanticTokensState where data : Array Nat lastLspPos : Lsp.Position partial def handleSemanticTokens (beginPos endPos : String.Pos) : RequestM (RequestTask SemanticTokens) := do let doc ← readDoc let text := doc.meta.text let t ← doc.cmdSnaps.waitAll (·.beginPos < endPos) mapTask t fun (snaps, _) => StateT.run' (s := { data := #[], lastLspPos := ⟨0, 0⟩ : SemanticTokensState }) do for s in snaps do if s.endPos <= beginPos then continue ReaderT.run (r := SemanticTokensContext.mk beginPos endPos text s) <| go s.stx return { data := (← get).data } where go (stx : Syntax) := do match stx with | `($e.$id:ident) => go e; addToken id SemanticTokenType.property -- indistinguishable from next pattern --| `(level|$id:ident) => addToken id SemanticTokenType.variable | `($id:ident) => highlightId id | _ => if !noHighlightKinds.contains stx.getKind then highlightKeyword stx if stx.isOfKind choiceKind then go stx[0] else stx.getArgs.forM go highlightId (stx : Syntax) : ReaderT SemanticTokensContext (StateT SemanticTokensState RequestM) _ := do if let some range := stx.getRange? then for ti in (← read).snap.infoTree.deepestNodes (fun | _, i@(Elab.Info.ofTermInfo ti), _ => match i.pos? with | some ipos => if range.contains ipos then some ti else none | _ => none | _, _, _ => none) do match ti.expr with | Expr.fvar .. => addToken ti.stx SemanticTokenType.variable | _ => if ti.stx.getPos?.get! > range.start then addToken ti.stx SemanticTokenType.property highlightKeyword stx := do if let Syntax.atom info val := stx then if val.bsize > 0 && val[0].isAlpha then addToken stx SemanticTokenType.keyword addToken stx type := do let ⟨beginPos, endPos, text, _⟩ ← read if let (some pos, some tailPos) := (stx.getPos?, stx.getTailPos?) then if beginPos <= pos && pos < endPos then let lspPos := (← get).lastLspPos let lspPos' := text.utf8PosToLspPos pos let deltaLine := lspPos'.line - lspPos.line let deltaStart := lspPos'.character - (if lspPos'.line == lspPos.line then lspPos.character else 0) let length := (text.utf8PosToLspPos tailPos).character - lspPos'.character let tokenType := type.toNat let tokenModifiers := 0 modify fun st => { data := st.data ++ #[deltaLine, deltaStart, length, tokenType, tokenModifiers] lastLspPos := lspPos' } def handleSemanticTokensFull (p : SemanticTokensParams) : RequestM (RequestTask SemanticTokens) := do handleSemanticTokens 0 (1 <<< 16) def handleSemanticTokensRange (p : SemanticTokensRangeParams) : RequestM (RequestTask SemanticTokens) := do let doc ← readDoc let text := doc.meta.text let beginPos := text.lspPosToUtf8Pos p.range.start let endPos := text.lspPosToUtf8Pos p.range.end handleSemanticTokens beginPos endPos partial def handleWaitForDiagnostics (p : WaitForDiagnosticsParams) : RequestM (RequestTask WaitForDiagnostics) := do let rec waitLoop : RequestM EditableDocument := do let doc ← readDoc if p.version ≤ doc.meta.version then return doc else IO.sleep 50 waitLoop let t ← RequestM.asTask waitLoop RequestM.bindTask t fun doc? => do let doc ← doc? let t₁ ← doc.cmdSnaps.waitAll return t₁.map fun _ => pure WaitForDiagnostics.mk builtin_initialize registerLspRequestHandler "textDocument/waitForDiagnostics" WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics registerLspRequestHandler "textDocument/completion" CompletionParams CompletionList handleCompletion registerLspRequestHandler "textDocument/hover" HoverParams (Option Hover) handleHover registerLspRequestHandler "textDocument/declaration" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.declaration) registerLspRequestHandler "textDocument/definition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.definition) registerLspRequestHandler "textDocument/typeDefinition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.type) registerLspRequestHandler "textDocument/documentHighlight" DocumentHighlightParams DocumentHighlightResult handleDocumentHighlight registerLspRequestHandler "textDocument/documentSymbol" DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol registerLspRequestHandler "textDocument/semanticTokens/full" SemanticTokensParams SemanticTokens handleSemanticTokensFull registerLspRequestHandler "textDocument/semanticTokens/range" SemanticTokensRangeParams SemanticTokens handleSemanticTokensRange registerLspRequestHandler "$/lean/plainGoal" PlainGoalParams (Option PlainGoal) handlePlainGoal registerLspRequestHandler "$/lean/plainTermGoal" PlainTermGoalParams (Option PlainTermGoal) handlePlainTermGoal end Lean.Server.FileWorker
52437f8c3361f176e54a7d970aa603593a1a358e
618003631150032a5676f229d13a079ac875ff77
/src/linear_algebra/bilinear_form.lean
386470dd8fd7c9a50d1c648d08ca96dae7863ef1
[ "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
24,516
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Andreas Swerdlow -/ import linear_algebra.matrix import linear_algebra.tensor_product /-! # Bilinear form This file defines a bilinear form over a module. Basic ideas such as orthogonality are also introduced, as well as reflexivive, symmetric and alternating bilinear forms. Adjoints of linear maps with respect to a bilinear form are also introduced. A bilinear form on an R-module M, is a function from M x M to R, that is linear in both arguments ## Notations Given any term B of type bilin_form, due to a coercion, can use the notation B x y to refer to the function field, ie. B x y = B.bilin x y. ## References * <https://en.wikipedia.org/wiki/Bilinear_form> ## Tags Bilinear form, -/ universes u v w /-- A bilinear form over a module -/ structure bilin_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] := (bilin : M → M → R) (bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z) (bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y)) (bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z) (bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y)) /-- A map with two arguments that is linear in both is a bilinear form -/ def linear_map.to_bilin {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M →ₗ[R] R) : bilin_form R M := { bilin := λ x y, f x y, bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z, bilin_smul_left := λ a x y, by {rw linear_map.map_smul, rw linear_map.smul_apply, rw smul_eq_mul}, bilin_add_right := λ x y z, linear_map.map_add (f x) y z, bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y } namespace bilin_form variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} instance : has_coe_to_fun (bilin_form R M) := ⟨_, λ B, B.bilin⟩ @[simp] lemma coe_fn_mk (f : M → M → R) (h₁ h₂ h₃ h₄) : (bilin_form.mk f h₁ h₂ h₃ h₄ : M → M → R) = f := rfl lemma coe_fn_congr : Π {x x' y y' : M}, x = x' → y = y' → B x y = B x' y' | _ _ _ _ rfl rfl := rfl lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y lemma zero_left (x : M) : B 0 x = 0 := by {rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul]} lemma zero_right (x : M) : B x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, ring.zero_mul] lemma neg_left (x y : M) : B (-x) y = -(B x y) := by rw [←@neg_one_smul R _ _, smul_left, neg_one_mul] lemma neg_right (x y : M) : B x (-y) = -(B x y) := by rw [←@neg_one_smul R _ _, smul_right, neg_one_mul] lemma sub_left (x y z : M) : B (x - y) z = B x z - B y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl lemma sub_right (x y z : M) : B x (y - z) = B x y - B x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl variable {D : bilin_form R M} @[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D := by {cases B, cases D, congr, funext, exact H _ _} instance : add_comm_group (bilin_form R M) := { add := λ B D, { bilin := λ x y, B x y + D x y, bilin_add_left := λ x y z, by {rw add_left, rw add_left, ac_refl}, bilin_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]}, bilin_add_right := λ x y z, by {rw add_right, rw add_right, ac_refl}, bilin_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} }, add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin coe_fn has_coe_to_fun.coe bilin, rw add_assoc}, zero := { bilin := λ x y, 0, bilin_add_left := λ x y z, (add_zero 0).symm, bilin_smul_left := λ a x y, (mul_zero a).symm, bilin_add_right := λ x y z, (zero_add 0).symm, bilin_smul_right := λ a x y, (mul_zero a).symm }, zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_add}, add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_zero}, neg := λ B, { bilin := λ x y, - (B.1 x y), bilin_add_left := λ x y z, by rw [bilin_add_left, neg_add], bilin_smul_left := λ a x y, by rw [bilin_smul_left, mul_neg_eq_neg_mul_symm], bilin_add_right := λ x y z, by rw [bilin_add_right, neg_add], bilin_smul_right := λ a x y, by rw [bilin_smul_right, mul_neg_eq_neg_mul_symm] }, add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw neg_add_self}, add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_comm} } lemma add_apply (x y : M) : (B + D) x y = B x y + D x y := rfl lemma neg_apply (x y : M) : (-B) x y = -(B x y) := rfl instance : inhabited (bilin_form R M) := ⟨0⟩ section variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] (F : bilin_form R₂ M) (f : M → M) instance to_module : module R₂ (bilin_form R₂ M) := { smul := λ c B, { bilin := λ x y, c * B x y, bilin_add_left := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_left, left_distrib]}, bilin_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_left, ←mul_assoc, mul_comm c, mul_assoc]}, bilin_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_right, left_distrib]}, bilin_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_right, ←mul_assoc, mul_comm c, mul_assoc]} }, smul_add := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw left_distrib}, add_smul := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw right_distrib}, mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_assoc}, one_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw one_mul}, zero_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_mul}, smul_zero := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_zero} } lemma smul_apply (a : R₂) (x y : M) : (a • F) x y = a • (F x y) := rfl /-- `B.to_linear_map` applies B on the left argument, then the right. -/ def to_linear_map : M →ₗ[R₂] M →ₗ[R₂] R₂ := linear_map.mk₂ R₂ F.1 (bilin_add_left F) (bilin_smul_left F) (bilin_add_right F) (bilin_smul_right F) /-- Bilinear forms are equivalent to maps with two arguments that is linear in both. -/ def bilin_linear_map_equiv : (bilin_form R₂ M) ≃ₗ[R₂] (M →ₗ[R₂] M →ₗ[R₂] R₂) := { to_fun := to_linear_map, add := λ B D, rfl, smul := λ a B, rfl, inv_fun := linear_map.to_bilin, left_inv := λ B, by {ext, refl}, right_inv := λ B, by {ext, refl} } @[norm_cast] lemma coe_fn_to_linear_map (x : M) : ⇑(F.to_linear_map x) = F x := rfl lemma map_sum_left {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (w : M) : B (t.sum g) w = t.sum (λ i, B (g i) w) := show B.to_linear_map (t.sum g) w = t.sum (λ i, B (g i) w), by { rw [B.to_linear_map.map_sum, linear_map.coe_fn_sum, finset.sum_apply], refl } lemma map_sum_right {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (v : M) : B v (t.sum g) = t.sum (λ i, B v (g i)) := (B.to_linear_map v).map_sum end section comp variables {N : Type w} [add_comm_group N] [module R N] /-- Apply a linear map on the left and right argument of a bilinear form. -/ def comp (B : bilin_form R N) (l r : M →ₗ[R] N) : bilin_form R M := { bilin := λ x y, B (l x) (r y), bilin_add_left := λ x y z, by simp [add_left], bilin_smul_left := λ x y z, by simp [smul_left], bilin_add_right := λ x y z, by simp [add_right], bilin_smul_right := λ x y z, by simp [smul_right] } /-- Apply a linear map to the left argument of a bilinear form. -/ def comp_left (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M := B.comp f linear_map.id /-- Apply a linear map to the right argument of a bilinear form. -/ def comp_right (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M := B.comp linear_map.id f @[simp] lemma comp_left_comp_right (B : bilin_form R M) (l r : M →ₗ[R] M) : (B.comp_left l).comp_right r = B.comp l r := rfl @[simp] lemma comp_right_comp_left (B : bilin_form R M) (l r : M →ₗ[R] M) : (B.comp_right r).comp_left l = B.comp l r := rfl @[simp] lemma comp_apply (B : bilin_form R N) (l r : M →ₗ[R] N) (v w) : B.comp l r v w = B (l v) (r w) := rfl @[simp] lemma comp_left_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) : B.comp_left f v w = B (f v) w := rfl @[simp] lemma comp_right_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) : B.comp_right f v w = B v (f w) := rfl end comp /-- The proposition that two elements of a bilinear form space are orthogonal -/ def is_ortho (B : bilin_form R M) (x y : M) : Prop := B x y = 0 lemma ortho_zero (x : M) : is_ortho B (0 : M) x := zero_left x section variables {R₃ : Type*} [domain R₃] [module R₃ M] {G : bilin_form R₃ M} theorem ortho_smul_left {x y : M} {a : R₃} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G (a • x) y) := begin dunfold is_ortho, split; intro H, { rw [smul_left, H, ring.mul_zero] }, { rw [smul_left, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end theorem ortho_smul_right {x y : M} {a : R₃} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G x (a • y)) := begin dunfold is_ortho, split; intro H, { rw [smul_right, H, ring.mul_zero] }, { rw [smul_right, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end end end bilin_form section matrix variables {R : Type u} [comm_ring R] variables {n o : Type w} [fintype n] [fintype o] open bilin_form finset matrix open_locale matrix /-- The linear map from `matrix n n R` to bilinear forms on `n → R`. -/ def matrix.to_bilin_formₗ : matrix n n R →ₗ[R] bilin_form R (n → R) := { to_fun := λ M, { bilin := λ v w, (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩, bilin_add_left := λ x y z, by simp [matrix.add_mul], bilin_smul_left := λ a x y, by simp, bilin_add_right := λ x y z, by simp [matrix.mul_add], bilin_smul_right := λ a x y, by simp }, add := λ f g, by { ext, simp [add_apply, matrix.mul_add, matrix.add_mul] }, smul := λ f g, by { ext, simp [smul_apply] } } /-- The map from `matrix n n R` to bilinear forms on `n → R`. -/ def matrix.to_bilin_form : matrix n n R → bilin_form R (n → R) := matrix.to_bilin_formₗ.to_fun lemma matrix.to_bilin_form_apply (M : matrix n n R) (v w : n → R) : (M.to_bilin_form : (n → R) → (n → R) → R) v w = (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩ := rfl variables [decidable_eq n] [decidable_eq o] /-- The linear map from bilinear forms on `n → R` to `matrix n n R`. -/ def bilin_form.to_matrixₗ : bilin_form R (n → R) →ₗ[R] matrix n n R := { to_fun := λ B i j, B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0), add := λ f g, rfl, smul := λ f g, rfl } /-- The map from bilinear forms on `n → R` to `matrix n n R`. -/ def bilin_form.to_matrix : bilin_form R (n → R) → matrix n n R := bilin_form.to_matrixₗ.to_fun lemma bilin_form.to_matrix_apply (B : bilin_form R (n → R)) (i j : n) : B.to_matrix i j = B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0) := rfl lemma bilin_form.to_matrix_smul (B : bilin_form R (n → R)) (x : R) : (x • B).to_matrix = x • B.to_matrix := by { ext, refl } open bilin_form lemma bilin_form.to_matrix_comp (B : bilin_form R (n → R)) (l r : (o → R) →ₗ[R] (n → R)) : (B.comp l r).to_matrix = l.to_matrixᵀ ⬝ B.to_matrix ⬝ r.to_matrix := begin ext i j, simp only [to_matrix_apply, comp_apply, mul_val, sum_mul], have sum_smul_eq : Π (f : (o → R) →ₗ[R] (n → R)) (i : o), f (λ n, ite (n = i) 1 0) = univ.sum (λ k, f.to_matrix k i • λ n, ite (n = k) (1 : R) 0), { intros f i, ext j, change f (λ n, ite (n = i) 1 0) j = univ.sum (λ k n, f.to_matrix k i * ite (n = k) (1 : R) 0) j, simp [linear_map.to_matrix, linear_map.to_matrixₗ, eq_comm] }, simp_rw [sum_smul_eq, map_sum_right, map_sum_left, smul_right, mul_comm, smul_left], refl end lemma bilin_form.to_matrix_comp_left (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) : (B.comp_left f).to_matrix = f.to_matrixᵀ ⬝ B.to_matrix := by simp [comp_left, bilin_form.to_matrix_comp] lemma bilin_form.to_matrix_comp_right (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) : (B.comp_right f).to_matrix = B.to_matrix ⬝ f.to_matrix := by simp [comp_right, bilin_form.to_matrix_comp] lemma bilin_form.mul_to_matrix_mul (B : bilin_form R (n → R)) (M : matrix o n R) (N : matrix n o R) : M ⬝ B.to_matrix ⬝ N = (B.comp (Mᵀ.to_lin) (N.to_lin)).to_matrix := by { ext, simp [B.to_matrix_comp (Mᵀ.to_lin) (N.to_lin), to_lin_to_matrix] } lemma bilin_form.mul_to_matrix (B : bilin_form R (n → R)) (M : matrix n n R) : M ⬝ B.to_matrix = (B.comp_left (Mᵀ.to_lin)).to_matrix := by { ext, simp [B.to_matrix_comp_left (Mᵀ.to_lin), to_lin_to_matrix] } lemma bilin_form.to_matrix_mul (B : bilin_form R (n → R)) (M : matrix n n R) : B.to_matrix ⬝ M = (B.comp_right (M.to_lin)).to_matrix := by { ext, simp [B.to_matrix_comp_right (M.to_lin), to_lin_to_matrix] } @[simp] lemma to_matrix_to_bilin_form (B : bilin_form R (n → R)) : B.to_matrix.to_bilin_form = B := begin ext, rw [matrix.to_bilin_form_apply, B.mul_to_matrix_mul, bilin_form.to_matrix_apply, comp_apply], { apply coe_fn_congr; ext; simp [mul_vec], }, { apply_instance, }, end @[simp] lemma to_bilin_form_to_matrix (M : matrix n n R) : M.to_bilin_form.to_matrix = M := by { ext, simp [bilin_form.to_matrix_apply, matrix.to_bilin_form_apply, mul_val], } /-- Bilinear forms are linearly equivalent to matrices. -/ def bilin_form_equiv_matrix : bilin_form R (n → R) ≃ₗ[R] matrix n n R := { inv_fun := matrix.to_bilin_form, left_inv := to_matrix_to_bilin_form, right_inv := to_bilin_form_to_matrix, ..bilin_form.to_matrixₗ } end matrix namespace refl_bilin_form open refl_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is reflexive -/ def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0 variable (H : is_refl B) lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y lemma ortho_sym {x y : M} : is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩ end refl_bilin_form namespace sym_bilin_form open sym_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is symmetric -/ def is_sym (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x variable (H : is_sym B) lemma sym (x y : M) : B x y = B y x := H x y lemma is_refl : refl_bilin_form.is_refl B := λ x y H1, H x y ▸ H1 lemma ortho_sym {x y : M} : is_ortho B x y ↔ is_ortho B y x := refl_bilin_form.ortho_sym (is_refl H) end sym_bilin_form namespace alt_bilin_form open alt_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is alternating -/ def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0 variable (H : is_alt B) include H lemma self_eq_zero (x : M) : B x x = 0 := H x lemma neg (x y : M) : - B x y = B y x := begin have H1 : B (x + y) (x + y) = 0, { exact self_eq_zero H (x + y) }, rw [add_left, add_right, add_right, self_eq_zero H, self_eq_zero H, ring.zero_add, ring.add_zero, add_eq_zero_iff_neg_eq] at H1, exact H1, end end alt_bilin_form namespace bilin_form section linear_adjoints variables {R : Type u} [comm_ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {M₂ : Type v} [add_comm_group M₂] [module R M₂] variables (B B' : bilin_form R M) (B₂ : bilin_form R M₂) variables (f f' : M →ₗ[R] M₂) (g g' : M₂ →ₗ[R] M) /-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of maps between them to be mutually adjoint. -/ def is_adjoint_pair := ∀ ⦃x y⦄, B₂ (f x) y = B x (g y) variables {B B' B₂ f f' g g'} lemma is_adjoint_pair.eq (h : is_adjoint_pair B B₂ f g) : ∀ {x y}, B₂ (f x) y = B x (g y) := h lemma is_adjoint_pair_iff_comp_left_eq_comp_right (f g : module.End R M) : is_adjoint_pair B B' f g ↔ B'.comp_left f = B.comp_right g := begin split; intros h, { ext x y, rw [comp_left_apply, comp_right_apply], apply h, }, { intros x y, rw [←comp_left_apply, ←comp_right_apply], rw h, }, end lemma is_adjoint_pair_zero : is_adjoint_pair B B₂ 0 0 := λ x y, by simp only [bilin_form.zero_left, bilin_form.zero_right, linear_map.zero_apply] lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl lemma is_adjoint_pair.add (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') : is_adjoint_pair B B₂ (f + f') (g + g') := λ x y, by rw [linear_map.add_apply, linear_map.add_apply, add_left, add_right, h, h'] lemma is_adjoint_pair.sub (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') : is_adjoint_pair B B₂ (f - f') (g - g') := λ x y, by rw [linear_map.sub_apply, linear_map.sub_apply, sub_left, sub_right, h, h'] lemma is_adjoint_pair.smul (c : R) (h : is_adjoint_pair B B₂ f g) : is_adjoint_pair B B₂ (c • f) (c • g) := λ x y, by rw [linear_map.smul_apply, linear_map.smul_apply, smul_left, smul_right, h] lemma is_adjoint_pair.comp {M₃ : Type v} [add_comm_group M₃] [module R M₃] {B₃ : bilin_form R M₃} {f' : M₂ →ₗ[R] M₃} {g' : M₃ →ₗ[R] M₂} (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B₂ B₃ f' g') : is_adjoint_pair B B₃ (f'.comp f) (g.comp g') := λ x y, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h] lemma is_adjoint_pair.mul {f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') : is_adjoint_pair B B (f * f') (g' * g) := λ x y, by rw [linear_map.mul_app, linear_map.mul_app, h, h'] variables (B B' B₂) /-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms on the underlying module. In the case that these two forms are identical, this is the usual concept of self adjointness. In the case that one of the forms is the negation of the other, this is the usual concept of skew adjointness. -/ def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B B' f f /-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/ def is_pair_self_adjoint_submodule : submodule R (module.End R M) := { carrier := { f | is_pair_self_adjoint B B' f }, zero := is_adjoint_pair_zero, add := λ f g hf hg, hf.add hg, smul := λ c f h, h.smul c, } /-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an adjoint for itself. -/ def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f /-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation serves as an adjoint. -/ def is_skew_adjoint (f : module.End R M) := is_adjoint_pair B B f (-f) lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R M) : B.is_skew_adjoint f ↔ is_adjoint_pair (-B) B f f := show (∀ x y, B (f x) y = B x ((-f) y)) ↔ ∀ x y, B (f x) y = (-B) x (f y), by simp only [linear_map.neg_apply, bilin_form.neg_apply, bilin_form.neg_right] /-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Jordan subalgebra.) -/ def self_adjoint_submodule := is_pair_self_adjoint_submodule B B @[simp] lemma mem_self_adjoint_submodule (f : module.End R M) : f ∈ B.self_adjoint_submodule ↔ B.is_self_adjoint f := iff.rfl /-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Lie subalgebra.) -/ def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B) B @[simp] lemma mem_skew_adjoint_submodule (f : module.End R M) : f ∈ B.skew_adjoint_submodule ↔ B.is_skew_adjoint f := by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl, } end linear_adjoints end bilin_form section matrix_adjoints open_locale matrix variables {R : Type u} [comm_ring R] variables {n : Type w} [fintype n] variables (J J₂ A B : matrix n n R) /-- The condition for the square matrices `A`, `B` to be an adjoint pair with respect to the square matrices `J`, `J₂`. -/ def matrix.is_adjoint_pair := Aᵀ ⬝ J₂ = J ⬝ B /-- The condition for a square matrix `A` to be self-adjoint with respect to the square matrix `J`. -/ def matrix.is_self_adjoint := matrix.is_adjoint_pair J J A A /-- The condition for a square matrix `A` to be skew-adjoint with respect to the square matrix `J`. -/ def matrix.is_skew_adjoint := matrix.is_adjoint_pair J J A (-A) lemma matrix_is_adjoint_pair_bilin_form : matrix.is_adjoint_pair J J₂ A B ↔ bilin_form.is_adjoint_pair J.to_bilin_form J₂.to_bilin_form A.to_lin B.to_lin := begin classical, rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right, have h : ∀ (B B' : bilin_form R (n → R)), B = B' ↔ B.to_matrix = B'.to_matrix := λ B B', by { split; intros h, { rw h, }, { rw [←to_matrix_to_bilin_form B, h, to_matrix_to_bilin_form B'], }, }, rw [h, J₂.to_bilin_form.to_matrix_comp_left A.to_lin, J.to_bilin_form.to_matrix_comp_right B.to_lin, to_lin_to_matrix, to_lin_to_matrix, to_bilin_form_to_matrix, to_bilin_form_to_matrix], refl, end variables [decidable_eq n] /-- Given a pair of square matrices `J`, `J₂` defining bilinear forms on the free module, there is a natural embedding from the corresponding submodule of pair-self-adjoint endomorphisms into the module of matrices. -/ def pair_self_adjoint_matrices_linear_embedding : bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form →ₗ[R] matrix n n R := linear_equiv_matrix'.to_linear_map.comp (bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form).subtype lemma pair_self_adjoint_matrices_linear_embedding_apply (f : bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form) : (pair_self_adjoint_matrices_linear_embedding J J₂ : _ →ₗ _) f = (f : module.End R (n → R)).to_matrix := rfl lemma pair_self_adjoint_matrices_linear_embedding_injective : function.injective (pair_self_adjoint_matrices_linear_embedding J J₂) := λ f g h, by { apply set_coe.ext, exact linear_equiv_matrix'.injective h, } /-- The submodule of pair-self-adjoint matrices with respect to bilinear forms corresponding to given matrices `J`, `J₂`. -/ def pair_self_adjoint_matrices_submodule : submodule R (matrix n n R) := (pair_self_adjoint_matrices_linear_embedding J J₂).range @[simp] lemma mem_pair_self_adjoint_matrices_submodule : A ∈ (pair_self_adjoint_matrices_submodule J J₂) ↔ matrix.is_adjoint_pair J J₂ A A := begin change A ∈ (pair_self_adjoint_matrices_linear_embedding J J₂).range ↔ matrix.is_adjoint_pair J J₂ A A, rw [matrix_is_adjoint_pair_bilin_form, linear_map.mem_range], simp only [pair_self_adjoint_matrices_linear_embedding_apply], split, { rintros ⟨⟨A', hA'⟩, h⟩, rw ←h, rw to_matrix_to_lin, exact hA', }, { intros h, exact ⟨⟨A.to_lin, h⟩, to_lin_to_matrix⟩, }, end /-- The submodule of self-adjoint matrices with respect to the bilinear form corresponding to the matrix `J`. -/ def self_adjoint_matrices_submodule : submodule R (matrix n n R) := pair_self_adjoint_matrices_submodule J J /-- The submodule of skew-adjoint matrices with respect to the bilinear form corresponding to the matrix `J`. -/ def skew_adjoint_matrices_submodule : submodule R (matrix n n R) := pair_self_adjoint_matrices_submodule (-J) J end matrix_adjoints
5dbaeb2e2be95862b6ac81c30be76a03b9c9a901
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/category/bitraversable/basic.lean
22fff327e3935eff1b77f14fa46716406039f441
[ "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,141
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Functors with two arguments -/ import data.sum category.basic category.functor category.bifunctor category.traversable.basic tactic.basic universes u class bitraversable (t : Type u → Type u → Type u) extends bifunctor t := (bitraverse : Π {m : Type u → Type u} [applicative m] {α α' β β'}, (α → m α') → (β → m β') → t α β → m (t α' β')) export bitraversable ( bitraverse ) def bisequence {t m} [bitraversable t] [applicative m] {α β} : t (m α) (m β) → m (t α β) := bitraverse id id open functor class is_lawful_bitraversable (t : Type u → Type u → Type u) [bitraversable t] extends is_lawful_bifunctor t := (id_bitraverse : ∀ {α β} (x : t α β), bitraverse id.mk id.mk x = id.mk x ) (comp_bitraverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α α' β β' γ γ'} (f : β → F γ) (f' : β' → F γ') (g : α → G β) (g' : α' → G β') (x : t α α'), bitraverse (comp.mk ∘ map f ∘ g) (comp.mk ∘ map f' ∘ g') x = comp.mk (bitraverse f f' <$> bitraverse g g' x) ) (bitraverse_eq_bimap_id : ∀ {α α' β β'} (f : α → β) (f' : α' → β') (x : t α α'), bitraverse (id.mk ∘ f) (id.mk ∘ f') x = id.mk (bimap f f' x)) (binaturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α α' β β'} (f : α → F β) (f' : α' → F β') (x : t α α'), η (bitraverse f f' x) = bitraverse (@η _ ∘ f) (@η _ ∘ f') x) export is_lawful_bitraversable ( id_bitraverse comp_bitraverse bitraverse_eq_bimap_id ) open is_lawful_bitraversable attribute [higher_order bitraverse_id_id] id_bitraverse attribute [higher_order bitraverse_comp] comp_bitraverse attribute [higher_order] binaturality bitraverse_eq_bimap_id export is_lawful_bitraversable (bitraverse_id_id bitraverse_comp)
c8491414914dd9e72bc81ef6282245b2f7850fef
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love11_logical_foundations_of_mathematics_homework_sheet.lean
91e08e69d40428b442a202c450cec4f16525fd26
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,122
lean
import .lovelib /- # LoVe Homework 11: Logical Foundations of Mathematics Homework must be done individually. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Question 1 (9 points): Multisets as a Quotient Type A multiset (or bag) is a collection of elements that allows for multiple (but finitely many) occurrences of its elements. For example, the multiset `{2, 7}` is equal to the multiset `{7, 2}` but different from `{2, 7, 7}`. Finite multisets can be defined as a quotient over lists. We start with the type `list α` of finite lists and consider only the number of occurrences of elements in the lists, ignoring the order in which elements occur. Following this scheme, `[2, 7, 7]`, `[7, 2, 7]`, and `[7, 7, 2]` would be three equally valid representations of the multiset `{2, 7, 7}`. The `list.count` function returns the number of occurrences of an element in a list. Since it uses equality on elements of type `α`, it requires `α` to belong to the `decidable_eq` type class. For this reason, the definitions and lemmas below all take `[decidable_eq α]` as type class argument. 1.1 (1 point). Provide the missing proof below. -/ @[instance] def multiset.rel (α : Type) [decidable_eq α] : setoid (list α) := { r := λas bs, ∀x, list.count x as = list.count x bs, iseqv := sorry } /- 1.2 (1 point). Define the type of multisets as the quotient over the relation `multiset.rel`. -/ def multiset (α : Type) [decidable_eq α] : Type := sorry /- 1.3 (3 points). Now we have a type `multiset α` but no operations on it. Basic operations on multisets include the empty multiset (`∅`), the singleton multiset (`{x} `for any element `x`), and the sum of two multisets (`A ⊎ B` for any multisets `A` and `B`). The sum should be defined so that the multiplicities of elements are added; thus, `{2} ⊎ {2, 2} = {2, 2, 2}`. Fill in the `sorry` placeholders below to implement the basic multiset operations. -/ def multiset.empty {α : Type} [decidable_eq α] : multiset α := sorry def multiset.singleton {α : Type} [decidable_eq α] (a : α) : multiset α := sorry def multiset.union {α : Type} [decidable_eq α] : multiset α → multiset α → multiset α := quotient.lift₂ sorry sorry /- 1.4 (4 points). Prove that `multiset.union` is commutative and associative, and has `multiset.empty` as identity element. -/ lemma multiset.union_comm {α : Type} [decidable_eq α] (A B : multiset α) : multiset.union A B = multiset.union B A := sorry lemma multiset.union_assoc {α : Type} [decidable_eq α] (A B C : multiset α) : multiset.union (multiset.union A B) C = multiset.union A (multiset.union B C) := sorry lemma multiset.union_iden_left {α : Type} [decidable_eq α] (A : multiset α) : multiset.union multiset.empty A = A := sorry lemma multiset.union_iden_right {α : Type} [decidable_eq α] (A : multiset α) : multiset.union A multiset.empty = A := sorry /- ## Question 2 (2 bonus points): Nonempty Types In the lecture, we saw the inductive predicate `nonempty` that states that a type has at least one element: -/ #print nonempty /- The purpose of this question is to think about what would happen if all types had at least one element. To investigate this, we introduce this fact as an axiom as follows. Introducing axioms should be generally avoided or done with great care, since they can easily lead to contradictions, as we will see. -/ axiom Sort_nonempty (α : Sort _) : nonempty α /- This axiom gives us a lemma `Sort_nonempty` admitted with no proof. It resembles a lemma proved by `sorry`, just without the warning. -/ #check Sort_nonempty /- 2.1 (1 bonus point). Prove that this axiom leads to a contradiction, i.e., lets us derive `false`. -/ lemma proof_of_false : false := sorry /- 2.2 (1 bonus point). Prove that even the following weaker axiom leads to a contradiction. Of course, you may not use the axiom or the lemma from 3.1. Hint: Subtypes can help. -/ axiom Type_nonempty (α : Type _) : nonempty α lemma proof_of_false₂ : false := sorry end LoVe
19892a754ecaab5caf3168c9fced882f6d19b08f
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/category_theory/limits/shapes/constructions/preserve_binary_products.lean
8e3a325b26ccc2b92f10645ed125dfaccdff5e8b
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,562
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.limits import category_theory.limits.preserves.basic import category_theory.limits.shapes.binary_products /-! Show that a functor `F : C ⥤ D` preserves binary products if and only if `⟨Fπ₁, Fπ₂⟩ : F (A ⨯ B) ⟶ F A ⨯ F B` (that is, `prod_comparison`) is an isomorphism for all `A, B`. -/ noncomputable theory open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables (F : C ⥤ D) /-- (Implementation). Construct a cone for `pair A B ⋙ F` which we will show is limiting. -/ @[simps] def alternative_cone (A B : C) [has_limit (pair (F.obj A) (F.obj B))] : cone (pair A B ⋙ F) := { X := F.obj A ⨯ F.obj B, π := discrete.nat_trans (λ j, walking_pair.cases_on j limits.prod.fst limits.prod.snd)} /-- (Implementation). Show that we have a limit for the shape `pair A B ⋙ F`. -/ def alternative_cone_is_limit (A B : C) [has_limit (pair (F.obj A) (F.obj B))] : is_limit (alternative_cone F A B) := { lift := λ s, prod.lift (s.π.app walking_pair.left) (s.π.app walking_pair.right), fac' := λ s j, walking_pair.cases_on j (prod.lift_fst _ _) (prod.lift_snd _ _), uniq' := λ s m w, prod.hom_ext (by { rw prod.lift_fst, apply w walking_pair.left }) (by { rw prod.lift_snd, apply w walking_pair.right }) } variables [has_binary_products C] [has_binary_products D] /-- If `prod_comparison F A B` is an iso, then `F` preserves the limit `A ⨯ B`. -/ def preserves_binary_prod_of_prod_comparison_iso (A B : C) [is_iso (prod_comparison F A B)] : preserves_limit (pair A B) F := preserves_limit_of_preserves_limit_cone (limit.is_limit (pair A B)) begin apply is_limit.of_iso_limit (alternative_cone_is_limit F A B) _, apply cones.ext _ _, { apply (as_iso (prod_comparison F A B)).symm }, { rintro ⟨j⟩, { apply (as_iso (prod_comparison F A B)).eq_inv_comp.2 (prod.lift_fst _ _) }, { apply (as_iso (prod_comparison F A B)).eq_inv_comp.2 (prod.lift_snd _ _) } }, end /-- If `prod_comparison F A B` is an iso for all `A, B` , then `F` preserves binary products. -/ instance preserves_binary_prods_of_prod_comparison_iso [∀ A B, is_iso (prod_comparison F A B)] : preserves_limits_of_shape (discrete walking_pair) F := { preserves_limit := λ K, begin haveI := preserves_binary_prod_of_prod_comparison_iso F (K.obj walking_pair.left) (K.obj walking_pair.right), apply preserves_limit_of_iso_diagram F (diagram_iso_pair K).symm, end } variables [preserves_limits_of_shape (discrete walking_pair) F] /-- The product comparison isomorphism. Technically a special case of `preserves_limit_iso`, but this version is convenient to have. -/ instance prod_comparison_iso_of_preserves_binary_prods (A B : C) : is_iso (prod_comparison F A B) := let t : is_limit (F.map_cone _) := preserves_limit.preserves (limit.is_limit (pair A B)) in { inv := t.lift (alternative_cone F A B), hom_inv_id' := begin apply is_limit.hom_ext t, rintro ⟨j⟩, { rw [category.assoc, t.fac, category.id_comp], apply prod.lift_fst }, { rw [category.assoc, t.fac, category.id_comp], apply prod.lift_snd }, end, inv_hom_id' := by ext ⟨j⟩; { simpa [prod_comparison] using t.fac _ _ } } end category_theory.limits
1bc9660c99ae0ea98b30e931e035134d18ec9faf
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/data/set/lattice.lean
3c2f775772d18127e1ccdfbb3d434214000cdf71
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
53,824
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit? -/ import order.complete_boolean_algebra import data.sigma.basic import order.galois_connection import order.directed open function tactic set auto universes u v variables {α β γ : Type*} {ι ι' ι₂ : Sort*} namespace set instance lattice_set : complete_lattice (set α) := { Sup := λs, {a | ∃ t ∈ s, a ∈ t }, Inf := λs, {a | ∀ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in, .. set.boolean_algebra, .. (infer_instance : complete_lattice (α → Prop)) } /-- Image is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := assume s t, assume h : s ⊆ t, image_subset _ h theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) := assume b₁ b₂ h, inter_subset_inter (hf h) (hg h) theorem monotone_union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) := assume b₁ b₂ h, union_subset_union (hf h) (hg h) theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s` -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, assume h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... lemma Union_prop (f : ι → set α) (p : ι → Prop) (i : ι) [decidable $ p i] : (⋃ (h : p i), f i) = if p i then f i else ∅ := begin ext x, rw mem_Union, split_ifs ; tauto, end @[simp] lemma Union_prop_pos {p : ι → Prop} {i : ι} (hi : p i) (f : ι → set α) : (⋃ (h : p i), f i) = f i := begin classical, ext x, rw [Union_prop, if_pos hi] end @[simp] lemma Union_prop_neg {p : ι → Prop} {i : ι} (hi : ¬ p i) (f : ι → set α) : (⋃ (h : p i), f i) = ∅ := begin classical, ext x, rw [Union_prop, if_neg hi] end lemma exists_set_mem_of_union_eq_top {ι : Type*} (t : set ι) (s : ι → set β) (w : (⋃ i ∈ t, s i) = ⊤) (x : β) : ∃ (i ∈ t), x ∈ s i := begin have p : x ∈ ⊤ := set.mem_univ x, simpa only [←w, set.mem_Union] using p, end lemma nonempty_of_union_eq_top_of_nonempty {ι : Type*} (t : set ι) (s : ι → set α) (H : nonempty α) (w : (⋃ i ∈ t, s i) = ⊤) : t.nonempty := begin obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some, exact ⟨x, m⟩, end theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) := ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := mem_Inter.2 theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set β) _ set.lattice_set _ _ h theorem subset_Inter_iff {t : set β} {s : ι → set β} : t ⊆ (⋂ i, s i) ↔ ∀ i, t ⊆ s i := @le_infi_iff (set β) _ set.lattice_set _ _ theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr -- This rather trivial consequence is convenient with `apply`, -- and has `i` explicit for this use case. theorem subset_subset_Union {A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i := subset.trans h (subset_Union s i) theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := set.subset.trans (set.Inter_subset s i) h lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ (⋂ i, t i) := set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i) lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x }) = {x : α | ∀ i, P i x} := by { ext, simp } lemma Union_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋃ x, f x) = ⋃ y, g y := supr_congr h h1 h2 lemma Inter_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋂ x, f x) = ⋂ y, g y := infi_congr h h1 h2 theorem Union_const [nonempty ι] (s : set β) : (⋃ i:ι, s) = s := supr_const theorem Inter_const [nonempty ι] (s : set β) : (⋂ i:ι, s) = s := infi_const @[simp] -- complete_boolean_algebra theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) := ext (λ x, by simp [not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ := by simp [compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := ext $ assume x, by simp [forall_or_distrib_left] theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) := by { rintro x ⟨_, ⟨i, rfl⟩, ⟨xs, xt⟩⟩, exact ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨i, rfl⟩, xt⟩⟩ } lemma Union_inter_of_monotone {ι α} [semilattice_sup ι] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := begin ext x, refine ⟨λ hx, Union_inter_subset hx, _⟩, rintro ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨j, rfl⟩, xt⟩⟩, exact ⟨_, ⟨i ⊔ j, rfl⟩, ⟨hs le_sup_left xs, ht le_sup_right xt⟩⟩ end /-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/ lemma Union_Inter_subset {ι ι' α} {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := by { rintro x ⟨_, ⟨i, rfl⟩, hx⟩ _ ⟨j, rfl⟩, exact ⟨_, ⟨i, rfl⟩, hx _ ⟨j, rfl⟩⟩ } lemma Union_option {ι} (s : option ι → set α) : (⋃ o, s o) = s none ∪ ⋃ i, s (some i) := supr_option s lemma Inter_option {ι} (s : option ι → set α) : (⋂ o, s o) = s none ∩ ⋂ i, s (some i) := infi_option s /-! ### Bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp lemma mem_bUnion_iff' {p : α → Prop} {t : α → set β} {y : β} : y ∈ (⋃ i (h : p i), t i) ↔ ∃ i (h : p i), y ∈ t i := mem_bUnion_iff theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := subset_Inter $ assume x, subset_Inter $ h x theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β} (h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) : (⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) := begin intros x, simp only [mem_Union], rintros ⟨a, a_in, ha⟩, rcases h a a_in with ⟨c, c_in, hc⟩, exact ⟨c, c_in, hc ha⟩ end theorem bInter_mono' {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) := begin intros x x_in, simp only [mem_Inter] at *, exact λ a a_in, h a a_in $ x_in _ (hs a_in) end theorem bInter_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s, t' x) := bInter_mono' (subset.refl s) h theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) := bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩) theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) : (⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) := supr_subtype' theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) : (⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) := infi_subtype' theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false. from infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := show (⨅ x ∈ ({a} : set α), s x) = s a, by simp theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by simp [inter_comm] lemma bInter_inter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, f i ∩ t) = (⋂ i ∈ s, f i) ∩ t := begin haveI : nonempty s := hs.to_subtype, simp [bInter_eq_Inter, ← Inter_inter] end lemma inter_bInter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, t ∩ f i) = t ∩ ⋂ i ∈ s, f i := begin rw [inter_comm, ← bInter_inter hs], simp [inter_comm] end theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union @[simp] lemma Union_subtype {α β : Type*} (s : set α) (f : α → set β) : (⋃ (i : s), f i) = ⋃ (i ∈ s), f i := (set.bUnion_eq_Union s $ λ x _, f x).symm -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) := ext (λ x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) := ext (λ x, by simp [not_forall]) theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) : u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i := begin ext x, simp only [exists_prop, mem_Union, mem_inter_eq], exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩ end theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) : (⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) := by simp [@inter_comm _ _ u, inter_bUnion] /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton @[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot @[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top @[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s := by simp [← ne_empty_iff_nonempty] lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩ lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty := nonempty.of_sUnion $ h.symm ▸ univ_nonempty theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := begin ext x, simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib], split ; tauto end @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl lemma Union_eq_univ_iff {f : ι → set α} : (⋃ i, f i) = univ ↔ ∀ x, ∃ i, x ∈ f i := by simp only [eq_univ_iff_forall, mem_Union] lemma bUnion_eq_univ_iff {f : α → set β} {s : set α} : (⋃ x ∈ s, f x) = univ ↔ ∀ y, ∃ x ∈ s, y ∈ f x := by simp only [Union_eq_univ_iff, mem_Union] lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b := by simp only [eq_univ_iff_forall, mem_sUnion] theorem compl_sUnion (S : set (set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := ext $ λ x, by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = (⋂₀ (compl '' S))ᶜ := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : (⋂₀ S)ᶜ = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set α)) : ⋂₀ S = (⋃₀ (compl '' S))ᶜ := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintros ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h @[simp] lemma Union_of_singleton (α : Type*) : (⋃(x : α), {x}) = @set.univ α := ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩ @[simp] lemma Union_of_singleton_coe (s : set α) : (⋃ (i : s), {i} : set α) = s := ext $ by simp theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := by rw [← sUnion_image, image_id'] lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := by rw [← sInter_image, image_id'] lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) := by simp only [←sUnion_range, subtype.range_coe] lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) := by simp only [←sInter_range, subtype.range_coe] lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set α) := { compl := compl, sdiff := (\), infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t), by simp; exact assume h, or.imp_right (assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], .. set.boolean_algebra, .. set.lattice_set } lemma sInter_union_sInter {S T : set (set α)} : (⋂₀S) ∪ (⋂₀T) = (⋂p ∈ S.prod T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀s) ∩ (⋃₀t) = (⋃p ∈ s.prod t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/ lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋂₀ T s ‹s ∈ S›) : ⋂₀ (⋃s∈S, T s ‹_›) = ⋂₀ S := begin ext, simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib], split, { assume H s sS, rw [hT s sS, mem_sInter], assume t tTs, exact H t s sS tTs }, { assume H t s sS tTs, suffices : s ⊆ t, exact this (H s sS), rw [hT s sS, sInter_eq_bInter], exact bInter_subset_of_mem tTs } end /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/ lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋃₀ T s ‹_›) : ⋃₀ (⋃s∈S, T s ‹_›) = ⋃₀ S := begin ext, simp only [exists_prop, set.mem_Union, set.mem_set_of_eq], split, { rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩, refine ⟨s, ⟨sS, _⟩⟩, rw hT s sS, exact subset_sUnion_of_mem tTs xt }, { rintros ⟨s, ⟨sS, xs⟩⟩, rw hT s sS at xs, rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩, exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ } end lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) : (⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨⟨s, hs⟩, rfl⟩⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨⟨s, hs⟩, _⟩⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α) {f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) : (⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ } end lemma union_distrib_Inter_right {ι : Type*} (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) := begin ext x, rw [mem_union_eq, mem_Inter], split ; finish end lemma union_distrib_Inter_left {ι : Type*} (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) := begin rw [union_comm, union_distrib_Inter_right], simp [union_comm] end section function /-! ### `maps_to` -/ lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) : maps_to f (⋃₀ S) t := λ x ⟨s, hs, hx⟩, H s hs hx lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) : maps_to f (⋃ i, s i) t := maps_to_sUnion $ forall_range_iff.2 H lemma maps_to_bUnion {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α} {t : set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) t) : maps_to f (⋃ i hi, s i hi) t := maps_to_Union $ λ i, maps_to_Union (H i) lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋃ i, s i) (⋃ i, t i) := maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i) lemma maps_to_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := maps_to_Union_Union $ λ i, maps_to_Union_Union (H i) lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) : maps_to f s (⋂₀ T) := λ x hx t ht, H t ht hx lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) : maps_to f s (⋂ i, t i) := λ x hx, mem_Inter.2 $ λ i, H i hx lemma maps_to_bInter {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f s (t i hi)) : maps_to f s (⋂ i hi, t i hi) := maps_to_Inter $ λ i, maps_to_Inter (H i) lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋂ i, s i) (⋂ i, t i) := maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _) lemma maps_to_bInter_bInter {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋂ i hi, s i hi) (⋂ i hi, t i hi) := maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i) lemma image_Inter_subset (s : ι → set α) (f : α → β) : f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) := (maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset lemma image_bInter_subset {p : ι → Prop} (s : Π i (hi : p i), set α) (f : α → β) : f '' (⋂ i hi, s i hi) ⊆ ⋂ i hi, f '' (s i hi) := (maps_to_bInter_bInter $ λ i hi, maps_to_image f (s i hi)).image_subset lemma image_sInter_subset (S : set (set α)) (f : α → β) : f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s := by { rw sInter_eq_bInter, apply image_bInter_subset } /-! ### `inj_on` -/ lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) : f '' (⋂ i, s i) = ⋂ i, f '' (s i) := begin inhabit ι, refine subset.antisymm (image_Inter_subset s f) (λ y hy, _), simp only [mem_Inter, mem_image_iff_bex] at hy, choose x hx hy using hy, refine ⟨x (default ι), mem_Inter.2 $ λ i, _, hy _⟩, suffices : x (default ι) = x i, { rw this, apply hx }, replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i), apply h (hx _) (hx _), simp only [hy] end lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β} (h : inj_on f (⋃ i hi, s i hi)) : f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) := begin simp only [Inter, infi_subtype'], haveI : nonempty {i // p i} := nonempty_subtype.2 hp, apply inj_on.image_Inter_eq, simpa only [Union, supr_subtype'] using h end lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {f : α → β} (hf : ∀ i, inj_on f (s i)) : inj_on f (⋃ i, s i) := begin intros x hx y hy hxy, rcases mem_Union.1 hx with ⟨i, hx⟩, rcases mem_Union.1 hy with ⟨j, hy⟩, rcases hs i j with ⟨k, hi, hj⟩, exact hf k (hi hx) (hj hy) hxy end /-! ### `surj_on` -/ lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) : surj_on f s (⋃₀ T) := λ x ⟨t, ht, hx⟩, H t ht hx lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) : surj_on f s (⋃ i, t i) := surj_on_sUnion $ forall_range_iff.2 H lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) : surj_on f (⋃ i, s i) (⋃ i, t i) := surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _) lemma surj_on_bUnion {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f s (t i hi)) : surj_on f s (⋃ i hi, t i hi) := surj_on_Union $ λ i, surj_on_Union (H i) lemma surj_on_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f (s i hi) (t i hi)) : surj_on f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := surj_on_Union_Union $ λ i, surj_on_Union_Union (H i) lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) t := begin intros y hy, rw [Hinj.image_Inter_eq, mem_Inter], exact λ i, H i hy end lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) (⋂ i, t i) := surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj /-! ### `bij_on` -/ lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := ⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩ lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := ⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _), surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩ lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) end function section variables {p : Prop} {μ : p → set α} @[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp @[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp @[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp @[simp] lemma Union_empty : (⋃i:ι, ∅:set α) = ∅ := supr_bot @[simp] lemma Inter_univ : (⋂i:ι, univ:set α) = univ := infi_top variables {s : ι → set α} @[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot @[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top @[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty := by simp [← ne_empty_iff_nonempty] end section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma image_bUnion {f : α → β} {s : ι → set α} {p : ι → Prop} : f '' (⋃ i (hi : p i), s i) = (⋃ i (hi : p i), f '' s i) := by simp only [image_Union] lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) := set.ext $ assume a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) := set.ext $ assume b, by simp [@eq_comm β b] @[simp] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) := supr_range @[simp] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) := infi_range variables {s : set γ} {f : γ → α} {g : α → set β} @[simp] lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) := supr_image @[simp] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) := infi_image end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort*} {f : α → β} {s : ι → set β} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : f ⁻¹' (⋃i ∈ s, t i) = (⋃i ∈ s, f ⁻¹' (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : f ⁻¹' (⋃₀ s) = (⋃t ∈ s, f ⁻¹' t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) := by ext; simp @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := by rw [← preimage_bUnion, bUnion_of_singleton] lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ := by simp end preimage section prod theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x).prod (g x)) := assume a b h, prod_mono (hf h) (hg h) alias monotone_prod ← monotone.set_prod lemma prod_Union {ι} {s : set α} {t : ι → set β} : s.prod (⋃ i, t i) = ⋃ i, s.prod (t i) := by { ext, simp } lemma prod_bUnion {ι} {u : set ι} {s : set α} {t : ι → set β} : s.prod (⋃ i ∈ u, t i) = ⋃ i ∈ u, s.prod (t i) := by simp_rw [prod_Union] lemma prod_sUnion {s : set α} {C : set (set β)} : s.prod (⋃₀ C) = ⋃₀ ((λ t, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, prod_bUnion, bUnion_image] } lemma Union_prod_const {ι} {s : ι → set α} {t : set β} : (⋃ i, s i).prod t = ⋃ i, (s i).prod t := by { ext, simp } lemma bUnion_prod_const {ι} {u : set ι} {s : ι → set α} {t : set β} : (⋃ i ∈ u, s i).prod t = ⋃ i ∈ u, (s i).prod t := by simp_rw [Union_prod_const] lemma sUnion_prod_const {C : set (set α)} {t : set β} : (⋃₀ C).prod t = ⋃₀ ((λ s : set α, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, bUnion_prod_const, bUnion_image] } lemma Union_prod {ι α β} (s : ι → set α) (t : ι → set β) : (⋃ (x : ι × ι), (s x.1).prod (t x.2)) = (⋃ (i : ι), s i).prod (⋃ (i : ι), t i) := by { ext, simp } lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ} (hs : monotone s) (ht : monotone t) : (⋃ x, (s x).prod (t x)) = (⋃ x, (s x)).prod (⋃ x, (t x)) := begin ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split, { intros x hz hw, exact ⟨⟨x, hz⟩, ⟨x, hw⟩⟩ }, { intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ } end end prod section image2 variables (f : α → β → γ) {s : set α} {t : set β} lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ } lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩, exact ⟨b, d, a, c, e⟩ } lemma image2_Union_left (s : ι → set α) (t : set β) : image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t := by simp only [← image_prod, Union_prod_const, image_Union] lemma image2_Union_right (s : set α) (t : ι → set β) : image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) := by simp only [← image_prod, prod_Union, image_Union] end image2 section seq /-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over all `f ∈ s`. -/ def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : s.prod t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap] lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t := by { ext, simp } end seq instance : monad set := { pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, seq := λ(α β : Type u), set.seq, map := λ(α β : Type u), set.image } section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad instance : is_lawful_monad set := { pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume α, id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ assume α β s t, prod_image_seq_comm s t ⟩ section pi variables {π : α → Type*} lemma pi_def (i : set α) (s : Πa, set (π a)) : pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) := by { ext, simp } lemma univ_pi_eq_Inter (t : Π i, set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i := by simp only [pi_def, Inter_pos, mem_univ] lemma pi_diff_pi_subset (i : set α) (s t : Πa, set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) := begin refine diff_subset_comm.2 (λ x hx a ha, _), simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply] at hx, exact hx.2 _ ha (hx.1 _ ha) end lemma Union_univ_pi (t : Π i, ι → set (π i)) : (⋃ (x : α → ι), pi univ (λ i, t i (x i))) = pi univ (λ i, ⋃ (j : ι), t i j) := by { ext, simp [classical.skolem] } end pi end set namespace function namespace surjective lemma Union_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋃ x, g (f x)) = ⋃ y, g y := hf.supr_comp g lemma Inter_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋂ x, g (f x)) = ⋂ y, g y := hf.infi_comp g end surjective end function /-! ### Disjoint sets -/ section disjoint variables {s t u : set α} namespace disjoint /-! We define some lemmas in the `disjoint` namespace to be able to use projection notation. -/ theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) := λ x hx, h hx end disjoint namespace set protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff lemma not_disjoint_iff : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t := not_forall.trans $ exists_congr $ λ x, not_not lemma disjoint_left : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩ theorem disjoint_right : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := d.mono_left h theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t := d.mono_right h theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) : disjoint s t := d.mono h1 h2 @[simp] theorem disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left @[simp] theorem disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right @[simp] theorem disjoint_Union_left {ι : Sort*} {s : ι → set α} : disjoint (⋃ i, s i) t ↔ ∀ i, disjoint (s i) t := supr_disjoint_iff @[simp] theorem disjoint_Union_right {ι : Sort*} {s : ι → set α} : disjoint t (⋃ i, s i) ↔ ∀ i, disjoint t (s i) := disjoint_supr_iff theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) @[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint {s : set α}: disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ := disjoint_top @[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl @[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) : pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) := λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂) lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) : f ⁻¹' s = ∅ := by simpa using h.preimage f lemma preimage_eq_empty_iff {f : α → β} {s : set β} : disjoint s (range f) ↔ f ⁻¹' s = ∅ := ⟨preimage_eq_empty, λ h, by { simp [eq_empty_iff_forall_not_mem, set.disjoint_iff_inter_eq_empty] at h ⊢, finish }⟩ end set end disjoint namespace set /-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection are disjoint. -/ def pairwise_disjoint (s : set (set α)) : Prop := pairwise_on s disjoint lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t) (ht : pairwise_disjoint t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y), intro h, apply hxy, apply congr_arg f, exact subtype.eq h end /- classical -/ lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩ end set namespace set variables (t : α → set β) lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := ⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩, λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩ /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma sigma_to_Union_surjective : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩ lemma sigma_to_Union_injective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma sigma_to_Union_bijective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩ /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) := (equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $ assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq end set
3a027cd3120af9eec61db560b6177bb12d4c7872
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/mellin_transform.lean
ac6518d306041b4941b7e41496a6aca2f5dfefb0
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
25,627
lean
/- Copyright (c) 2023 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import analysis.special_functions.improper_integrals import analysis.calculus.parametric_integral import measure_theory.measure.haar.normed_space /-! # The Mellin transform > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the Mellin transform of a locally integrable function on `Ioi 0`, and show it is differentiable in a suitable vertical strip. ## Main statements - `mellin` : the Mellin transform `∫ (t : ℝ) in Ioi 0, t ^ (s - 1) • f t`, where `s` is a complex number. - `has_mellin`: shorthand asserting that the Mellin transform exists and has a given value (analogous to `has_sum`). - `mellin_differentiable_at_of_is_O_rpow` : if `f` is `O(x ^ (-a))` at infinity, and `O(x ^ (-b))` at 0, then `mellin f` is holomorphic on the domain `b < re s < a`. -/ open measure_theory set filter asymptotics topological_space namespace complex /- Porting note: move this to `analysis.special_functions.pow.complex` -/ lemma cpow_mul_of_real_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) (z : ℂ) : (x : ℂ) ^ (↑y * z) = (↑(x ^ y) : ℂ) ^ z := begin rw [cpow_mul, of_real_cpow hx], { rw [←of_real_log hx, ←of_real_mul, of_real_im, neg_lt_zero], exact real.pi_pos }, { rw [←of_real_log hx, ←of_real_mul, of_real_im], exact real.pi_pos.le }, end end complex open real complex (hiding exp log abs_of_nonneg) open_locale topology noncomputable theory section defs variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E] /-- Predicate on `f` and `s` asserting that the Mellin integral is well-defined. -/ def mellin_convergent (f : ℝ → E) (s : ℂ) : Prop := integrable_on (λ t : ℝ, (t : ℂ) ^ (s - 1) • f t) (Ioi 0) lemma mellin_convergent.const_smul {f : ℝ → E} {s : ℂ} (hf : mellin_convergent f s) {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℂ 𝕜 E] (c : 𝕜) : mellin_convergent (λ t, c • f t) s := by simpa only [mellin_convergent, smul_comm] using hf.smul c lemma mellin_convergent.cpow_smul {f : ℝ → E} {s a : ℂ} : mellin_convergent (λ t, (t : ℂ) ^ a • f t) s ↔ mellin_convergent f (s + a) := begin refine integrable_on_congr_fun (λ t ht, _) measurable_set_Ioi, simp_rw [←sub_add_eq_add_sub, cpow_add _ _ (of_real_ne_zero.2 $ ne_of_gt ht), mul_smul], end lemma mellin_convergent.div_const {f : ℝ → ℂ} {s : ℂ} (hf : mellin_convergent f s) (a : ℂ) : mellin_convergent (λ t, f t / a) s := by simpa only [mellin_convergent, smul_eq_mul, ←mul_div_assoc] using hf.div_const a lemma mellin_convergent.comp_mul_left {f : ℝ → E} {s : ℂ} {a : ℝ} (ha : 0 < a) : mellin_convergent (λ t, f (a * t)) s ↔ mellin_convergent f s := begin have := integrable_on_Ioi_comp_mul_left_iff (λ t : ℝ, (t : ℂ) ^ (s - 1) • f t) 0 ha, rw mul_zero at this, have h1 : eq_on (λ t : ℝ, (↑(a * t) : ℂ) ^ (s - 1) • f (a * t)) ((a : ℂ) ^ (s - 1) • (λ t : ℝ, (t : ℂ) ^ (s - 1) • f (a * t))) (Ioi 0), { intros t ht, simp only [of_real_mul, mul_cpow_of_real_nonneg ha.le (le_of_lt ht), mul_smul, pi.smul_apply] }, have h2 : (a : ℂ) ^ (s - 1) ≠ 0, { rw [ne.def, cpow_eq_zero_iff, not_and_distrib, of_real_eq_zero], exact or.inl ha.ne' }, simp_rw [mellin_convergent, ←this, integrable_on_congr_fun h1 measurable_set_Ioi, integrable_on, integrable_smul_iff h2], end lemma mellin_convergent.comp_rpow {f : ℝ → E} {s : ℂ} {a : ℝ} (ha : a ≠ 0) : mellin_convergent (λ t, f (t ^ a)) s ↔ mellin_convergent f (s / a) := begin simp_rw mellin_convergent, letI u : normed_space ℝ E := normed_space.complex_to_real, -- why isn't this automatic? conv_rhs { rw ←@integrable_on_Ioi_comp_rpow_iff' _ _ u _ a ha }, refine integrable_on_congr_fun (λ t ht, _) measurable_set_Ioi, dsimp only [pi.smul_apply], rw [←complex.coe_smul (t ^ (a - 1)), ←mul_smul, ←cpow_mul_of_real_nonneg (le_of_lt ht), of_real_cpow (le_of_lt ht), ←cpow_add _ _ (of_real_ne_zero.mpr (ne_of_gt ht)), of_real_sub, of_real_one, mul_sub, mul_div_cancel' _ (of_real_ne_zero.mpr ha), mul_one, add_comm, ←add_sub_assoc, sub_add_cancel], end variables [complete_space E] /-- The Mellin transform of a function `f` (for a complex exponent `s`), defined as the integral of `t ^ (s - 1) • f` over `Ioi 0`. -/ def mellin (f : ℝ → E) (s : ℂ) : E := ∫ t : ℝ in Ioi 0, (t : ℂ) ^ (s - 1) • f t -- next few lemmas don't require convergence of the Mellin transform (they are just 0 = 0 otherwise) lemma mellin_cpow_smul (f : ℝ → E) (s a : ℂ) : mellin (λ t, (t : ℂ) ^ a • f t) s = mellin f (s + a) := begin refine set_integral_congr measurable_set_Ioi (λ t ht, _), simp_rw [←sub_add_eq_add_sub, cpow_add _ _ (of_real_ne_zero.2 $ ne_of_gt ht), mul_smul], end lemma mellin_const_smul (f : ℝ → E) (s : ℂ) {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℂ 𝕜 E] (c : 𝕜) : mellin (λ t, c • f t) s = c • mellin f s := by simp only [mellin, smul_comm, integral_smul] lemma mellin_div_const (f : ℝ → ℂ) (s a : ℂ) : mellin (λ t, f t / a) s = mellin f s / a := by simp_rw [mellin, smul_eq_mul, ←mul_div_assoc, integral_div] lemma mellin_comp_rpow (f : ℝ → E) (s : ℂ) {a : ℝ} (ha : a ≠ 0) : mellin (λ t, f (t ^ a)) s = |a|⁻¹ • mellin f (s / a) := begin -- note: this is also true for a = 0 (both sides are zero), but this is mathematically -- uninteresting and rather time-consuming to check simp_rw mellin, conv_rhs { rw [←integral_comp_rpow_Ioi _ ha, ←integral_smul] }, refine set_integral_congr measurable_set_Ioi (λ t ht, _), dsimp only, rw [←mul_smul, ←mul_assoc, inv_mul_cancel, one_mul, ←smul_assoc, real_smul], show |a| ≠ 0, { contrapose! ha, exact abs_eq_zero.mp ha }, rw [of_real_cpow (le_of_lt ht), ←cpow_mul_of_real_nonneg (le_of_lt ht), ←cpow_add _ _ (of_real_ne_zero.mpr $ ne_of_gt ht), of_real_sub, of_real_one, mul_sub, mul_div_cancel' _ (of_real_ne_zero.mpr ha), add_comm, ←add_sub_assoc, mul_one, sub_add_cancel] end lemma mellin_comp_mul_left (f : ℝ → E) (s : ℂ) {a : ℝ} (ha : 0 < a) : mellin (λ t, f (a * t)) s = (a : ℂ) ^ (-s) • mellin f s := begin simp_rw mellin, have : eq_on (λ t : ℝ, (t : ℂ) ^ (s - 1) • f (a * t)) (λ t : ℝ, (a : ℂ) ^ (1 - s) • (λ u : ℝ, (u : ℂ) ^ (s - 1) • f u) (a * t)) (Ioi 0), { intros t ht, dsimp only, rw [of_real_mul, mul_cpow_of_real_nonneg ha.le (le_of_lt ht), ←mul_smul, (by ring : 1 - s = -(s - 1)), cpow_neg, inv_mul_cancel_left₀], rw [ne.def, cpow_eq_zero_iff, of_real_eq_zero, not_and_distrib], exact or.inl ha.ne' }, rw [set_integral_congr measurable_set_Ioi this, integral_smul, integral_comp_mul_left_Ioi _ _ ha, mul_zero, ←complex.coe_smul, ←mul_smul, sub_eq_add_neg, cpow_add _ _ (of_real_ne_zero.mpr ha.ne'), cpow_one, abs_of_pos (inv_pos.mpr ha), of_real_inv, mul_assoc, mul_comm, inv_mul_cancel_right₀ (of_real_ne_zero.mpr ha.ne')] end lemma mellin_comp_mul_right (f : ℝ → E) (s : ℂ) {a : ℝ} (ha : 0 < a) : mellin (λ t, f (t * a)) s = (a : ℂ) ^ (-s) • mellin f s := by simpa only [mul_comm] using mellin_comp_mul_left f s ha lemma mellin_comp_inv (f : ℝ → E) (s : ℂ) : mellin (λ t, f (t⁻¹)) s = mellin f (-s) := by simp_rw [←rpow_neg_one, mellin_comp_rpow _ _ (neg_ne_zero.mpr one_ne_zero), abs_neg, abs_one, inv_one, one_smul, of_real_neg, of_real_one, div_neg, div_one] /-- Predicate standing for "the Mellin transform of `f` is defined at `s` and equal to `m`". This shortens some arguments. -/ def has_mellin (f : ℝ → E) (s : ℂ) (m : E) : Prop := mellin_convergent f s ∧ mellin f s = m lemma has_mellin_add {f g : ℝ → E} {s : ℂ} (hf : mellin_convergent f s) (hg : mellin_convergent g s) : has_mellin (λ t, f t + g t) s (mellin f s + mellin g s) := ⟨by simpa only [mellin_convergent, smul_add] using hf.add hg, by simpa only [mellin, smul_add] using integral_add hf hg⟩ lemma has_mellin_sub {f g : ℝ → E} {s : ℂ} (hf : mellin_convergent f s) (hg : mellin_convergent g s) : has_mellin (λ t, f t - g t) s (mellin f s - mellin g s) := ⟨by simpa only [mellin_convergent, smul_sub] using hf.sub hg, by simpa only [mellin, smul_sub] using integral_sub hf hg⟩ end defs variables {E : Type*} [normed_add_comm_group E] section mellin_convergent /-! ## Convergence of Mellin transform integrals -/ /-- Auxiliary lemma to reduce convergence statements from vector-valued functions to real scalar-valued functions. -/ lemma mellin_convergent_iff_norm [normed_space ℂ E] {f : ℝ → E} {T : set ℝ} (hT : T ⊆ Ioi 0) (hT' : measurable_set T) (hfc : ae_strongly_measurable f $ volume.restrict $ Ioi 0) {s : ℂ} : integrable_on (λ t : ℝ, (t : ℂ) ^ (s - 1) • f t) T ↔ integrable_on (λ t : ℝ, t ^ (s.re - 1) * ‖f t‖) T := begin have : ae_strongly_measurable (λ t : ℝ, (t : ℂ) ^ (s - 1) • f t) (volume.restrict T), { refine ((continuous_at.continuous_on _).ae_strongly_measurable hT').smul (hfc.mono_set hT), exact λ t ht, continuous_at_of_real_cpow_const _ _ (or.inr $ ne_of_gt (hT ht)) }, rw [integrable_on, ←integrable_norm_iff this, ←integrable_on], refine integrable_on_congr_fun (λ t ht, _) hT', simp_rw [norm_smul, complex.norm_eq_abs, abs_cpow_eq_rpow_re_of_pos (hT ht), sub_re, one_re], end /-- If `f` is a locally integrable real-valued function which is `O(x ^ (-a))` at `∞`, then for any `s < a`, its Mellin transform converges on some neighbourhood of `+∞`. -/ lemma mellin_convergent_top_of_is_O {f : ℝ → ℝ} (hfc : ae_strongly_measurable f $ volume.restrict (Ioi 0)) {a s : ℝ} (hf : is_O at_top f (λ t, t ^ (-a))) (hs : s < a) : ∃ (c : ℝ), 0 < c ∧ integrable_on (λ t : ℝ, t ^ (s - 1) * f t) (Ioi c) := begin obtain ⟨d, hd, hd'⟩ := hf.exists_pos, simp_rw [is_O_with, eventually_at_top] at hd', obtain ⟨e, he⟩ := hd', have he' : 0 < max e 1, from zero_lt_one.trans_le (le_max_right _ _), refine ⟨max e 1, he', _, _⟩, { refine ae_strongly_measurable.mul _ (hfc.mono_set (Ioi_subset_Ioi he'.le)), refine (continuous_at.continuous_on (λ t ht, _)).ae_strongly_measurable measurable_set_Ioi, exact continuous_at_rpow_const _ _ (or.inl $ (he'.trans ht).ne') }, { have : ∀ᵐ (t : ℝ) ∂volume.restrict (Ioi $ max e 1), ‖t ^ (s - 1) * f t‖ ≤ t ^ ((s - 1) + -a) * d, { refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ t ht, _)), have ht' : 0 < t, from he'.trans ht, rw [norm_mul, rpow_add ht', ←norm_of_nonneg (rpow_nonneg_of_nonneg ht'.le (-a)), mul_assoc, mul_comm _ d, norm_of_nonneg (rpow_nonneg_of_nonneg ht'.le _)], exact mul_le_mul_of_nonneg_left (he t ((le_max_left e 1).trans_lt ht).le) (rpow_pos_of_pos ht' _).le }, refine (has_finite_integral.mul_const _ _).mono' this, exact (integrable_on_Ioi_rpow_of_lt (by linarith) he').has_finite_integral } end /-- If `f` is a locally integrable real-valued function which is `O(x ^ (-b))` at `0`, then for any `b < s`, its Mellin transform converges on some right neighbourhood of `0`. -/ lemma mellin_convergent_zero_of_is_O {b : ℝ} {f : ℝ → ℝ} (hfc : ae_strongly_measurable f $ volume.restrict (Ioi 0)) (hf : is_O (𝓝[>] 0) f (λ t, t ^ (-b))) {s : ℝ} (hs : b < s) : ∃ (c : ℝ), 0 < c ∧ integrable_on (λ t : ℝ, t ^ (s - 1) * f t) (Ioc 0 c) := begin obtain ⟨d, hd, hd'⟩ := hf.exists_pos, simp_rw [is_O_with, eventually_nhds_within_iff, metric.eventually_nhds_iff, gt_iff_lt] at hd', obtain ⟨ε, hε, hε'⟩ := hd', refine ⟨ε, hε, integrable_on_Ioc_iff_integrable_on_Ioo.mpr ⟨_, _⟩⟩, { refine ae_strongly_measurable.mul _ (hfc.mono_set Ioo_subset_Ioi_self), refine (continuous_at.continuous_on (λ t ht, _)).ae_strongly_measurable measurable_set_Ioo, exact continuous_at_rpow_const _ _ (or.inl ht.1.ne') }, { apply has_finite_integral.mono', { show has_finite_integral (λ t, d * t ^ (s - b - 1)) _, refine (integrable.has_finite_integral _).const_mul _, rw [←integrable_on, ←integrable_on_Ioc_iff_integrable_on_Ioo, ←interval_integrable_iff_integrable_Ioc_of_le hε.le], exact interval_integral.interval_integrable_rpow' (by linarith) }, { refine (ae_restrict_iff' measurable_set_Ioo).mpr (eventually_of_forall $ λ t ht, _), rw [mul_comm, norm_mul], specialize hε' _ ht.1, { rw [dist_eq_norm, sub_zero, norm_of_nonneg (le_of_lt ht.1)], exact ht.2 }, { refine (mul_le_mul_of_nonneg_right hε' (norm_nonneg _)).trans _, simp_rw [norm_of_nonneg (rpow_nonneg_of_nonneg (le_of_lt ht.1) _), mul_assoc], refine mul_le_mul_of_nonneg_left (le_of_eq _) hd.le, rw ←rpow_add ht.1, congr' 1, abel } } }, end /-- If `f` is a locally integrable real-valued function on `Ioi 0` which is `O(x ^ (-a))` at `∞` and `O(x ^ (-b))` at `0`, then its Mellin transform integral converges for `b < s < a`. -/ lemma mellin_convergent_of_is_O_scalar {a b : ℝ} {f : ℝ → ℝ} {s : ℝ} (hfc : locally_integrable_on f $ Ioi 0) (hf_top : is_O at_top f (λ t, t ^ (-a))) (hs_top : s < a) (hf_bot : is_O (𝓝[>] 0) f (λ t, t ^ (-b))) (hs_bot : b < s) : integrable_on (λ t : ℝ, t ^ (s - 1) * f t) (Ioi 0) := begin obtain ⟨c1, hc1, hc1'⟩ := mellin_convergent_top_of_is_O hfc.ae_strongly_measurable hf_top hs_top, obtain ⟨c2, hc2, hc2'⟩ := mellin_convergent_zero_of_is_O hfc.ae_strongly_measurable hf_bot hs_bot, have : Ioi 0 = Ioc 0 c2 ∪ Ioc c2 c1 ∪ Ioi c1, { rw [union_assoc, Ioc_union_Ioi (le_max_right _ _), Ioc_union_Ioi ((min_le_left _ _).trans (le_max_right _ _)), min_eq_left (lt_min hc2 hc1).le] }, rw [this, integrable_on_union, integrable_on_union], refine ⟨⟨hc2', integrable_on_Icc_iff_integrable_on_Ioc.mp _⟩, hc1'⟩, refine (hfc.continuous_on_mul _ is_open_Ioi).integrable_on_compact_subset (λ t ht, (hc2.trans_le ht.1 : 0 < t)) is_compact_Icc, exact continuous_at.continuous_on (λ t ht, continuous_at_rpow_const _ _ $ or.inl $ ne_of_gt ht), end lemma mellin_convergent_of_is_O_rpow [normed_space ℂ E] {a b : ℝ} {f : ℝ → E} {s : ℂ} (hfc : locally_integrable_on f $ Ioi 0) (hf_top : is_O at_top f (λ t, t ^ (-a))) (hs_top : s.re < a) (hf_bot : is_O (𝓝[>] 0) f (λ t, t ^ (-b))) (hs_bot : b < s.re) : mellin_convergent f s := begin rw [mellin_convergent, mellin_convergent_iff_norm (subset_refl _) measurable_set_Ioi hfc.ae_strongly_measurable], exact mellin_convergent_of_is_O_scalar hfc.norm hf_top.norm_left hs_top hf_bot.norm_left hs_bot, end end mellin_convergent section mellin_diff /-- If `f` is `O(x ^ (-a))` as `x → +∞`, then `log • f` is `O(x ^ (-b))` for every `b < a`. -/ lemma is_O_rpow_top_log_smul [normed_space ℝ E] {a b : ℝ} {f : ℝ → E} (hab : b < a) (hf : is_O at_top f (λ t, t ^ (-a))) : is_O at_top (λ t : ℝ, log t • f t) (λ t, t ^ (-b)) := begin refine ((is_o_log_rpow_at_top (sub_pos.mpr hab)).is_O.smul hf).congr' (eventually_of_forall (λ t, by refl)) ((eventually_gt_at_top 0).mp (eventually_of_forall (λ t ht, _))), rw [smul_eq_mul, ←rpow_add ht, ←sub_eq_add_neg, sub_eq_add_neg a, add_sub_cancel'], end /-- If `f` is `O(x ^ (-a))` as `x → 0`, then `log • f` is `O(x ^ (-b))` for every `a < b`. -/ lemma is_O_rpow_zero_log_smul [normed_space ℝ E] {a b : ℝ} {f : ℝ → E} (hab : a < b) (hf : is_O (𝓝[>] 0) f (λ t, t ^ (-a))) : is_O (𝓝[>] 0) (λ t : ℝ, log t • f t) (λ t, t ^ (-b)) := begin have : is_o (𝓝[>] 0) log (λ t : ℝ, t ^ (a - b)), { refine ((is_o_log_rpow_at_top (sub_pos.mpr hab)).neg_left.comp_tendsto tendsto_inv_zero_at_top).congr' (eventually_nhds_within_iff.mpr $ eventually_of_forall (λ t ht, _)) (eventually_nhds_within_iff.mpr $ eventually_of_forall (λ t ht, _)), { simp_rw [function.comp_app, ←one_div, log_div one_ne_zero (ne_of_gt ht), real.log_one, zero_sub, neg_neg] }, { simp_rw [function.comp_app, inv_rpow (le_of_lt ht), ←rpow_neg (le_of_lt ht), neg_sub] } }, refine (this.is_O.smul hf).congr' (eventually_of_forall (λ t, by refl)) (eventually_nhds_within_iff.mpr (eventually_of_forall (λ t ht, _))), simp_rw [smul_eq_mul, ←rpow_add ht], congr' 1, abel, end /-- Suppose `f` is locally integrable on `(0, ∞)`, is `O(x ^ (-a))` as `x → ∞`, and is `O(x ^ (-b))` as `x → 0`. Then its Mellin transform is differentiable on the domain `b < re s < a`, with derivative equal to the Mellin transform of `log • f`. -/ theorem mellin_has_deriv_of_is_O_rpow [complete_space E] [normed_space ℂ E] {a b : ℝ} {f : ℝ → E} {s : ℂ} (hfc : locally_integrable_on f $ Ioi 0) (hf_top : is_O at_top f (λ t, t ^ (-a))) (hs_top : s.re < a) (hf_bot : is_O (𝓝[>] 0) f (λ t, t ^ (-b))) (hs_bot : b < s.re) : mellin_convergent (λ t, log t • f t) s ∧ has_deriv_at (mellin f) (mellin (λ t, log t • f t) s) s := begin let F : ℂ → ℝ → E := λ z t, (t : ℂ) ^ (z - 1) • f t, let F' : ℂ → ℝ → E := λ z t, ((t : ℂ) ^ (z - 1) * log t) • f t, have hab : b < a := hs_bot.trans hs_top, -- A convenient radius of ball within which we can uniformly bound the derivative. obtain ⟨v, hv0, hv1, hv2⟩ : ∃ (v : ℝ), (0 < v) ∧ (v < s.re - b) ∧ (v < a - s.re), { obtain ⟨w, hw1, hw2⟩ := exists_between (sub_pos.mpr hs_top), obtain ⟨w', hw1', hw2'⟩ := exists_between (sub_pos.mpr hs_bot), exact ⟨min w w', lt_min hw1 hw1', (min_le_right _ _).trans_lt hw2', (min_le_left _ _).trans_lt hw2⟩ }, let bound : ℝ → ℝ := λ t : ℝ, (t ^ (s.re + v - 1) + t ^ (s.re - v - 1)) * |log t| * ‖f t‖, have h1 : ∀ᶠ (z : ℂ) in 𝓝 s, ae_strongly_measurable (F z) (volume.restrict $ Ioi 0), { refine eventually_of_forall (λ z, ae_strongly_measurable.smul _ hfc.ae_strongly_measurable), refine continuous_on.ae_strongly_measurable _ measurable_set_Ioi, refine continuous_at.continuous_on (λ t ht, _), exact (continuous_at_of_real_cpow_const _ _ (or.inr $ ne_of_gt ht)), }, have h2 : integrable_on (F s) (Ioi 0), { exact mellin_convergent_of_is_O_rpow hfc hf_top hs_top hf_bot hs_bot }, have h3 : ae_strongly_measurable (F' s) (volume.restrict $ Ioi 0), { apply locally_integrable_on.ae_strongly_measurable, refine hfc.continuous_on_smul is_open_Ioi ((continuous_at.continuous_on (λ t ht, _)).mul _), { exact continuous_at_of_real_cpow_const _ _ (or.inr $ ne_of_gt ht) }, { refine continuous_of_real.comp_continuous_on _, exact continuous_on_log.mono (subset_compl_singleton_iff.mpr not_mem_Ioi_self) } }, have h4 : (∀ᵐ (t : ℝ) ∂volume.restrict (Ioi 0), ∀ (z : ℂ), z ∈ metric.ball s v → ‖F' z t‖ ≤ bound t), { refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ $ λ t ht z hz, _), simp_rw [bound, F', norm_smul, norm_mul, complex.norm_eq_abs (log _), complex.abs_of_real, mul_assoc], refine mul_le_mul_of_nonneg_right _ (mul_nonneg (abs_nonneg _) (norm_nonneg _)), rw [complex.norm_eq_abs, abs_cpow_eq_rpow_re_of_pos ht], rcases le_or_lt 1 t, { refine le_add_of_le_of_nonneg (rpow_le_rpow_of_exponent_le h _) (rpow_nonneg_of_nonneg (zero_le_one.trans h) _), rw [sub_re, one_re, sub_le_sub_iff_right], rw [mem_ball_iff_norm, complex.norm_eq_abs] at hz, have hz' := (re_le_abs _).trans hz.le, rwa [sub_re, sub_le_iff_le_add'] at hz' }, { refine le_add_of_nonneg_of_le (rpow_pos_of_pos ht _).le (rpow_le_rpow_of_exponent_ge ht h.le _), rw [sub_re, one_re, sub_le_iff_le_add, sub_add_cancel], rw [mem_ball_iff_norm', complex.norm_eq_abs] at hz, have hz' := (re_le_abs _).trans hz.le, rwa [sub_re, sub_le_iff_le_add, ←sub_le_iff_le_add'] at hz', } }, have h5 : integrable_on bound (Ioi 0), { simp_rw [bound, add_mul, mul_assoc], suffices : ∀ {j : ℝ} (hj : b < j) (hj' : j < a), integrable_on (λ (t : ℝ), t ^ (j - 1) * (|log t| * ‖f t‖)) (Ioi 0) volume, { refine integrable.add (this _ _) (this _ _), all_goals { linarith } }, { intros j hj hj', obtain ⟨w, hw1, hw2⟩ := exists_between hj, obtain ⟨w', hw1', hw2'⟩ := exists_between hj', refine mellin_convergent_of_is_O_scalar _ _ hw1' _ hw2, { simp_rw mul_comm, refine hfc.norm.mul_continuous_on _ is_open_Ioi, refine continuous.comp_continuous_on continuous_abs (continuous_on_log.mono _), exact subset_compl_singleton_iff.mpr not_mem_Ioi_self }, { refine (is_O_rpow_top_log_smul hw2' hf_top).norm_left.congr' _ (eventually_eq.refl _ _), refine (eventually_gt_at_top 0).mp (eventually_of_forall (λ t ht, _)), simp only [norm_smul, real.norm_eq_abs] }, { refine (is_O_rpow_zero_log_smul hw1 hf_bot).norm_left.congr' _ (eventually_eq.refl _ _), refine eventually_nhds_within_iff.mpr (eventually_of_forall (λ t ht, _)), simp only [norm_smul, real.norm_eq_abs] } } }, have h6 : ∀ᵐ (t : ℝ) ∂volume.restrict (Ioi 0), ∀ (y : ℂ), y ∈ metric.ball s v → has_deriv_at (λ (z : ℂ), F z t) (F' y t) y, { dsimp only [F, F'], refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ $ λ t ht y hy, _), have ht' : (t : ℂ) ≠ 0 := of_real_ne_zero.mpr (ne_of_gt ht), have u1 : has_deriv_at (λ z : ℂ, (t : ℂ) ^ (z - 1)) (t ^ (y - 1) * log t) y, { convert ((has_deriv_at_id' y).sub_const 1).const_cpow (or.inl ht') using 1, rw of_real_log (le_of_lt ht), ring }, exact u1.smul_const (f t) }, have main := has_deriv_at_integral_of_dominated_loc_of_deriv_le hv0 h1 h2 h3 h4 h5 h6, exact ⟨by simpa only [F', mul_smul] using main.1, by simpa only [F', mul_smul] using main.2⟩ end /-- Suppose `f` is locally integrable on `(0, ∞)`, is `O(x ^ (-a))` as `x → ∞`, and is `O(x ^ (-b))` as `x → 0`. Then its Mellin transform is differentiable on the domain `b < re s < a`. -/ lemma mellin_differentiable_at_of_is_O_rpow [complete_space E] [normed_space ℂ E] {a b : ℝ} {f : ℝ → E} {s : ℂ} (hfc : locally_integrable_on f $ Ioi 0) (hf_top : is_O at_top f (λ t, t ^ (-a))) (hs_top : s.re < a) (hf_bot : is_O (𝓝[>] 0) f (λ t, t ^ (-b))) (hs_bot : b < s.re) : differentiable_at ℂ (mellin f) s := (mellin_has_deriv_of_is_O_rpow hfc hf_top hs_top hf_bot hs_bot).2.differentiable_at end mellin_diff section exp_decay /-- If `f` is locally integrable, decays exponentially at infinity, and is `O(x ^ (-b))` at 0, then its Mellin transform converges for `b < s.re`. -/ lemma mellin_convergent_of_is_O_rpow_exp [normed_space ℂ E] {a b : ℝ} (ha : 0 < a) {f : ℝ → E} {s : ℂ} (hfc : locally_integrable_on f $ Ioi 0) (hf_top : is_O at_top f (λ t, exp (-a * t))) (hf_bot : is_O (𝓝[>] 0) f (λ t, t ^ (-b))) (hs_bot : b < s.re) : mellin_convergent f s := mellin_convergent_of_is_O_rpow hfc (hf_top.trans (is_o_exp_neg_mul_rpow_at_top ha _).is_O) (lt_add_one _) hf_bot hs_bot /-- If `f` is locally integrable, decays exponentially at infinity, and is `O(x ^ (-b))` at 0, then its Mellin transform is holomorphic on `b < s.re`. -/ lemma mellin_differentiable_at_of_is_O_rpow_exp [complete_space E] [normed_space ℂ E] {a b : ℝ} (ha : 0 < a) {f : ℝ → E} {s : ℂ} (hfc : locally_integrable_on f $ Ioi 0) (hf_top : is_O at_top f (λ t, exp (-a * t))) (hf_bot : is_O (𝓝[>] 0) f (λ t, t ^ (-b))) (hs_bot : b < s.re) : differentiable_at ℂ (mellin f) s := mellin_differentiable_at_of_is_O_rpow hfc (hf_top.trans (is_o_exp_neg_mul_rpow_at_top ha _).is_O) (lt_add_one _) hf_bot hs_bot end exp_decay section mellin_Ioc /-! ## Mellin transforms of functions on `Ioc 0 1` -/ /-- The Mellin transform of the indicator function of `Ioc 0 1`. -/ lemma has_mellin_one_Ioc {s : ℂ} (hs : 0 < re s) : has_mellin (indicator (Ioc 0 1) (λ t, 1 : ℝ → ℂ)) s (1 / s) := begin have aux1 : -1 < (s - 1).re, by simpa only [sub_re, one_re, sub_eq_add_neg] using lt_add_of_pos_left _ hs, have aux2 : s ≠ 0, by { contrapose! hs, rw [hs, zero_re] }, have aux3 : measurable_set (Ioc (0 : ℝ) 1), from measurable_set_Ioc, simp_rw [has_mellin, mellin, mellin_convergent, ←indicator_smul, integrable_on, integrable_indicator_iff aux3, smul_eq_mul, integral_indicator aux3, mul_one, integrable_on, measure.restrict_restrict_of_subset Ioc_subset_Ioi_self], rw [←integrable_on, ←interval_integrable_iff_integrable_Ioc_of_le zero_le_one], refine ⟨interval_integral.interval_integrable_cpow' aux1, _⟩, rw [←interval_integral.integral_of_le zero_le_one, integral_cpow (or.inl aux1), sub_add_cancel, of_real_zero, of_real_one, one_cpow, zero_cpow aux2, sub_zero] end /-- The Mellin transform of a power function restricted to `Ioc 0 1`. -/ lemma has_mellin_cpow_Ioc (a : ℂ) {s : ℂ} (hs : 0 < re s + re a) : has_mellin (indicator (Ioc 0 1) (λ t, ↑t ^ a : ℝ → ℂ)) s (1 / (s + a)) := begin have := has_mellin_one_Ioc (by rwa add_re : 0 < (s + a).re), simp_rw [has_mellin, ←mellin_convergent.cpow_smul, ←mellin_cpow_smul, ←indicator_smul, smul_eq_mul, mul_one] at this, exact this end end mellin_Ioc
a1f499ac044e27460a4ffffc6bbe90072137eea8
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/group/to_additive.lean
ebfed29a298dddaebb56470dccf7ec9cfd4e0261
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,144
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov, Floris van Doorn -/ import tactic.transform_decl import tactic.algebra /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. Usage information is contained in the doc string of `to_additive.attr`. ### Missing features * Automatically transport structures and other inductive types. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. -/ namespace to_additive open tactic setup_tactic_parser section performance_hack -- see Note [user attribute parameters] local attribute [semireducible] reflected /-- Temporarily change the `has_reflect` instance for `name`. -/ local attribute [instance, priority 9000] meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) /-- An auxiliary attribute used to store the names of the additive versions of declarations that have been processed by `to_additive`. -/ @[user_attribute] meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", parser := failed, cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', do let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end, param ← aux_attr.get_param_untyped n', pure $ dict.insert n param.app_arg.const_name) mk_name_map, []⟩ } end performance_hack section extra_attributes /-- An attribute that tells `@[to_additive]` that certain arguments of this definition are not involved when using `@[to_additive]`. This helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another fixed type occurs as one of these arguments. -/ @[user_attribute] meta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_ignore_args, descr := "Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := (lean.parser.small_nat)* } /-- An attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed. This attribute tells which argument is the type where this declaration uses the multiplicative structure. If there are multiple argument, we typically tag the first one. If this argument contains a fixed type, this declaration will note be additivized. See the Heuristics section of `to_additive.attr` for more details. If a declaration is not tagged, it is presumed that the first argument is relevant. `@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag declarations. It is ok to update it manually if the automatic tagging made an error. Implementation note: we only allow exactly 1 relevant argument, even though some declarations (like `prod.group`) have multiple arguments with a multiplicative structure on it. The reason is that whether we additivize a declaration is an all-or-nothing decision, and if we will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α` anyway. Warning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this attribute is currently not supported. -/ @[user_attribute] meta def relevant_arg_attr : user_attribute (name_map ℕ) ℕ := { name := `to_additive_relevant_arg, descr := "Auxiliary attribute for `to_additive` stating which arguments are the types with a " ++ "multiplicative structure.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← relevant_arg_attr.get_param_untyped n, -- see Note [user attribute parameters] -- we subtract 1 from the values provided by the user. return $ dict.insert n $ param.to_nat.iget.pred) mk_name_map, []⟩, parser := lean.parser.small_nat } /-- An attribute that stores all the declarations that needs their arguments reordered when applying `@[to_additive]`. Currently, we only support swapping consecutive arguments. The list of the natural numbers contains the positions of the first of the two arguments to be swapped. If the first two arguments are swapped, the first two universe variables are also swapped. Example: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in positions 4 and 5. -/ @[user_attribute] meta def reorder_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_reorder, descr := "Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← reorder_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := do l ← (lean.parser.small_nat)*, guard (l.all (≠ 0)) <|> exceptional.fail "The reorder positions must be positive", return l } end extra_attributes /-- Find the first argument of `nm` that has a multiplicative type-class on it. Returns 1 if there are no types with a multiplicative class as arguments. E.g. `prod.group` returns 1, and `pi.has_one` returns 2. -/ meta def first_multiplicative_arg (nm : name) : tactic ℕ := do d ← get_decl nm, let (es, _) := d.type.pi_binders, l ← es.mmap_with_index $ λ n bi, do { let tgt := bi.type.pi_codomain, let n_bi := bi.type.pi_binders.fst.length, tt ← has_attribute' `to_additive tgt.get_app_fn.const_name | return none, let n2 := tgt.get_app_args.head.get_app_fn.match_var.map $ λ m, n + n_bi - m, return $ n2 }, let l := l.reduce_option, return $ if l = [] then 1 else l.foldr min l.head /-- A command that can be used to have future uses of `to_additive` change the `src` namespace to the `tgt` namespace. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. -/ meta def map_namespace (src tgt : name) : command := do let n := src.mk_string "_to_additive", let decl := declaration.thm n [] `(unit) (pure (reflect ())), add_decl decl, aux_attr.set n tgt tt /-- `value_type` is the type of the arguments that can be provided to `to_additive`. `to_additive.parser` parses the provided arguments: * `replace_all`: replace all multiplicative declarations, do not use the heuristic. * `trace`: output the generated additive declaration. * `tgt : name`: the name of the target (the additive declaration). * `doc`: an optional doc string. * if `allow_auto_name` is `ff` (default) then `@[to_additive]` will check whether the given name can be auto-generated. -/ @[derive has_reflect, derive inhabited] structure value_type : Type := (replace_all : bool) (trace : bool) (tgt : name) (doc : option string) (allow_auto_name : bool) /-- `add_comm_prefix x s` returns `"comm_" ++ s` if `x = tt` and `s` otherwise. -/ meta def add_comm_prefix : bool → string → string | tt s := "comm_" ++ s | ff s := s /-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/ meta def tr : bool → list string → list string | is_comm ("one" :: "le" :: s) := add_comm_prefix is_comm "nonneg" :: tr ff s | is_comm ("one" :: "lt" :: s) := add_comm_prefix is_comm "pos" :: tr ff s | is_comm ("le" :: "one" :: s) := add_comm_prefix is_comm "nonpos" :: tr ff s | is_comm ("lt" :: "one" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("mul" :: "support" :: s) := add_comm_prefix is_comm "support" :: tr ff s | is_comm ("mul" :: "indicator" :: s) := add_comm_prefix is_comm "indicator" :: tr ff s | is_comm ("mul" :: s) := add_comm_prefix is_comm "add" :: tr ff s | is_comm ("smul" :: s) := add_comm_prefix is_comm "vadd" :: tr ff s | is_comm ("inv" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("div" :: s) := add_comm_prefix is_comm "sub" :: tr ff s | is_comm ("one" :: s) := add_comm_prefix is_comm "zero" :: tr ff s | is_comm ("prod" :: s) := add_comm_prefix is_comm "sum" :: tr ff s | is_comm ("finprod" :: s) := add_comm_prefix is_comm "finsum" :: tr ff s | is_comm ("npow" :: s) := add_comm_prefix is_comm "nsmul" :: tr ff s | is_comm ("gpow" :: s) := add_comm_prefix is_comm "gsmul" :: tr ff s | is_comm ("monoid" :: s) := ("add_" ++ add_comm_prefix is_comm "monoid") :: tr ff s | is_comm ("submonoid" :: s) := ("add_" ++ add_comm_prefix is_comm "submonoid") :: tr ff s | is_comm ("group" :: s) := ("add_" ++ add_comm_prefix is_comm "group") :: tr ff s | is_comm ("subgroup" :: s) := ("add_" ++ add_comm_prefix is_comm "subgroup") :: tr ff s | is_comm ("semigroup" :: s) := ("add_" ++ add_comm_prefix is_comm "semigroup") :: tr ff s | is_comm ("magma" :: s) := ("add_" ++ add_comm_prefix is_comm "magma") :: tr ff s | is_comm ("haar" :: s) := ("add_" ++ add_comm_prefix is_comm "haar") :: tr ff s | is_comm ("prehaar" :: s) := ("add_" ++ add_comm_prefix is_comm "prehaar") :: tr ff s | is_comm ("comm" :: s) := tr tt s | is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s) | tt [] := ["comm"] | ff [] := [] /-- Autogenerate target name for `to_additive`. -/ meta def guess_name : string → string := string.map_tokens ''' $ λ s, string.intercalate (string.singleton '_') $ tr ff (s.split_on '_') /-- Return the provided target name or autogenerate one if one was not provided. -/ meta def target_name (src tgt : name) (dict : name_map name) (allow_auto_name : bool) : tactic name := (if tgt.get_prefix ≠ name.anonymous ∨ allow_auto_name -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto ∨ tgt = src) <|> trace ("`to_additive " ++ src.to_string ++ "`: correctly autogenerated target " ++ "name, you may remove the explicit " ++ tgt_auto ++ " argument."), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src ∧ tgt ≠ src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself. Give the desired additive name explicitly using `@[to_additive additive_name]`. ") else pure res) /-- the parser for the arguments to `to_additive`. -/ meta def parser : lean.parser value_type := do bang ← option.is_some <$> (tk "!")?, ques ← option.is_some <$> (tk "?")?, tgt ← ident?, e ← texpr?, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨bang, ques, tgt.get_or_else name.anonymous, doc, ff⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio /-- Add the `aux_attr` attribute to the structure fields of `src` so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> get_tagged_ancestors n)) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string: ``` @[to_additive add_foo "add_foo doc string"] /-- foo doc string -/ theorem foo := sorry ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. If the declaration to be transported has attributes which need to be copied to the additive version, then `to_additive` should come last: ``` @[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x ``` The exception to this rule is the `simps` attribute, which should come after `to_additive`: ``` @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ ``` ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `comm_semigroup` to `add_comm_semigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`. ### Heuristics `to_additive` uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The basic heuristic is * Only map an identifier to its additive version if its first argument doesn't contain any unapplied identifiers. Examples: * `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its first argument is `ℕ`, an identifier not applied to any arguments. * `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier `prod`, but this is applied to arguments, `α` and `β`. * `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`. The reasoning behind the heuristic is that the first argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type. There are some exceptions to this heuristic: * Identifiers that have the `@[to_additive]` attribute are ignored. For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`. * If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument in position `n` is checked for a fixed type, instead of checking the first argument. `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a declaration when the first argument has no multiplicative type-class, but argument `n` does. * If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1). For example, `times_cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means that its 21st argument `(n : with_top ℕ)` can contain `ℕ` (usually in the form `has_top.top ℕ ...`) and still be additivized. So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized. ### Troubleshooting If `@[to_additive]` fails because the additive declaration raises a type mismatch, there are various things you can try. The first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type mismatch error. * Option 1: It additivized a declaration `d` that should remain multiplicative. Solution: * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you reorder the (implicit) arguments of `d` so that the first argument becomes a type with a multiplicative structure (and not some indexing type)? The reason is that `@[to_additive]` doesn't additivize declarations if their first argument contains fixed types like `ℕ` or `ℝ`. See section Heuristics. If the first argument is not the argument with a multiplicative type-class, `@[to_additive]` should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration. You can test this by running the following (where `d` is the full name of the declaration): ``` run_cmd to_additive.relevant_arg_attr.get_param `d >>= tactic.trace ``` The expected output is `n` where the `n`-th argument of `d` is a type (family) with a multiplicative structure on it. If you get a different output (or a failure), you could add the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an argument with a multiplicative structure. * Option 2: It didn't additivize a declaration that should be additivized. This happened because the heuristic applied, and the first argument contains a fixed type, like `ℕ` or `ℝ`. Solutions: * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]` attribute. * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the `k`-th argument is not connected to the multiplicative structure on `d`, consider adding attribute `[to_additive_ignore_args k]` to `d`. * If you want to disable the heuristic and replace all multiplicative identifiers with their additive counterpart, use `@[to_additive!]`. * Option 3: Arguments / universe levels are incorrectly ordered in the additive version. This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions: * Ensure that the order of arguments of all relevant declarations are the same for the multiplicative and additive version. This might mean that arguments have an "unnatural" order (e.g. `monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `monoid.npow` has this argument order, since it matches `add_monoid.nsmul n x`. * If this is not possible, add the `[to_additive_reorder k]` to the multiplicative declaration to indicate that the `k`-th and `(k+1)`-st arguments are reordered in the additive version. If neither of these solutions work, and `to_additive` is unable to automatically generate the additive version of a declaration, manually write and prove the additive version. Often the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to `multiplicative G`. Afterwards, apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. After transporting the “main” declaration, `to_additive` transports its equational lemmas. ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. The `ancestor` attribute must come before the `to_additive` attribute, and it is essential that the order of the base structures passed to `ancestor` matches between the multiplicative and additive versions of the structure. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first case `to_additive` double checks that the new name differs from the original one. -/ @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, ignore ← ignore_args_attr.get_cache, relevant ← relevant_arg_attr.get_cache, reorder ← reorder_attr.get_cache, tgt ← target_name src val.tgt dict val.allow_auto_name, aux_attr.set src tgt tt, let dict := dict.insert src tgt, first_mult_arg ← first_multiplicative_arg src, when (first_mult_arg ≠ 1) $ relevant_arg_attr.set src first_mult_arg tt, if env.contains tgt then proceed_fields env src tgt prio else do transform_decl_with_prefix_dict dict val.replace_all val.trace relevant ignore reorder src tgt [`reducible, `_refl_lemma, `simp, `norm_cast, `instance, `refl, `symm, `trans, `elab_as_eliminator, `no_rsimp, `continuity, `ext, `ematch, `measurability, `alias, `_ext_core, `_ext_lemma_core, `nolint], mwhen (has_attribute' `simps src) (trace "Apply the simps attribute after the to_additive attribute"), mwhen (has_attribute' `mono src) (trace $ "to_additive does not work with mono, apply the mono attribute to both" ++ "versions after"), match val.doc with | some doc := add_doc_string tgt doc | none := skip end } add_tactic_doc { name := "to_additive", category := doc_category.attr, decl_names := [`to_additive.attr], tags := ["transport", "environment", "lemma derivation"] } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv has_div /- the following types are supported by `@[to_additive]` and mapped to themselves. -/ attribute [to_additive empty] empty attribute [to_additive pempty] pempty attribute [to_additive punit] punit attribute [to_additive unit] unit /- We ignore the third argument of `has_coe_to_fun.F` when deciding whether the operation needs to be additivized. The reason is that this argument is the element to be coerced, which usually does not actually show up in the type after reduction. Hypothetically, this could be ignoring too much, in that case, we can remove this, but in that case we have to add the `to_additive_ignore_args` attribute more systematically to a lot of other definitions (like `times_cont_mdiff_map.comp`). -/ attribute [to_additive_ignore_args 3] has_coe_to_fun.F
3c15210af53d9be641d1e63b1e5e111198fdaa50
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/library/init/util.lean
4d894b3abe53821feabe3f2343767eeb4c46ce66
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
512
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.string.basic /- This function has a native implementation that tracks time. -/ def timeit {α : Type} (s : string) (f : unit → α) : α := f () /- This function has a native implementation that displays the given string in the regular output stream. -/ def trace {α : Type} (s : string) (f : unit → α) : α := f ()
abc56a0b2f30f95efb6c676414de6fc566dc4d76
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/algebra/subalgebra/basic.lean
890bf221c604bf11c47fb73e72ece7d5539110dc
[ "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
46,202
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.algebra.basic import data.set.Union_lift import linear_algebra.finsupp import ring_theory.ideal.operations /-! # Subalgebras over Commutative Semiring In this file we define `subalgebra`s and the usual operations on them (`map`, `comap`). More lemmas about `adjoin` can be found in `ring_theory.adjoin`. -/ universes u u' v w w' open_locale big_operators set_option old_structure_cmd true /-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/ structure subalgebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v := (algebra_map_mem' : ∀ r, algebra_map R A r ∈ carrier) (zero_mem' := (algebra_map R A).map_zero ▸ algebra_map_mem' 0) (one_mem' := (algebra_map R A).map_one ▸ algebra_map_mem' 1) /-- Reinterpret a `subalgebra` as a `subsemiring`. -/ add_decl_doc subalgebra.to_subsemiring namespace subalgebra variables {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'} variables [comm_semiring R] variables [semiring A] [algebra R A] [semiring B] [algebra R B] [semiring C] [algebra R C] include R instance : set_like (subalgebra R A) A := { coe := subalgebra.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : subsemiring_class (subalgebra R A) A := { add_mem := add_mem', mul_mem := mul_mem', one_mem := one_mem', zero_mem := zero_mem' } @[simp] lemma mem_carrier {s : subalgebra R A} {x : A} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma mem_to_subsemiring {S : subalgebra R A} {x} : x ∈ S.to_subsemiring ↔ x ∈ S := iff.rfl @[simp] lemma coe_to_subsemiring (S : subalgebra R A) : (↑S.to_subsemiring : set A) = S := rfl theorem to_subsemiring_injective : function.injective (to_subsemiring : subalgebra R A → subsemiring A) := λ S T h, ext $ λ x, by rw [← mem_to_subsemiring, ← mem_to_subsemiring, h] theorem to_subsemiring_inj {S U : subalgebra R A} : S.to_subsemiring = U.to_subsemiring ↔ S = U := to_subsemiring_injective.eq_iff /-- Copy of a subalgebra with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : subalgebra R A) (s : set A) (hs : s = ↑S) : subalgebra R A := { carrier := s, add_mem' := hs.symm ▸ S.add_mem', mul_mem' := hs.symm ▸ S.mul_mem', algebra_map_mem' := hs.symm ▸ S.algebra_map_mem' } @[simp] lemma coe_copy (S : subalgebra R A) (s : set A) (hs : s = ↑S) : (S.copy s hs : set A) = s := rfl lemma copy_eq (S : subalgebra R A) (s : set A) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs variables (S : subalgebra R A) theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S := S.algebra_map_mem' r theorem srange_le : (algebra_map R A).srange ≤ S.to_subsemiring := λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r theorem range_subset : set.range (algebra_map R A) ⊆ S := λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r theorem range_le : set.range (algebra_map R A) ≤ S := S.range_subset theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S := (algebra.smul_def r x).symm ▸ mul_mem (S.algebra_map_mem r) hx protected theorem one_mem : (1 : A) ∈ S := one_mem S protected theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S := mul_mem hx hy protected theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S := pow_mem hx n protected theorem zero_mem : (0 : A) ∈ S := zero_mem S protected theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S := add_mem hx hy protected theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n • x ∈ S := nsmul_mem hx n protected theorem coe_nat_mem (n : ℕ) : (n : A) ∈ S := coe_nat_mem S n protected theorem list_prod_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S := list_prod_mem h protected theorem list_sum_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S := list_sum_mem h protected theorem multiset_sum_mem {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S := multiset_sum_mem m h protected theorem sum_mem {ι : Type w} {t : finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : ∑ x in t, f x ∈ S := sum_mem h protected theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S := multiset_prod_mem m h protected theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {ι : Type w} {t : finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S := prod_mem h instance {R A : Type*} [comm_ring R] [ring A] [algebra R A] : subring_class (subalgebra R A) A := { neg_mem := λ S x hx, neg_one_smul R x ▸ S.smul_mem hx _, .. subalgebra.subsemiring_class } protected theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S := neg_mem hx protected theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := sub_mem hx hy protected theorem zsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) (n : ℤ) : n • x ∈ S := zsmul_mem hx n protected theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) (n : ℤ) : (n : A) ∈ S := coe_int_mem S n /-- The projection from a subalgebra of `A` to an additive submonoid of `A`. -/ def to_add_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : add_submonoid A := S.to_subsemiring.to_add_submonoid /-- The projection from a subalgebra of `A` to a submonoid of `A`. -/ def to_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : submonoid A := S.to_subsemiring.to_submonoid /-- A subalgebra over a ring is also a `subring`. -/ def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : subring A := { neg_mem' := λ _, S.neg_mem, .. S.to_subsemiring } @[simp] lemma mem_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {S : subalgebra R A} {x} : x ∈ S.to_subring ↔ x ∈ S := iff.rfl @[simp] lemma coe_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : (↑S.to_subring : set A) = S := rfl theorem to_subring_injective {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] : function.injective (to_subring : subalgebra R A → subring A) := λ S T h, ext $ λ x, by rw [← mem_to_subring, ← mem_to_subring, h] theorem to_subring_inj {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {S U : subalgebra R A} : S.to_subring = U.to_subring ↔ S = U := to_subring_injective.eq_iff instance : inhabited S := ⟨(0 : S.to_subsemiring)⟩ section /-! `subalgebra`s inherit structure from their `subsemiring` / `semiring` coercions. -/ instance to_semiring {R A} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : semiring S := S.to_subsemiring.to_semiring instance to_comm_semiring {R A} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : comm_semiring S := S.to_subsemiring.to_comm_semiring instance to_ring {R A} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : ring S := S.to_subring.to_ring instance to_comm_ring {R A} [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := S.to_subring.to_comm_ring instance to_ordered_semiring {R A} [comm_semiring R] [ordered_semiring A] [algebra R A] (S : subalgebra R A) : ordered_semiring S := S.to_subsemiring.to_ordered_semiring instance to_ordered_comm_semiring {R A} [comm_semiring R] [ordered_comm_semiring A] [algebra R A] (S : subalgebra R A) : ordered_comm_semiring S := S.to_subsemiring.to_ordered_comm_semiring instance to_ordered_ring {R A} [comm_ring R] [ordered_ring A] [algebra R A] (S : subalgebra R A) : ordered_ring S := S.to_subring.to_ordered_ring instance to_ordered_comm_ring {R A} [comm_ring R] [ordered_comm_ring A] [algebra R A] (S : subalgebra R A) : ordered_comm_ring S := S.to_subring.to_ordered_comm_ring instance to_linear_ordered_semiring {R A} [comm_semiring R] [linear_ordered_semiring A] [algebra R A] (S : subalgebra R A) : linear_ordered_semiring S := S.to_subsemiring.to_linear_ordered_semiring /-! There is no `linear_ordered_comm_semiring`. -/ instance to_linear_ordered_ring {R A} [comm_ring R] [linear_ordered_ring A] [algebra R A] (S : subalgebra R A) : linear_ordered_ring S := S.to_subring.to_linear_ordered_ring instance to_linear_ordered_comm_ring {R A} [comm_ring R] [linear_ordered_comm_ring A] [algebra R A] (S : subalgebra R A) : linear_ordered_comm_ring S := S.to_subring.to_linear_ordered_comm_ring end /-- Convert a `subalgebra` to `submodule` -/ def to_submodule : submodule R A := { carrier := S, zero_mem' := (0:S).2, add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } @[simp] lemma mem_to_submodule {x} : x ∈ S.to_submodule ↔ x ∈ S := iff.rfl @[simp] lemma coe_to_submodule (S : subalgebra R A) : (↑S.to_submodule : set A) = S := rfl theorem to_submodule_injective : function.injective (to_submodule : subalgebra R A → submodule R A) := λ S T h, ext $ λ x, by rw [← mem_to_submodule, ← mem_to_submodule, h] theorem to_submodule_inj {S U : subalgebra R A} : S.to_submodule = U.to_submodule ↔ S = U := to_submodule_injective.eq_iff section /-! `subalgebra`s inherit structure from their `submodule` coercions. -/ instance module' [semiring R'] [has_smul R' R] [module R' A] [is_scalar_tower R' R A] : module R' S := S.to_submodule.module' instance : module R S := S.module' instance [semiring R'] [has_smul R' R] [module R' A] [is_scalar_tower R' R A] : is_scalar_tower R' R S := S.to_submodule.is_scalar_tower instance algebra' [comm_semiring R'] [has_smul R' R] [algebra R' A] [is_scalar_tower R' R A] : algebra R' S := { commutes' := λ c x, subtype.eq $ algebra.commutes _ _, smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _, .. (algebra_map R' A).cod_restrict S $ λ x, begin rw [algebra.algebra_map_eq_smul_one, ←smul_one_smul R x (1 : A), ←algebra.algebra_map_eq_smul_one], exact algebra_map_mem S _, end } instance : algebra R S := S.algebra' end instance no_zero_smul_divisors_bot [no_zero_smul_divisors R A] : no_zero_smul_divisors R S := ⟨λ c x h, have c = 0 ∨ (x : A) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ protected lemma coe_add (x y : S) : (↑(x + y) : A) = ↑x + ↑y := rfl protected lemma coe_mul (x y : S) : (↑(x * y) : A) = ↑x * ↑y := rfl protected lemma coe_zero : ((0 : S) : A) = 0 := rfl protected lemma coe_one : ((1 : S) : A) = 1 := rfl protected lemma coe_neg {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {S : subalgebra R A} (x : S) : (↑(-x) : A) = -↑x := rfl protected lemma coe_sub {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {S : subalgebra R A} (x y : S) : (↑(x - y) : A) = ↑x - ↑y := rfl @[simp, norm_cast] lemma coe_smul [semiring R'] [has_smul R' R] [module R' A] [is_scalar_tower R' R A] (r : R') (x : S) : (↑(r • x) : A) = r • ↑x := rfl @[simp, norm_cast] lemma coe_algebra_map [comm_semiring R'] [has_smul R' R] [algebra R' A] [is_scalar_tower R' R A] (r : R') : ↑(algebra_map R' S r) = algebra_map R' A r := rfl protected lemma coe_pow (x : S) (n : ℕ) : (↑(x^n) : A) = (↑x)^n := submonoid_class.coe_pow x n protected lemma coe_eq_zero {x : S} : (x : A) = 0 ↔ x = 0 := add_submonoid_class.coe_eq_zero protected lemma coe_eq_one {x : S} : (x : A) = 1 ↔ x = 1 := submonoid_class.coe_eq_one -- todo: standardize on the names these morphisms -- compare with submodule.subtype /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := by refine_struct { to_fun := (coe : S → A) }; intros; refl @[simp] lemma coe_val : (S.val : S → A) = coe := rfl lemma val_apply (x : S) : S.val x = (x : A) := rfl @[simp] lemma to_subsemiring_subtype : S.to_subsemiring.subtype = (S.val : S →+* A) := rfl @[simp] lemma to_subring_subtype {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : S.to_subring.subtype = (S.val : S →+* A) := rfl /-- Linear equivalence between `S : submodule R A` and `S`. Though these types are equal, we define it as a `linear_equiv` to avoid type equalities. -/ def to_submodule_equiv (S : subalgebra R A) : S.to_submodule ≃ₗ[R] S := linear_equiv.of_eq _ _ rfl /-- Transport a subalgebra via an algebra homomorphism. -/ def map (f : A →ₐ[R] B) (S : subalgebra R A) : subalgebra R B := { algebra_map_mem' := λ r, f.commutes r ▸ set.mem_image_of_mem _ (S.algebra_map_mem r), .. S.to_subsemiring.map (f : A →+* B) } lemma map_mono {S₁ S₂ : subalgebra R A} {f : A →ₐ[R] B} : S₁ ≤ S₂ → S₁.map f ≤ S₂.map f := set.image_subset f lemma map_injective {f : A →ₐ[R] B} (hf : function.injective f) : function.injective (map f) := λ S₁ S₂ ih, ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih @[simp] lemma map_id (S : subalgebra R A) : S.map (alg_hom.id R A) = S := set_like.coe_injective $ set.image_id _ lemma map_map (S : subalgebra R A) (g : B →ₐ[R] C) (f : A →ₐ[R] B) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma mem_map {S : subalgebra R A} {f : A →ₐ[R] B} {y : B} : y ∈ map f S ↔ ∃ x ∈ S, f x = y := subsemiring.mem_map lemma map_to_submodule {S : subalgebra R A} {f : A →ₐ[R] B} : (S.map f).to_submodule = S.to_submodule.map f.to_linear_map := set_like.coe_injective rfl lemma map_to_subsemiring {S : subalgebra R A} {f : A →ₐ[R] B} : (S.map f).to_subsemiring = S.to_subsemiring.map f.to_ring_hom := set_like.coe_injective rfl @[simp] lemma coe_map (S : subalgebra R A) (f : A →ₐ[R] B) : (S.map f : set B) = f '' S := rfl /-- Preimage of a subalgebra under an algebra homomorphism. -/ def comap (f : A →ₐ[R] B) (S : subalgebra R B) : subalgebra R A := { algebra_map_mem' := λ r, show f (algebra_map R A r) ∈ S, from (f.commutes r).symm ▸ S.algebra_map_mem r, .. S.to_subsemiring.comap (f : A →+* B) } theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} : map f S ≤ U ↔ S ≤ comap f U := set.image_subset_iff lemma gc_map_comap (f : A →ₐ[R] B) : galois_connection (map f) (comap f) := λ S U, map_le @[simp] lemma mem_comap (S : subalgebra R B) (f : A →ₐ[R] B) (x : A) : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[simp, norm_cast] lemma coe_comap (S : subalgebra R B) (f : A →ₐ[R] B) : (S.comap f : set A) = f ⁻¹' (S : set B) := rfl instance no_zero_divisors {R A : Type*} [comm_semiring R] [semiring A] [no_zero_divisors A] [algebra R A] (S : subalgebra R A) : no_zero_divisors S := S.to_subsemiring.no_zero_divisors instance is_domain {R A : Type*} [comm_ring R] [ring A] [is_domain A] [algebra R A] (S : subalgebra R A) : is_domain S := subring.is_domain S.to_subring end subalgebra namespace submodule variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] variables (p : submodule R A) /-- A submodule containing `1` and closed under multiplication is a subalgebra. -/ def to_subalgebra (p : submodule R A) (h_one : (1 : A) ∈ p) (h_mul : ∀ x y, x ∈ p → y ∈ p → x * y ∈ p) : subalgebra R A := { mul_mem' := h_mul, algebra_map_mem' := λ r, begin rw algebra.algebra_map_eq_smul_one, exact p.smul_mem _ h_one, end, ..p} @[simp] lemma mem_to_subalgebra {p : submodule R A} {h_one h_mul} {x} : x ∈ p.to_subalgebra h_one h_mul ↔ x ∈ p := iff.rfl @[simp] lemma coe_to_subalgebra (p : submodule R A) (h_one h_mul) : (p.to_subalgebra h_one h_mul : set A) = p := rfl @[simp] lemma to_subalgebra_mk (s : set A) (h0 hadd hsmul h1 hmul) : (submodule.mk s hadd h0 hsmul : submodule R A).to_subalgebra h1 hmul = subalgebra.mk s @hmul h1 @hadd h0 (λ r, by { rw algebra.algebra_map_eq_smul_one, exact hsmul r h1 }) := rfl @[simp] lemma to_subalgebra_to_submodule (p : submodule R A) (h_one h_mul) : (p.to_subalgebra h_one h_mul).to_submodule = p := set_like.coe_injective rfl @[simp] lemma _root_.subalgebra.to_submodule_to_subalgebra (S : subalgebra R A) : S.to_submodule.to_subalgebra S.one_mem (λ _ _, S.mul_mem) = S := set_like.coe_injective rfl end submodule namespace alg_hom variables {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'} variables [comm_semiring R] variables [semiring A] [algebra R A] [semiring B] [algebra R B] [semiring C] [algebra R C] variables (φ : A →ₐ[R] B) /-- Range of an `alg_hom` as a subalgebra. -/ protected def range (φ : A →ₐ[R] B) : subalgebra R B := { algebra_map_mem' := λ r, ⟨algebra_map R A r, φ.commutes r⟩, .. φ.to_ring_hom.srange } @[simp] lemma mem_range (φ : A →ₐ[R] B) {y : B} : y ∈ φ.range ↔ ∃ x, φ x = y := ring_hom.mem_srange theorem mem_range_self (φ : A →ₐ[R] B) (x : A) : φ x ∈ φ.range := φ.mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (φ : A →ₐ[R] B) : (φ.range : set B) = set.range φ := by { ext, rw [set_like.mem_coe, mem_range], refl } theorem range_comp (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).range = f.range.map g := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).range ≤ g.range := set_like.coe_mono (set.range_comp_subset_range f g) /-- Restrict the codomain of an algebra homomorphism. -/ def cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : A →ₐ[R] S := { commutes' := λ r, subtype.eq $ f.commutes r, .. ring_hom.cod_restrict (f : A →+* B) S hf } @[simp] lemma val_comp_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : S.val.comp (f.cod_restrict S hf) = f := alg_hom.ext $ λ _, rfl @[simp] lemma coe_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) (x : A) : ↑(f.cod_restrict S hf x) = f x := rfl theorem injective_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : function.injective (f.cod_restrict S hf) ↔ function.injective f := ⟨λ H x y hxy, H $ subtype.eq hxy, λ H x y hxy, H (congr_arg subtype.val hxy : _)⟩ /-- Restrict the codomain of a alg_hom `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict (f : A →ₐ[R] B) : A →ₐ[R] f.range := f.cod_restrict f.range f.mem_range_self /-- The equalizer of two R-algebra homomorphisms -/ def equalizer (ϕ ψ : A →ₐ[R] B) : subalgebra R A := { carrier := {a | ϕ a = ψ a}, add_mem' := λ x y (hx : ϕ x = ψ x) (hy : ϕ y = ψ y), by rw [set.mem_set_of_eq, ϕ.map_add, ψ.map_add, hx, hy], mul_mem' := λ x y (hx : ϕ x = ψ x) (hy : ϕ y = ψ y), by rw [set.mem_set_of_eq, ϕ.map_mul, ψ.map_mul, hx, hy], algebra_map_mem' := λ x, by rw [set.mem_set_of_eq, alg_hom.commutes, alg_hom.commutes] } @[simp] lemma mem_equalizer (ϕ ψ : A →ₐ[R] B) (x : A) : x ∈ ϕ.equalizer ψ ↔ ϕ x = ψ x := iff.rfl /-- The range of a morphism of algebras is a fintype, if the domain is a fintype. Note that this instance can cause a diamond with `subtype.fintype` if `B` is also a fintype. -/ instance fintype_range [fintype A] [decidable_eq B] (φ : A →ₐ[R] B) : fintype φ.range := set.fintype_range φ end alg_hom namespace alg_equiv variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] /-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range. This is a computable alternative to `alg_equiv.of_injective`. -/ def of_left_inverse {g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) : A ≃ₐ[R] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.val, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := f.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.range_restrict } @[simp] lemma of_left_inverse_apply {g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : A) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply {g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl /-- Restrict an injective algebra homomorphism to an algebra isomorphism -/ noncomputable def of_injective (f : A →ₐ[R] B) (hf : function.injective f) : A ≃ₐ[R] f.range := of_left_inverse (classical.some_spec hf.has_left_inverse) @[simp] lemma of_injective_apply (f : A →ₐ[R] B) (hf : function.injective f) (x : A) : ↑(of_injective f hf x) = f x := rfl /-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/ noncomputable def of_injective_field {E F : Type*} [division_ring E] [semiring F] [nontrivial F] [algebra R E] [algebra R F] (f : E →ₐ[R] F) : E ≃ₐ[R] f.range := of_injective f f.to_ring_hom.injective /-- Given an equivalence `e : A ≃ₐ[R] B` of `R`-algebras and a subalgebra `S` of `A`, `subalgebra_map` is the induced equivalence between `S` and `S.map e` -/ @[simps] def subalgebra_map (e : A ≃ₐ[R] B) (S : subalgebra R A) : S ≃ₐ[R] (S.map e.to_alg_hom) := { commutes' := λ r, by { ext, simp }, ..e.to_ring_equiv.subsemiring_map S.to_subsemiring } end alg_equiv namespace algebra variables (R : Type u) {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- The minimal subalgebra that includes `s`. -/ def adjoin (s : set A) : subalgebra R A := { algebra_map_mem' := λ r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩, .. subsemiring.closure (set.range (algebra_map R A) ∪ s) } variables {R} protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H, λ H, show subsemiring.closure (set.range (algebra_map R A) ∪ s) ≤ S.to_subsemiring, from subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩ /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, (adjoin R s).copy s $ le_antisymm (algebra.gc.le_u_l s) hs, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_rfl, choice_eq := λ _ _, subalgebra.copy_eq _ _ _ } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi @[simp] lemma coe_top : (↑(⊤ : subalgebra R A) : set A) = set.univ := rfl @[simp] lemma mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := set.mem_univ x @[simp] lemma top_to_submodule : (⊤ : subalgebra R A).to_submodule = ⊤ := rfl @[simp] lemma top_to_subsemiring : (⊤ : subalgebra R A).to_subsemiring = ⊤ := rfl @[simp] lemma top_to_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] : (⊤ : subalgebra R A).to_subring = ⊤ := rfl @[simp] lemma to_submodule_eq_top {S : subalgebra R A} : S.to_submodule = ⊤ ↔ S = ⊤ := subalgebra.to_submodule_injective.eq_iff' top_to_submodule @[simp] lemma to_subsemiring_eq_top {S : subalgebra R A} : S.to_subsemiring = ⊤ ↔ S = ⊤ := subalgebra.to_subsemiring_injective.eq_iff' top_to_subsemiring @[simp] lemma to_subring_eq_top {R A : Type*} [comm_ring R] [ring A] [algebra R A] {S : subalgebra R A} : S.to_subring = ⊤ ↔ S = ⊤ := subalgebra.to_subring_injective.eq_iff' top_to_subring lemma mem_sup_left {S T : subalgebra R A} : ∀ {x : A}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : subalgebra R A} : ∀ {x : A}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mul_mem_sup {S T : subalgebra R A} {x y : A} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T := (S ⊔ T).mul_mem (mem_sup_left hx) (mem_sup_right hy) lemma map_sup (f : A →ₐ[R] B) (S T : subalgebra R A) : (S ⊔ T).map f = S.map f ⊔ T.map f := (subalgebra.gc_map_comap f).l_sup @[simp, norm_cast] lemma coe_inf (S T : subalgebra R A) : (↑(S ⊓ T) : set A) = S ∩ T := rfl @[simp] lemma mem_inf {S T : subalgebra R A} {x : A} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl @[simp] lemma inf_to_submodule (S T : subalgebra R A) : (S ⊓ T).to_submodule = S.to_submodule ⊓ T.to_submodule := rfl @[simp] lemma inf_to_subsemiring (S T : subalgebra R A) : (S ⊓ T).to_subsemiring = S.to_subsemiring ⊓ T.to_subsemiring := rfl @[simp, norm_cast] lemma coe_Inf (S : set (subalgebra R A)) : (↑(Inf S) : set A) = ⋂ s ∈ S, ↑s := Inf_image lemma mem_Inf {S : set (subalgebra R A)} {x : A} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := by simp only [← set_like.mem_coe, coe_Inf, set.mem_Inter₂] @[simp] lemma Inf_to_submodule (S : set (subalgebra R A)) : (Inf S).to_submodule = Inf (subalgebra.to_submodule '' S) := set_like.coe_injective $ by simp @[simp] lemma Inf_to_subsemiring (S : set (subalgebra R A)) : (Inf S).to_subsemiring = Inf (subalgebra.to_subsemiring '' S) := set_like.coe_injective $ by simp @[simp, norm_cast] lemma coe_infi {ι : Sort*} {S : ι → subalgebra R A} : (↑(⨅ i, S i) : set A) = ⋂ i, S i := by simp [infi] lemma mem_infi {ι : Sort*} {S : ι → subalgebra R A} {x : A} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp] lemma infi_to_submodule {ι : Sort*} (S : ι → subalgebra R A) : (⨅ i, S i).to_submodule = ⨅ i, (S i).to_submodule := set_like.coe_injective $ by simp instance : inhabited (subalgebra R A) := ⟨⊥⟩ theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := suffices (of_id R A).range = (⊥ : subalgebra R A), by { rw [← this, ←set_like.mem_coe, alg_hom.coe_range], refl }, le_bot_iff.mp (λ x hx, subalgebra.range_le _ ((of_id R A).coe_range ▸ hx)) theorem to_submodule_bot : (⊥ : subalgebra R A).to_submodule = R ∙ 1 := by { ext x, simp [mem_bot, -set.singleton_one, submodule.mem_span_singleton, algebra.smul_def] } @[simp] theorem coe_bot : ((⊥ : subalgebra R A) : set A) = set.range (algebra_map R A) := by simp [set.ext_iff, algebra.mem_bot] theorem eq_top_iff {S : subalgebra R A} : S = ⊤ ↔ ∀ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩ lemma range_top_iff_surjective (f : A →ₐ[R] B) : f.range = (⊤ : subalgebra R B) ↔ function.surjective f := algebra.eq_top_iff @[simp] theorem range_id : (alg_hom.id R A).range = ⊤ := set_like.coe_injective set.range_id @[simp] theorem map_top (f : A →ₐ[R] B) : (⊤ : subalgebra R A).map f = f.range := set_like.coe_injective set.image_univ @[simp] theorem map_bot (f : A →ₐ[R] B) : (⊥ : subalgebra R A).map f = ⊥ := set_like.coe_injective $ by simp only [← set.range_comp, (∘), algebra.coe_bot, subalgebra.coe_map, f.commutes] @[simp] theorem comap_top (f : A →ₐ[R] B) : (⊤ : subalgebra R B).comap f = ⊤ := eq_top_iff.2 $ λ x, mem_top /-- `alg_hom` to `⊤ : subalgebra R A`. -/ def to_top : A →ₐ[R] (⊤ : subalgebra R A) := (alg_hom.id R A).cod_restrict ⊤ (λ _, mem_top) theorem surjective_algebra_map_iff : function.surjective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ := ⟨λ h, eq_bot_iff.2 $ λ y _, let ⟨x, hx⟩ := h y in hx ▸ subalgebra.algebra_map_mem _ _, λ h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y ∈ _)⟩ theorem bijective_algebra_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A] [algebra R A] : function.bijective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ := ⟨λ h, surjective_algebra_map_iff.1 h.2, λ h, ⟨(algebra_map R A).injective, surjective_algebra_map_iff.2 h⟩⟩ /-- The bottom subalgebra is isomorphic to the base ring. -/ noncomputable def bot_equiv_of_injective (h : function.injective (algebra_map R A)) : (⊥ : subalgebra R A) ≃ₐ[R] R := alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _) ⟨λ x y hxy, h (congr_arg subtype.val hxy : _), λ ⟨y, hy⟩, let ⟨x, hx⟩ := algebra.mem_bot.1 hy in ⟨x, subtype.eq hx⟩⟩ /-- The bottom subalgebra is isomorphic to the field. -/ @[simps symm_apply] noncomputable def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] : (⊥ : subalgebra F R) ≃ₐ[F] F := bot_equiv_of_injective (ring_hom.injective _) end algebra namespace subalgebra open algebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] variables (S : subalgebra R A) /-- The top subalgebra is isomorphic to the algebra. This is the algebra version of `submodule.top_equiv`. -/ @[simps] def top_equiv : (⊤ : subalgebra R A) ≃ₐ[R] A := alg_equiv.of_alg_hom (subalgebra.val ⊤) to_top rfl $ alg_hom.ext $ λ _, subtype.ext rfl instance subsingleton_of_subsingleton [subsingleton A] : subsingleton (subalgebra R A) := ⟨λ B C, ext (λ x, by { simp only [subsingleton.elim x 0, zero_mem B, zero_mem C] })⟩ instance _root_.alg_hom.subsingleton [subsingleton (subalgebra R A)] : subsingleton (A →ₐ[R] B) := ⟨λ f g, alg_hom.ext $ λ a, have a ∈ (⊥ : subalgebra R A) := subsingleton.elim (⊤ : subalgebra R A) ⊥ ▸ mem_top, let ⟨x, hx⟩ := set.mem_range.mp (mem_bot.mp this) in hx ▸ (f.commutes _).trans (g.commutes _).symm⟩ instance _root_.alg_equiv.subsingleton_left [subsingleton (subalgebra R A)] : subsingleton (A ≃ₐ[R] B) := ⟨λ f g, alg_equiv.ext (λ x, alg_hom.ext_iff.mp (subsingleton.elim f.to_alg_hom g.to_alg_hom) x)⟩ instance _root_.alg_equiv.subsingleton_right [subsingleton (subalgebra R B)] : subsingleton (A ≃ₐ[R] B) := ⟨λ f g, by rw [← f.symm_symm, subsingleton.elim f.symm g.symm, g.symm_symm]⟩ lemma range_val : S.val.range = S := ext $ set.ext_iff.1 $ S.val.coe_range.trans subtype.range_val instance : unique (subalgebra R R) := { uniq := begin intro S, refine le_antisymm (λ r hr, _) bot_le, simp only [set.mem_range, mem_bot, id.map_eq_self, exists_apply_eq_apply, default], end .. algebra.subalgebra.inhabited } /-- The map `S → T` when `S` is a subalgebra contained in the subalgebra `T`. This is the subalgebra version of `submodule.of_le`, or `subring.inclusion` -/ def inclusion {S T : subalgebra R A} (h : S ≤ T) : S →ₐ[R] T := { to_fun := set.inclusion h, map_one' := rfl, map_add' := λ _ _, rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, commutes' := λ _, rfl } lemma inclusion_injective {S T : subalgebra R A} (h : S ≤ T) : function.injective (inclusion h) := λ _ _, subtype.ext ∘ subtype.mk.inj @[simp] lemma inclusion_self {S : subalgebra R A}: inclusion (le_refl S) = alg_hom.id R S := alg_hom.ext $ λ x, subtype.ext rfl @[simp] lemma inclusion_mk {S T : subalgebra R A} (h : S ≤ T) (x : A) (hx : x ∈ S) : inclusion h ⟨x, hx⟩ = ⟨x, h hx⟩ := rfl lemma inclusion_right {S T : subalgebra R A} (h : S ≤ T) (x : T) (m : (x : A) ∈ S) : inclusion h ⟨x, m⟩ = x := subtype.ext rfl @[simp] lemma inclusion_inclusion {S T U : subalgebra R A} (hst : S ≤ T) (htu : T ≤ U) (x : S) : inclusion htu (inclusion hst x) = inclusion (le_trans hst htu) x := subtype.ext rfl @[simp] lemma coe_inclusion {S T : subalgebra R A} (h : S ≤ T) (s : S) : (inclusion h s : A) = s := rfl /-- Two subalgebras that are equal are also equivalent as algebras. This is the `subalgebra` version of `linear_equiv.of_eq` and `equiv.set.of_eq`. -/ @[simps apply] def equiv_of_eq (S T : subalgebra R A) (h : S = T) : S ≃ₐ[R] T := { to_fun := λ x, ⟨x, h ▸ x.2⟩, inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩, map_mul' := λ _ _, rfl, commutes' := λ _, rfl, .. linear_equiv.of_eq _ _ (congr_arg to_submodule h) } @[simp] lemma equiv_of_eq_symm (S T : subalgebra R A) (h : S = T) : (equiv_of_eq S T h).symm = equiv_of_eq T S h.symm := rfl @[simp] lemma equiv_of_eq_rfl (S : subalgebra R A) : equiv_of_eq S S rfl = alg_equiv.refl := by { ext, refl } @[simp] lemma equiv_of_eq_trans (S T U : subalgebra R A) (hST : S = T) (hTU : T = U) : (equiv_of_eq S T hST).trans (equiv_of_eq T U hTU) = equiv_of_eq S U (trans hST hTU) := rfl section prod variables (S₁ : subalgebra R B) /-- The product of two subalgebras is a subalgebra. -/ def prod : subalgebra R (A × B) := { carrier := S ×ˢ S₁, algebra_map_mem' := λ r, ⟨algebra_map_mem _ _, algebra_map_mem _ _⟩, .. S.to_subsemiring.prod S₁.to_subsemiring } @[simp] lemma coe_prod : (prod S S₁ : set (A × B)) = S ×ˢ S₁ := rfl lemma prod_to_submodule : (S.prod S₁).to_submodule = S.to_submodule.prod S₁.to_submodule := rfl @[simp] lemma mem_prod {S : subalgebra R A} {S₁ : subalgebra R B} {x : A × B} : x ∈ prod S S₁ ↔ x.1 ∈ S ∧ x.2 ∈ S₁ := set.mem_prod @[simp] lemma prod_top : (prod ⊤ ⊤ : subalgebra R (A × B)) = ⊤ := by ext; simp lemma prod_mono {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} : S ≤ T → S₁ ≤ T₁ → prod S S₁ ≤ prod T T₁ := set.prod_mono @[simp] lemma prod_inf_prod {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} : S.prod S₁ ⊓ T.prod T₁ = (S ⊓ T).prod (S₁ ⊓ T₁) := set_like.coe_injective set.prod_inter_prod end prod section supr_lift variables {ι : Type*} lemma coe_supr_of_directed [nonempty ι] {S : ι → subalgebra R A} (dir : directed (≤) S) : ↑(supr S) = ⋃ i, (S i : set A) := let K : subalgebra R A := { carrier := ⋃ i, (S i), mul_mem' := λ x y hx hy, let ⟨i, hi⟩ := set.mem_Union.1 hx in let ⟨j, hj⟩ := set.mem_Union.1 hy in let ⟨k, hik, hjk⟩ := dir i j in set.mem_Union.2 ⟨k, subalgebra.mul_mem (S k) (hik hi) (hjk hj)⟩ , add_mem' := λ x y hx hy, let ⟨i, hi⟩ := set.mem_Union.1 hx in let ⟨j, hj⟩ := set.mem_Union.1 hy in let ⟨k, hik, hjk⟩ := dir i j in set.mem_Union.2 ⟨k, subalgebra.add_mem (S k) (hik hi) (hjk hj)⟩, algebra_map_mem' := λ r, let i := @nonempty.some ι infer_instance in set.mem_Union.2 ⟨i, subalgebra.algebra_map_mem _ _⟩ } in have supr S = K, from le_antisymm (supr_le (λ i, set.subset_Union (λ i, ↑(S i)) i)) (set_like.coe_subset_coe.1 (set.Union_subset (λ i, set_like.coe_subset_coe.2 (le_supr _ _)))), this.symm ▸ rfl /-- Define an algebra homomorphism on a directed supremum of subalgebras by defining it on each subalgebra, and proving that it agrees on the intersection of subalgebras. -/ noncomputable def supr_lift [nonempty ι] (K : ι → subalgebra R A) (dir : directed (≤) K) (f : Π i, K i →ₐ[R] B) (hf : ∀ (i j : ι) (h : K i ≤ K j), f i = (f j).comp (inclusion h)) (T : subalgebra R A) (hT : T = supr K) : ↥T →ₐ[R] B := by subst hT; exact { to_fun := set.Union_lift (λ i, ↑(K i)) (λ i x, f i x) (λ i j x hxi hxj, let ⟨k, hik, hjk⟩ := dir i j in begin rw [hf i k hik, hf j k hjk], refl end) ↑(supr K) (by rw coe_supr_of_directed dir; refl), map_one' := set.Union_lift_const _ (λ _, 1) (λ _, rfl) _ (by simp), map_zero' := set.Union_lift_const _ (λ _, 0) (λ _, rfl) _ (by simp), map_mul' := set.Union_lift_binary (coe_supr_of_directed dir) dir _ (λ _, (*)) (λ _ _ _, rfl) _ (by simp), map_add' := set.Union_lift_binary (coe_supr_of_directed dir) dir _ (λ _, (+)) (λ _ _ _, rfl) _ (by simp), commutes' := λ r, set.Union_lift_const _ (λ _, algebra_map _ _ r) (λ _, rfl) _ (λ i, by erw [alg_hom.commutes (f i)]) } variables [nonempty ι] {K : ι → subalgebra R A} {dir : directed (≤) K} {f : Π i, K i →ₐ[R] B} {hf : ∀ (i j : ι) (h : K i ≤ K j), f i = (f j).comp (inclusion h)} {T : subalgebra R A} {hT : T = supr K} @[simp] lemma supr_lift_inclusion {i : ι} (x : K i) (h : K i ≤ T) : supr_lift K dir f hf T hT (inclusion h x) = f i x := by subst T; exact set.Union_lift_inclusion _ _ @[simp] lemma supr_lift_comp_inclusion {i : ι} (h : K i ≤ T) : (supr_lift K dir f hf T hT).comp (inclusion h) = f i := by ext; simp @[simp] lemma supr_lift_mk {i : ι} (x : K i) (hx : (x : A) ∈ T) : supr_lift K dir f hf T hT ⟨x, hx⟩ = f i x := by subst hT; exact set.Union_lift_mk x hx lemma supr_lift_of_mem {i : ι} (x : T) (hx : (x : A) ∈ K i) : supr_lift K dir f hf T hT x = f i ⟨x, hx⟩ := by subst hT; exact set.Union_lift_of_mem x hx end supr_lift /-! ## Actions by `subalgebra`s These are just copies of the definitions about `subsemiring` starting from `subring.mul_action`. -/ section actions variables {α β : Type*} /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [has_smul A α] (S : subalgebra R A) : has_smul S α := S.to_subsemiring.has_smul lemma smul_def [has_smul A α] {S : subalgebra R A} (g : S) (m : α) : g • m = (g : A) • m := rfl instance smul_comm_class_left [has_smul A β] [has_smul α β] [smul_comm_class A α β] (S : subalgebra R A) : smul_comm_class S α β := S.to_subsemiring.smul_comm_class_left instance smul_comm_class_right [has_smul α β] [has_smul A β] [smul_comm_class α A β] (S : subalgebra R A) : smul_comm_class α S β := S.to_subsemiring.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance is_scalar_tower_left [has_smul α β] [has_smul A α] [has_smul A β] [is_scalar_tower A α β] (S : subalgebra R A) : is_scalar_tower S α β := S.to_subsemiring.is_scalar_tower instance is_scalar_tower_mid {R S T : Type*} [comm_semiring R] [semiring S] [add_comm_monoid T] [algebra R S] [module R T] [module S T] [is_scalar_tower R S T] (S' : subalgebra R S) : is_scalar_tower R S' T := ⟨λ x y z, (smul_assoc _ (y : S) _ : _)⟩ instance [has_smul A α] [has_faithful_smul A α] (S : subalgebra R A) : has_faithful_smul S α := S.to_subsemiring.has_faithful_smul /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [mul_action A α] (S : subalgebra R A) : mul_action S α := S.to_subsemiring.mul_action /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [add_monoid α] [distrib_mul_action A α] (S : subalgebra R A) : distrib_mul_action S α := S.to_subsemiring.distrib_mul_action /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [has_zero α] [smul_with_zero A α] (S : subalgebra R A) : smul_with_zero S α := S.to_subsemiring.smul_with_zero /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [has_zero α] [mul_action_with_zero A α] (S : subalgebra R A) : mul_action_with_zero S α := S.to_subsemiring.mul_action_with_zero /-- The action by a subalgebra is the action by the underlying algebra. -/ instance module_left [add_comm_monoid α] [module A α] (S : subalgebra R A) : module S α := S.to_subsemiring.module /-- The action by a subalgebra is the action by the underlying algebra. -/ instance to_algebra {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring α] [algebra R A] [algebra A α] (S : subalgebra R A) : algebra S α := algebra.of_subsemiring S.to_subsemiring lemma algebra_map_eq {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring α] [algebra R A] [algebra A α] (S : subalgebra R A) : algebra_map S α = (algebra_map A α).comp S.val := rfl @[simp] lemma srange_algebra_map {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : (algebra_map S A).srange = S.to_subsemiring := by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, ← to_subsemiring_subtype, subsemiring.srange_subtype] @[simp] lemma range_algebra_map {R A : Type*} [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : (algebra_map S A).range = S.to_subring := by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, ← to_subring_subtype, subring.range_subtype] instance no_zero_smul_divisors_top [no_zero_divisors A] (S : subalgebra R A) : no_zero_smul_divisors S A := ⟨λ c x h, have (c : A) = 0 ∨ x = 0, from eq_zero_or_eq_zero_of_mul_eq_zero h, this.imp_left (@subtype.ext_iff _ _ c 0).mpr⟩ end actions section center lemma _root_.set.algebra_map_mem_center (r : R) : algebra_map R A r ∈ set.center A := by simp [algebra.commutes, set.mem_center_iff] variables (R A) /-- The center of an algebra is the set of elements which commute with every element. They form a subalgebra. -/ def center : subalgebra R A := { algebra_map_mem' := set.algebra_map_mem_center, .. subsemiring.center A } lemma coe_center : (center R A : set A) = set.center A := rfl @[simp] lemma center_to_subsemiring : (center R A).to_subsemiring = subsemiring.center A := rfl @[simp] lemma center_to_subring (R A : Type*) [comm_ring R] [ring A] [algebra R A] : (center R A).to_subring = subring.center A := rfl @[simp] lemma center_eq_top (A : Type*) [comm_semiring A] [algebra R A] : center R A = ⊤ := set_like.coe_injective (set.center_eq_univ A) variables {R A} instance : comm_semiring (center R A) := subsemiring.center.comm_semiring instance {A : Type*} [ring A] [algebra R A] : comm_ring (center R A) := subring.center.comm_ring lemma mem_center_iff {a : A} : a ∈ center R A ↔ ∀ (b : A), b*a = a*b := iff.rfl end center section centralizer @[simp] lemma _root_.set.algebra_map_mem_centralizer {s : set A} (r : R) : algebra_map R A r ∈ s.centralizer := λ a h, (algebra.commutes _ _).symm variables (R) /-- The centralizer of a set as a subalgebra. -/ def centralizer (s : set A) : subalgebra R A := { algebra_map_mem' := set.algebra_map_mem_centralizer, ..subsemiring.centralizer s, } @[simp, norm_cast] lemma coe_centralizer (s : set A) : (centralizer R s : set A) = s.centralizer := rfl lemma mem_centralizer_iff {s : set A} {z : A} : z ∈ centralizer R s ↔ ∀ g ∈ s, g * z = z * g := iff.rfl lemma centralizer_le (s t : set A) (h : s ⊆ t) : centralizer R t ≤ centralizer R s := set.centralizer_subset h @[simp] lemma centralizer_univ : centralizer R set.univ = center R A := set_like.ext' (set.centralizer_univ A) end centralizer /-- Suppose we are given `∑ i, lᵢ * sᵢ = 1` in `S`, and `S'` a subalgebra of `S` that contains `lᵢ` and `sᵢ`. To check that an `x : S` falls in `S'`, we only need to show that `r ^ n • x ∈ M'` for some `n` for each `r : s`. -/ lemma mem_of_span_eq_top_of_smul_pow_mem {S : Type*} [comm_ring S] [algebra R S] (S' : subalgebra R S) (s : set S) (l : s →₀ S) (hs : finsupp.total s S S coe l = 1) (hs' : s ⊆ S') (hl : ∀ i, l i ∈ S') (x : S) (H : ∀ r : s, ∃ (n : ℕ), (r ^ n : S) • x ∈ S') : x ∈ S' := begin let s' : set S' := coe ⁻¹' s, let e : s' ≃ s := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨⟨_, hs' x.2⟩, x.2⟩, λ ⟨⟨_, _⟩, _⟩, rfl, λ ⟨_, _⟩, rfl⟩, let l' : s →₀ S' := ⟨l.support, λ x, ⟨_, hl x⟩, λ _, finsupp.mem_support_iff.trans $ iff.not $ by { rw ← subtype.coe_inj, refl }⟩, have : ideal.span s' = ⊤, { rw [ideal.eq_top_iff_one, ideal.span, finsupp.mem_span_iff_total], refine ⟨finsupp.equiv_map_domain e.symm l', subtype.ext $ eq.trans _ hs⟩, rw finsupp.total_equiv_map_domain, exact finsupp.apply_total _ (algebra.of_id S' S).to_linear_map _ _ }, obtain ⟨s'', hs₁, hs₂⟩ := (ideal.span_eq_top_iff_finite _).mp this, replace H : ∀ r : s'', ∃ (n : ℕ), (r ^ n : S) • x ∈ S' := λ r, H ⟨r, hs₁ r.2⟩, choose n₁ n₂ using H, let N := s''.attach.sup n₁, have hs' := ideal.span_pow_eq_top _ hs₂ N, have : ∀ {x : S}, x ∈ (algebra.of_id S' S).range.to_submodule ↔ x ∈ S' := λ x, ⟨by { rintro ⟨x, rfl⟩, exact x.2 }, λ h, ⟨⟨x, h⟩, rfl⟩⟩, rw ← this, apply (algebra.of_id S' S).range.to_submodule.mem_of_span_top_of_smul_mem _ hs', rintro ⟨_, r, hr, rfl⟩, convert submodule.smul_mem _ (r ^ (N - n₁ ⟨r, hr⟩)) (this.mpr $ n₂ ⟨r, hr⟩) using 1, simp only [_root_.coe_coe, subtype.coe_mk, subalgebra.smul_def, smul_smul, ← pow_add, subalgebra.coe_pow], rw tsub_add_cancel_of_le (finset.le_sup (s''.mem_attach _) : n₁ ⟨r, hr⟩ ≤ N), end end subalgebra section nat variables {R : Type*} [semiring R] /-- A subsemiring is a `ℕ`-subalgebra. -/ def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra ℕ R := { algebra_map_mem' := λ i, coe_nat_mem S i, .. S } @[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} : x ∈ subalgebra_of_subsemiring S ↔ x ∈ S := iff.rfl end nat section int variables {R : Type*} [ring R] /-- A subring is a `ℤ`-subalgebra. -/ def subalgebra_of_subring (S : subring R) : subalgebra ℤ R := { algebra_map_mem' := λ i, int.induction_on i (by simpa using S.zero_mem) (λ i ih, by simpa using S.add_mem ih S.one_mem) (λ i ih, show ((-i - 1 : ℤ) : R) ∈ S, by { rw [int.cast_sub, int.cast_one], exact S.sub_mem ih S.one_mem }), .. S } variables {S : Type*} [semiring S] @[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl end int
4867d69f3dfaf84b2d3cf5903c1f54c6fc4f1cce
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/direct_sum/basic.lean
1fff7998e7e392908041c7e2a8b06e0970ee717c
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,254
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.dfinsupp import group_theory.submonoid.operations import group_theory.subgroup.basic /-! # Direct sum This file defines the direct sum of abelian groups, indexed by a discrete type. ## Notation `⨁ i, β i` is the n-ary direct sum `direct_sum`. This notation is in the `direct_sum` locale, accessible after `open_locale direct_sum`. ## References * https://en.wikipedia.org/wiki/Direct_sum -/ open_locale big_operators universes u v w u₁ variables (ι : Type v) [dec_ι : decidable_eq ι] (β : ι → Type w) /-- `direct_sum β` is the direct sum of a family of additive commutative monoids `β i`. Note: `open_locale direct_sum` will enable the notation `⨁ i, β i` for `direct_sum β`. -/ @[derive [has_coe_to_fun, add_comm_monoid, inhabited]] def direct_sum [Π i, add_comm_monoid (β i)] : Type* := Π₀ i, β i localized "notation `⨁` binders `, ` r:(scoped f, direct_sum _ f) := r" in direct_sum namespace direct_sum variables {ι} section add_comm_group variables [Π i, add_comm_group (β i)] instance : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group variables {β} @[simp] lemma sub_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := dfinsupp.sub_apply _ _ _ end add_comm_group variables [Π i, add_comm_monoid (β i)] @[simp] lemma zero_apply (i : ι) : (0 : ⨁ i, β i) i = 0 := rfl variables {β} @[simp] lemma add_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := dfinsupp.add_apply _ _ _ variables (β) include dec_ι /-- `mk β s x` is the element of `⨁ i, β i` that is zero outside `s` and has coefficient `x i` for `i` in `s`. -/ def mk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →+ ⨁ i, β i := { to_fun := dfinsupp.mk s, map_add' := λ _ _, dfinsupp.mk_add, map_zero' := dfinsupp.mk_zero, } /-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/ def of (i : ι) : β i →+ ⨁ i, β i := dfinsupp.single_add_hom β i variables {β} theorem mk_injective (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_injective s theorem of_injective (i : ι) : function.injective (of β i) := dfinsupp.single_injective @[elab_as_eliminator] protected theorem induction_on {C : (⨁ i, β i) → Prop} (x : ⨁ i, β i) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. -/ lemma add_hom_ext {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (of _ i y) = g (of _ i y)) : f = g := dfinsupp.add_hom_ext H /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma add_hom_ext' {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι), f.comp (of _ i) = g.comp (of _ i)) : f = g := add_hom_ext $ λ i, add_monoid_hom.congr_fun $ H i variables {γ : Type u₁} [add_comm_monoid γ] section to_add_monoid variables (φ : Π i, β i →+ γ) (ψ : (⨁ i, β i) →+ γ) /-- `to_add_monoid φ` is the natural homomorphism from `⨁ i, β i` to `γ` induced by a family `φ` of homomorphisms `β i → γ`. -/ def to_add_monoid : (⨁ i, β i) →+ γ := (dfinsupp.lift_add_hom φ) @[simp] lemma to_add_monoid_of (i) (x : β i) : to_add_monoid φ (of β i x) = φ i x := dfinsupp.lift_add_hom_apply_single φ i x theorem to_add_monoid.unique (f : ⨁ i, β i) : ψ f = to_add_monoid (λ i, ψ.comp (of β i)) f := by {congr, ext, simp [to_add_monoid, of]} end to_add_monoid section from_add_monoid /-- `from_add_monoid φ` is the natural homomorphism from `γ` to `⨁ i, β i` induced by a family `φ` of homomorphisms `γ → β i`. Note that this is not an isomorphism. Not every homomorphism `γ →+ ⨁ i, β i` arises in this way. -/ def from_add_monoid : (⨁ i, γ →+ β i) →+ (γ →+ ⨁ i, β i) := to_add_monoid $ λ i, add_monoid_hom.comp_hom (of β i) @[simp] lemma from_add_monoid_of (i : ι) (f : γ →+ β i) : from_add_monoid (of _ i f) = (of _ i).comp f := by { rw [from_add_monoid, to_add_monoid_of], refl } lemma from_add_monoid_of_apply (i : ι) (f : γ →+ β i) (x : γ) : from_add_monoid (of _ i f) x = of _ i (f x) := by rw [from_add_monoid_of, add_monoid_hom.coe_comp] end from_add_monoid variables (β) /-- `set_to_set β S T h` is the natural homomorphism `⨁ (i : S), β i → ⨁ (i : T), β i`, where `h : S ⊆ T`. -/ -- TODO: generalize this to remove the assumption `S ⊆ T`. def set_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), β i) →+ (⨁ (i : T), β i) := to_add_monoid $ λ i, of (λ (i : subtype T), β i) ⟨↑i, H i.prop⟩ variables {β} omit dec_ι /-- The natural equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ protected def id (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [unique ι] : (⨁ (_ : ι), M) ≃+ M := { to_fun := direct_sum.to_add_monoid (λ _, add_monoid_hom.id M), inv_fun := of (λ _, M) (default ι), left_inv := λ x, direct_sum.induction_on x (by rw [add_monoid_hom.map_zero, add_monoid_hom.map_zero]) (λ p x, by rw [unique.default_eq p, to_add_monoid_of]; refl) (λ x y ihx ihy, by rw [add_monoid_hom.map_add, add_monoid_hom.map_add, ihx, ihy]), right_inv := λ x, to_add_monoid_of _ _ _, ..direct_sum.to_add_monoid (λ _, add_monoid_hom.id M) } /-- The `direct_sum` formed by a collection of `add_submonoid`s of `M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective. See `direct_sum.add_subgroup_is_internal` for the same statement about `add_subgroup`s. -/ def add_submonoid_is_internal {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) : Prop := function.bijective (direct_sum.to_add_monoid (λ i, (A i).subtype) : (⨁ i, A i) →+ M) lemma add_submonoid_is_internal.supr_eq_top {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) (h : add_submonoid_is_internal A) : supr A = ⊤ := begin rw [add_submonoid.supr_eq_mrange_dfinsupp_sum_add_hom, add_monoid_hom.mrange_top_iff_surjective], exact function.bijective.surjective h, end /-- The `direct_sum` formed by a collection of `add_subgroup`s of `M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective. See `direct_sum.submodule_is_internal` for the same statement about `submodules`s. -/ def add_subgroup_is_internal {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : Prop := function.bijective (direct_sum.to_add_monoid (λ i, (A i).subtype) : (⨁ i, A i) →+ M) lemma add_subgroup_is_internal.to_add_submonoid {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : add_subgroup_is_internal A ↔ add_submonoid_is_internal (λ i, (A i).to_add_submonoid) := iff.rfl end direct_sum
652aa4d0488e1585dc41a88765bb4328f62bb237
e953c38599905267210b87fb5d82dcc3e52a4214
/library/data/set/basic.lean
17d3fc6162628dbc587ea8eb8e8669e4e5dd9d56
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
10,980
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import logic.connectives logic.identities algebra.binary open eq.ops binary definition set [reducible] (X : Type) := X → Prop namespace set variable {X : Type} /- membership and subset -/ definition mem [reducible] (x : X) (a : set X) := a x infix `∈` := mem notation a ∉ b := ¬ mem a b theorem ext {a b : set X} (H : ∀x, x ∈ a ↔ x ∈ b) : a = b := funext (take x, propext (H x)) definition subset (a b : set X) := ∀⦃x⦄, x ∈ a → x ∈ b infix `⊆` := subset definition superset [reducible] (s t : set X) : Prop := t ⊆ s infix `⊇` := superset theorem subset.refl (a : set X) : a ⊆ a := take x, assume H, H theorem subset.trans {a b c : set X} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c := take x, assume ax, subbc (subab ax) theorem subset.antisymm {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem mem_of_subset_of_mem {s₁ s₂ : set X} {a : X} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ _ h₂ -- an alterantive name theorem eq_of_subset_of_subset {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ definition strict_subset (a b : set X) := a ⊆ b ∧ a ≠ b infix `⊂`:50 := strict_subset theorem strict_subset.irrefl (a : set X) : ¬ a ⊂ a := assume h, absurd rfl (and.elim_right h) /- bounded quantification -/ abbreviation bounded_forall (a : set X) (P : X → Prop) := ∀⦃x⦄, x ∈ a → P x notation `forallb` binders `∈` a `,` r:(scoped:1 P, P) := bounded_forall a r notation `∀₀` binders `∈` a `,` r:(scoped:1 P, P) := bounded_forall a r abbreviation bounded_exists (a : set X) (P : X → Prop) := ∃⦃x⦄, x ∈ a ∧ P x notation `existsb` binders `∈` a `,` r:(scoped:1 P, P) := bounded_exists a r notation `∃₀` binders `∈` a `,` r:(scoped:1 P, P) := bounded_exists a r theorem bounded_exists.intro {P : X → Prop} {s : set X} {x : X} (xs : x ∈ s) (Px : P x) : ∃₀ x ∈ s, P x := exists.intro x (and.intro xs Px) /- empty set -/ definition empty [reducible] : set X := λx, false notation `∅` := empty theorem not_mem_empty (x : X) : ¬ (x ∈ ∅) := assume H : x ∈ ∅, H theorem mem_empty_eq (x : X) : x ∈ ∅ = false := rfl theorem eq_empty_of_forall_not_mem {s : set X} (H : ∀ x, x ∉ s) : s = ∅ := ext (take x, iff.intro (assume xs, absurd xs (H x)) (assume xe, absurd xe !not_mem_empty)) theorem empty_subset (s : set X) : ∅ ⊆ s := take x, assume H, false.elim H theorem eq_empty_of_subset_empty {s : set X} (H : s ⊆ ∅) : s = ∅ := subset.antisymm H (empty_subset s) theorem subset_empty_iff (s : set X) : s ⊆ ∅ ↔ s = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) /- universal set -/ definition univ : set X := λx, true theorem mem_univ (x : X) : x ∈ univ := trivial theorem mem_univ_eq (x : X) : x ∈ univ = true := rfl theorem empty_ne_univ [h : inhabited X] : (empty : set X) ≠ univ := assume H : empty = univ, absurd (mem_univ (inhabited.value h)) (eq.rec_on H (not_mem_empty _)) theorem subset_univ (s : set X) : s ⊆ univ := λ x H, trivial theorem eq_univ_of_univ_subset {s : set X} (H : univ ⊆ s) : s = univ := eq_of_subset_of_subset (subset_univ s) H theorem eq_univ_of_forall {s : set X} (H : ∀ x, x ∈ s) : s = univ := ext (take x, iff.intro (assume H', trivial) (assume H', H x)) /- union -/ definition union [reducible] (a b : set X) : set X := λx, x ∈ a ∨ x ∈ b notation a ∪ b := union a b theorem mem_union (x : X) (a b : set X) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := !iff.refl theorem mem_union_eq (x : X) (a b : set X) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl theorem mem_union_of_mem_left {x : X} {a : set X} (b : set X) : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_union_of_mem_right {x : X} {b : set X} (a : set X) : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem union_self (a : set X) : a ∪ a = a := ext (take x, !or_self) theorem union_empty (a : set X) : a ∪ ∅ = a := ext (take x, !or_false) theorem empty_union (a : set X) : ∅ ∪ a = a := ext (take x, !false_or) theorem union.comm (a b : set X) : a ∪ b = b ∪ a := ext (take x, or.comm) theorem union.assoc (a b c : set X) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (take x, or.assoc) theorem union.left_comm (s₁ s₂ s₃ : set X) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union.comm union.assoc s₁ s₂ s₃ theorem union.right_comm (s₁ s₂ s₃ : set X) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union.comm union.assoc s₁ s₂ s₃ theorem subset_union_left (s t : set X) : s ⊆ s ∪ t := λ x H, or.inl H theorem subset_union_right (s t : set X) : t ⊆ s ∪ t := λ x H, or.inr H theorem union_subset {s t r : set X} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x xst, or.elim xst (λ xs, sr xs) (λ xt, tr xt) /- intersection -/ definition inter [reducible] (a b : set X) : set X := λx, x ∈ a ∧ x ∈ b notation a ∩ b := inter a b theorem mem_inter (x : X) (a b : set X) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := !iff.refl theorem mem_inter_eq (x : X) (a b : set X) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem inter_self (a : set X) : a ∩ a = a := ext (take x, !and_self) theorem inter_empty (a : set X) : a ∩ ∅ = ∅ := ext (take x, !and_false) theorem empty_inter (a : set X) : ∅ ∩ a = ∅ := ext (take x, !false_and) theorem inter.comm (a b : set X) : a ∩ b = b ∩ a := ext (take x, !and.comm) theorem inter.assoc (a b c : set X) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (take x, !and.assoc) theorem inter.left_comm (s₁ s₂ s₃ : set X) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter.right_comm (s₁ s₂ s₃ : set X) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter_univ (a : set X) : a ∩ univ = a := ext (take x, !and_true) theorem univ_inter (a : set X) : univ ∩ a = a := ext (take x, !true_and) theorem inter_subset_left (s t : set X) : s ∩ t ⊆ s := λ x H, and.left H theorem inter_subset_right (s t : set X) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set X} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x xr, and.intro (rs xr) (rt xr) /- distributivity laws -/ theorem inter.distrib_left (s t u : set X) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, !and.left_distrib) theorem inter.distrib_right (s t u : set X) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, !and.right_distrib) theorem union.distrib_left (s t u : set X) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, !or.left_distrib) theorem union.distrib_right (s t u : set X) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, !or.right_distrib) /- set-builder notation -/ -- {x : X | P} definition set_of (P : X → Prop) : set X := P notation `{` binder `|` r:(scoped:1 P, set_of P) `}` := r -- {x ∈ s | P} definition sep (P : X → Prop) (s : set X) : set X := λx, x ∈ s ∧ P x notation `{` binder ∈ s `|` r:(scoped:1 p, sep p s) `}` := r /- insert -/ definition insert (x : X) (a : set X) : set X := {y : X | y = x ∨ y ∈ a} -- '{x, y, z} notation `'{`:max a:(foldr `,` (x b, insert x b) ∅) `}`:0 := a theorem subset_insert (x : X) (a : set X) : a ⊆ insert x a := take y, assume ys, or.inr ys theorem mem_insert (x : X) (s : set X) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : X} {s : set X} (y : X) : x ∈ s → x ∈ insert y s := assume h, or.inr h theorem eq_or_mem_of_mem_insert {x a : X} {s : set X} : x ∈ insert a s → x = a ∨ x ∈ s := assume h, h theorem mem_of_mem_insert_of_ne {x a : X} {s : set X} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_eq (x a : X) (s : set X) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem)) theorem insert_eq_of_mem {a : X} {s : set X} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem insert.comm (x y : X) (s : set X) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) theorem eq_of_mem_singleton {x y : X} : x ∈ insert y ∅ → x = y := assume h, or.elim (eq_or_mem_of_mem_insert h) (suppose x = y, this) (suppose x ∈ ∅, absurd this !not_mem_empty) theorem mem_singleton_iff (a b : X) : a ∈ '{b} ↔ a = b := iff.intro (assume ainb, or.elim ainb (λ aeqb, aeqb) (λ f, false.elim f)) (assume aeqb, or.inl aeqb) /- separation -/ theorem eq_sep_of_subset {s t : set X} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, and.intro (ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, and.right this)) /- set difference -/ definition diff (s t : set X) : set X := {x ∈ s | x ∉ t} infix `\`:70 := diff theorem mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∈ s := and.left H theorem not_mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∉ t := and.right H theorem mem_diff {s t : set X} {x : X} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := and.intro H1 H2 theorem diff_eq (s t : set X) : s \ t = {x ∈ s | x ∉ t} := rfl theorem mem_diff_iff (s t : set X) (x : X) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := !iff.refl theorem mem_diff_eq (s t : set X) (x : X) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := rfl theorem union_diff_cancel {s t : set X} [dec : Π x, decidable (x ∈ s)] (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (assume H1 : x ∈ s ∪ (t \ s), or.elim H1 (assume H2, !H H2) (assume H2, and.left H2)) (assume H1 : x ∈ t, decidable.by_cases (suppose x ∈ s, or.inl this) (suppose x ∉ s, or.inr (and.intro H1 this)))) /- powerset -/ definition powerset (s : set X) : set (set X) := {x : set X | x ⊆ s} prefix `𝒫`:100 := powerset /- large unions -/ section variables {I : Type} variable a : set I variable b : I → set X variable C : set (set X) definition Inter : set X := {x : X | ∀i, x ∈ b i} definition bInter : set X := {x : X | ∀₀ i ∈ a, x ∈ b i} definition sInter : set X := {x : X | ∀₀ c ∈ C, x ∈ c} definition Union : set X := {x : X | ∃i, x ∈ b i} definition bUnion : set X := {x : X | ∃₀ i ∈ a, x ∈ b i} definition sUnion : set X := {x : X | ∃₀ c ∈ C, x ∈ c} -- TODO: need notation for these end end set
43a483b0a9d7877cd5401bfee9bef5f9bdf92585
ff5230333a701471f46c57e8c115a073ebaaa448
/tests/lean/run/1804a.lean
3c7cf6933769beb5b3bd9bfaad77e9a011937917
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
688
lean
section parameter P : match unit.star with | unit.star := true end include P example : false := begin dsimp [_match_1] at P, guard_hyp P := true, admit end end section parameter P : match unit.star with | unit.star := true end include P example : false := begin dsimp [_match_1] at P, guard_hyp P := true, admit end end section parameter P : match unit.star with | unit.star := true end parameter Q : match unit.star with | unit.star := true end section include P example : false := begin dsimp [_match_1] at P, guard_hyp P := true, admit end end section include Q example : false := begin dsimp [_match_2] at Q, guard_hyp Q := true, admit end end end
922777a04e987ecbd06e9725a8a7683569516564
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/metric_space/gromov_hausdorff_realized.lean
0a25b1becc1383adb91eb30e410ce39b9fb0b801
[ "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
26,157
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance import topology.continuous_function.bounded /-! # The Gromov-Hausdorff distance is realized In this file, we construct of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces. Given two nonempty compact metric spaces `X` and `Y`, we define `optimal_GH_coupling X Y` as a compact metric space, together with two isometric embeddings `optimal_GH_injl` and `optimal_GH_injr` respectively of `X` and `Y` into `optimal_GH_coupling X Y`. The main property of the optimal coupling is that the Hausdorff distance between `X` and `Y` in `optimal_GH_coupling X Y` is smaller than the corresponding distance in any other coupling. We do not prove completely this fact in this file, but we show a good enough approximation of this fact in `Hausdorff_dist_optimal_le_HD`, that will suffice to obtain the full statement once the Gromov-Hausdorff distance is properly defined, in `Hausdorff_dist_optimal`. The key point in the construction is that the set of possible distances coming from isometric embeddings of `X` and `Y` in metric spaces is a set of equicontinuous functions. By Arzela-Ascoli, it is compact, and one can find such a distance which is minimal. This distance defines a premetric space structure on `X ⊕ Y`. The corresponding metric quotient is `optimal_GH_coupling X Y`. -/ noncomputable theory open_locale classical topology nnreal universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union `X ⊕ Y` of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] @[reducible] private def prod_space_fun : Type* := ((X ⊕ Y) × (X ⊕ Y)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((X ⊕ Y) × (X ⊕ Y)) ℝ private def max_var : ℝ≥0 := 2 * ⟨diam (univ : set X), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set Y), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var X Y := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on `X ⊕ Y` that are candidates distances to realize the minimum of the Hausdorff distances between `X` and `Y` in a coupling -/ def candidates : set (prod_space_fun X Y) := {f | (((((∀ x y : X, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀ x y : Y, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀ x y, f (x, y) = f (y, x))) ∧ (∀ x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀ x, f (x, x) = 0)) ∧ (∀ x y, f (x, y) ≤ max_var X Y) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb X Y) := {f : Cb X Y | (f : _ → ℝ) ∈ candidates X Y} end definitions --section section constructions variables {X : Type u} {Y : Type v} [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] {f : prod_space_fun X Y} {x y z t : X ⊕ Y} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var X Y := calc dist x y ≤ diam (univ : set (X ⊕ Y)) : dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _) ... = diam (range inl ∪ range inr : set (X ⊕ Y)) : by rw [range_inl_union_range_inr] ... ≤ diam (range inl : set (X ⊕ Y)) + dist (inl default) (inr default) + diam (range inr : set (X ⊕ Y)) : diam_union (mem_range_self _) (mem_range_self _) ... = diam (univ : set X) + (dist default default + 1 + dist default default) + diam (univ : set Y) : by { rw [isometry_inl.diam_range, isometry_inr.diam_range], refl } ... = 1 * diam (univ : set X) + 1 + 1 * diam (univ : set Y) : by simp ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates X Y) : f (x, y) = f (y, x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates X Y) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates X Y) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates X Y) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates X Y) (x y: X) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates X Y) (x y : Y) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates X Y) : f (x, y) ≤ max_var X Y := fA.2 x y /-- candidates are bounded by `max_var X Y` -/ private lemma candidates_dist_bound (fA : f ∈ candidates X Y) : ∀ {x y : X ⊕ Y}, f (x, y) ≤ max_var X Y * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq X Y, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var X Y * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var X Y : candidates_le_max_var fA ... = max_var X Y * 1 : by simp ... ≤ max_var X Y * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var X Y : candidates_le_max_var fA ... = max_var X Y * 1 : by simp ... ≤ max_var X Y * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq X Y, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var X Y * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates X Y) : f (x, y) - f (z, t) ≤ 2 * max_var X Y * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var X Y * dist x z + max_var X Y * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var X Y * max (dist x z) (dist t y) + max_var X Y * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var X Y)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var X Y)), end ... = 2 * max_var X Y * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var X Y * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates X Y) : lipschitz_with (2 * max_var X Y) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : Cb X Y := bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩ lemma candidates_b_of_candidates_mem (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : candidates_b_of_candidates f fA ∈ candidates_b X Y := fA /-- The distance on `X ⊕ Y` is a candidate -/ private lemma dist_mem_candidates : (λp : (X ⊕ Y) × (X ⊕ Y), dist p.1 p.2) ∈ candidates X Y := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end /-- The distance on `X ⊕ Y` as a candidate -/ def candidates_b_dist (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [inhabited X] [metric_space Y] [compact_space Y] [inhabited Y] : Cb X Y := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist X Y ∈ candidates_b X Y := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b X Y).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/ private lemma closed_candidates_b : is_closed (candidates_b X Y) := begin have I1 : ∀ x y, is_closed {f : Cb X Y | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_eval_const continuous_const, have I2 : ∀ x y, is_closed {f : Cb X Y | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_eval_const continuous_const, have I3 : ∀ x y, is_closed {f : Cb X Y | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_eval_const continuous_eval_const, have I4 : ∀ x y z, is_closed {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_eval_const (continuous_eval_const.add continuous_eval_const), have I5 : ∀ x, is_closed {f : Cb X Y | f (x, x) = 0} := λx, is_closed_eq continuous_eval_const continuous_const, have I6 : ∀ x y, is_closed {f : Cb X Y | f (x, y) ≤ max_var X Y} := λx y, is_closed_le continuous_eval_const continuous_const, have : candidates_b X Y = (⋂x y, {f : Cb X Y | f ((@inl X Y x), (@inl X Y y)) = dist x y}) ∩ (⋂x y, {f : Cb X Y | f ((@inr X Y x), (@inr X Y y)) = dist x y}) ∩ (⋂x y, {f : Cb X Y | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb X Y | f (x, x) = 0}) ∩ (⋂x y, {f : Cb X Y | f (x, y) ≤ max_var X Y}), { ext, simp only [candidates_b, candidates, mem_inter_iff, mem_Inter, mem_set_of_eq] }, rw this, repeat { apply is_closed.inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows. -/ private lemma is_compact_candidates_b : is_compact (candidates_b X Y) := begin refine arzela_ascoli₂ (Icc 0 (max_var X Y)) is_compact_Icc (candidates_b X Y) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var X Y * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var X Y : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var X Y * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { rintros x y ⟨f, hf⟩, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb X Y) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on `ℝ`, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb X Y} (C : ℝ) {x : X} : bdd_below (range (λ (y : Y), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb X Y) (C : ℝ) : bdd_above (range (λ (x : X), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr default) + C : cinfi_le (HD_below_aux1 C) default ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) le_rfl end lemma HD_below_aux2 {f : Cb X Y} (C : ℝ) {y : Y} : bdd_below (range (λ (x : X), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb X Y) (C : ℝ) : bdd_above (range (λ (y : Y), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl default, inr y) + C : cinfi_le (HD_below_aux2 C) default ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) le_rfl end /-- Explicit bound on `HD (dist)`. This means that when looking for minimizers it will be sufficient to look for functions with `HD(f)` bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist X Y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist X Y (inl x, inr y)) ≤ candidates_b_dist X Y (inl x, inr default) := cinfi_le (by simpa using HD_below_aux1 0) default, have B : dist (inl x) (inr default) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc dist (inl x) (inr (default : Y)) = dist x (default : X) + 1 + dist default default : rfl ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : begin apply add_le_add (add_le_add _ le_rfl), exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _), end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist X Y (inl x, inr y)) ≤ candidates_b_dist X Y (inl default, inr y) := cinfi_le (by simpa using HD_below_aux2 0) default, have B : dist (inl default) (inr y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc dist (inl (default : X)) (inr y) = dist default default + 1 + dist default y : rfl ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : begin apply add_le_add (add_le_add _ le_rfl), exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb X Y) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 g.bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_mono (HD_bound_aux1 _ (dist f g)) (λx, cinfi_mono ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀ x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : Y), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine monotone.map_csupr_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb X Y) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 g.bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_mono (HD_bound_aux2 _ (dist f g)) (λy, cinfi_mono ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀ y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:X, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine monotone.map_csupr_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb X Y) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb X Y → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃ f ∈ candidates_b X Y, ∀ g ∈ candidates_b X Y, HD f ≤ HD g := is_compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb X Y := classical.some (exists_minimizer X Y) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist X Y ∈ candidates_b X Y := by cases (classical.some_spec (exists_minimizer X Y)); assumption private lemma HD_optimal_GH_dist_le (g : Cb X Y) (hg : g ∈ candidates_b X Y) : HD (optimal_GH_dist X Y) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer X Y) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on `X ⊕ Y`, on which the predistance is given by the candidate. Then, we will identify points at `0` predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : pseudo_metric_space (X ⊕ Y) := { dist := λp q, optimal_GH_dist X Y (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b X Y), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b X Y), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b X Y) } local attribute [instance] premetric_optimal_GH_dist /-- A metric space which realizes the optimal coupling between `X` and `Y` -/ @[derive metric_space, nolint has_nonempty_instance] definition optimal_GH_coupling : Type* := @uniform_space.separation_quotient (X ⊕ Y) (premetric_optimal_GH_dist X Y).to_uniform_space /-- Injection of `X` in the optimal coupling between `X` and `Y` -/ def optimal_GH_injl (x : X) : optimal_GH_coupling X Y := quotient.mk' (inl x) /-- The injection of `X` in the optimal coupling between `X` and `Y` is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl X Y) := isometry.of_dist_eq $ λ x y, candidates_dist_inl (optimal_GH_dist_mem_candidates_b X Y) _ _ /-- Injection of `Y` in the optimal coupling between `X` and `Y` -/ def optimal_GH_injr (y : Y) : optimal_GH_coupling X Y := quotient.mk' (inr y) /-- The injection of `Y` in the optimal coupling between `X` and `Y` is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr X Y) := isometry.of_dist_eq $ λ x y, candidates_dist_inr (optimal_GH_dist_mem_candidates_b X Y) _ _ /-- The optimal coupling between two compact spaces `X` and `Y` is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling X Y) := ⟨begin rw [← range_quotient_mk'], exact is_compact_range (continuous_sum_dom.2 ⟨(isometry_optimal_GH_injl X Y).continuous, (isometry_optimal_GH_injr X Y).continuous⟩) end⟩ /-- For any candidate `f`, `HD(f)` is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b X Y) : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λ r hr, _)) (HD_optimal_GH_dist_le X Y f h), have A : ∀ x ∈ range (optimal_GH_injl X Y), ∃ y ∈ range (optimal_GH_injr X Y), dist x y ≤ r, { rintro _ ⟨z, rfl⟩, have I1 : (⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', ⟨z', rfl⟩, hr'⟩, exact ⟨optimal_GH_injr X Y z', mem_range_self _, le_of_lt hr'⟩ }, refine Hausdorff_dist_le_of_mem_dist _ A _, { inhabit X, rcases A _ (mem_range_self default) with ⟨y, -, hy⟩, exact le_trans dist_nonneg hy }, { rintro _ ⟨z, rfl⟩, have I1 : (⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', ⟨z', rfl⟩, hr'⟩, refine ⟨optimal_GH_injl X Y z', mem_range_self _, le_of_lt _⟩, rwa dist_comm } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
9ff4ce36d14881c2cb8df9e14b762648f0bd2182
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/tactic/induction.lean
db46e0e5899cf1b343c658cfc17f3b53686ebab3
[ "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
50,876
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import tactic.dependencies import tactic.fresh_names import tactic.generalizes import tactic.has_variable_names import tactic.unify_equations /-! # A better tactic for induction and case analysis This module defines the tactics `tactic.interactive.induction'` and `tactic.interactive.cases'`, which are variations on Lean's builtin `induction` and `cases`. The primed variants feature various improvements over the builtin tactics; in particular, they generate more human-friendly names and `induction'` deals much better with indexed inductive types. See the tactics' documentation for more details. We also provide corresponding non-interactive induction tactics `tactic.eliminate_hyp` and `tactic.eliminate_expr`. The design and implementation of these tactics is described in a [draft paper](https://limperg.de/paper/cpp2021-induction/). -/ open expr native open tactic.interactive (case_tag.from_tag_hyps) namespace tactic namespace eliminate /-! ## Tracing We set up two tracing functions to be used by `eliminate_hyp` and its supporting tactics. Their output is enabled by setting `trace.eliminate_hyp` to `true`. -/ declare_trace eliminate_hyp /-- `trace_eliminate_hyp msg` traces `msg` if the option `trace.eliminate_hyp` is `true`. -/ meta def trace_eliminate_hyp {α} [has_to_format α] (msg : thunk α) : tactic unit := when_tracing `eliminate_hyp $ trace $ to_fmt "eliminate_hyp: " ++ to_fmt (msg ()) /-- `trace_state_eliminate_hyp msg` traces `msg` followed by the tactic state if the option `trace.eliminate_hyp` is `true`. -/ meta def trace_state_eliminate_hyp {α} [has_to_format α] (msg : thunk α) : tactic unit := do state ← read, trace_eliminate_hyp $ format.join [to_fmt (msg ()), "\n-----\n", to_fmt state, "\n-----"] /-! ## Information Gathering We define data structures for information relevant to the induction, and functions to collect this information for a specific goal. -/ /-- Information about a constructor argument. E.g. given the declaration ``` induction ℕ : Type | zero : ℕ | suc (n : ℕ) : ℕ ``` the `zero` constructor has no arguments and the `suc` constructor has one argument, `n`. We record the following information: - `aname`: the argument's name. If the argument was not explicitly named in the declaration, the elaborator generates a name for it. - `type` : the argument's type. - `dependent`: whether the argument is dependent, i.e. whether it occurs in the remainder of the constructor type. - `index_occurrences`: the index arguments of the constructor's return type in which this argument occurs. If the constructor return type is `I i₀ ... iₙ` and the argument under consideration is `a`, and `a` occurs in `i₁` and `i₂`, then the `index_occurrences` are `1, 2`. As an additional requirement, for `iⱼ` to be considered an index occurrences, the type of `iⱼ` must match that of `a` according to `index_occurrence_type_match`. - `is_recursive`: whether this is a recursive constructor argument. -/ @[derive has_reflect] meta structure constructor_argument_info := (aname : name) (type : expr) (dependent : bool) (index_occurrences : list ℕ) (is_recursive : bool) /-- Information about a constructor. Contains: - `cname`: the constructor's name. - `non_param_args`: information about the arguments of the constructor, excluding the arguments induced by the parameters of the inductive type. - `num_non_param_args`: the length of `non_param_args`. - `rec_args`: the subset of `non_param_args` which are recursive constructor arguments. - `num_rec_args`: the length of `rec_args`. For example, take the constructor ``` list.cons : ∀ {α} (x : α) (xs : list α), list α ``` `α` is a parameter of `list`, so `non_param_args` contains information about `x` and `xs`. `rec_args` contains information about `xs`. -/ @[derive has_reflect] meta structure constructor_info := (cname : name) (non_param_args : list constructor_argument_info) (num_non_param_args : ℕ) (rec_args : list constructor_argument_info) (num_rec_args : ℕ) /-- When we construct the goal for the minor premise of a given constructor, this is the number of hypotheses we must name. -/ meta def constructor_info.num_nameable_hypotheses (c : constructor_info) : ℕ := c.num_non_param_args + c.num_rec_args /-- Information about an inductive type. Contains: - `iname`: the type's name. - `constructors`: information about the type's constructors. - `num_constructors`: the length of `constructors`. - `type`: the type's type. - `num_param`: the type's number of parameters. - `num_indices`: the type's number of indices. -/ @[derive has_reflect] meta structure inductive_info := (iname : name) (constructors : list constructor_info) (num_constructors : ℕ) (type : expr) (num_params : ℕ) (num_indices : ℕ) /-- Information about a major premise (i.e. the hypothesis on which we are performing induction). Contains: - `mpname`: the major premise's name. - `mpexpr`: the major premise itself. - `type`: the type of `mpexpr`. - `args`: the arguments of the major premise. The major premise has type `I x₀ ... xₙ`, where `I` is an inductive type. `args` is the map `[0 → x₀, ..., n → xₙ]`. -/ meta structure major_premise_info := (mpname : name) (mpexpr : expr) (type : expr) (args : rb_map ℕ expr) /-- `index_occurrence_type_match t s` is true iff `t` and `s` are definitionally equal. -/ -- We could extend this check to be more permissive. E.g. if a constructor -- argument has type `list α` and the index has type `list β`, we may want to -- consider these types sufficiently similar to inherit the name. Same (but even -- more obvious) with `vec α n` and `vec α (n + 1)`. meta def index_occurrence_type_match (t s : expr) : tactic bool := succeeds $ is_def_eq t s /-- From the return type of a constructor `C` of an inductive type `I`, determine the index occurrences of the constructor arguments of `C`. Input: - `num_params:` the number of parameters of `I`. - `ret_type`: the return type of `C`. `e` must be of the form `I x₁ ... xₙ`. Output: A map associating each local constant `c` that appears in any of the `xᵢ` with the set of indexes `j` such that `c` appears in `xⱼ` and `xⱼ`'s type matches that of `c` according to `tactic.index_occurrence_type_match`. -/ meta def get_index_occurrences (num_params : ℕ) (ret_type : expr) : tactic (rb_lmap expr ℕ) := do ret_args ← get_app_args_whnf ret_type, ret_args.mfoldl_with_index (λ i occ_map ret_arg, do if i < num_params then pure occ_map else do let ret_arg_consts := ret_arg.list_local_consts', ret_arg_consts.mfold occ_map $ λ c occ_map, do ret_arg_type ← infer_type ret_arg, eq ← index_occurrence_type_match c.local_type ret_arg_type, pure $ if eq then occ_map.insert c i else occ_map) mk_rb_map /-- Returns true iff `arg_type` is the local constant named `type_name` (possibly applied to some arguments). If `arg_type` is the type of an argument of one of `type_name`'s constructors and this function returns true, then the constructor argument is a recursive occurrence. -/ meta def is_recursive_constructor_argument (type_name : name) (arg_type : expr) : bool := let base := arg_type.get_app_fn in match base with | (expr.const base _) := base = type_name | _ := ff end /-- Get information about the arguments of a constructor `C` of an inductive type `I`. Input: - `inductive_name`: the name of `I`. - `num_params`: the number of parameters of `I`. - `T`: the type of `C`. Output: a `constructor_argument_info` structure for each argument of `C`. -/ meta def get_constructor_argument_info (inductive_name : name) (num_params : ℕ) (T : expr) : tactic (list constructor_argument_info) := do ⟨args, ret⟩ ← open_pis_whnf_dep T, index_occs ← get_index_occurrences num_params ret, pure $ args.map $ λ ⟨c, dep⟩, let occs := rb_set.of_list $ index_occs.find c in let type := c.local_type in let is_recursive := is_recursive_constructor_argument inductive_name type in ⟨c.local_pp_name, type, dep, occs.to_list, is_recursive⟩ /-- Get information about a constructor `C` of an inductive type `I`. Input: - `iname`: the name of `I`. - `num_params`: the number of parameters of `I`. - `c` : the name of `C`. Output: A `constructor_info` structure for `C`. -/ meta def get_constructor_info (iname : name) (num_params : ℕ) (c : name) : tactic constructor_info := do env ← get_env, when (¬ env.is_constructor c) $ fail! "Expected {c} to be a constructor.", decl ← env.get c, args ← get_constructor_argument_info iname num_params decl.type, let non_param_args := args.drop num_params, let rec_args := non_param_args.filter $ λ ainfo, ainfo.is_recursive, pure { cname := decl.to_name, non_param_args := non_param_args, num_non_param_args := non_param_args.length, rec_args := rec_args, num_rec_args := rec_args.length } /-- Get information about an inductive type `I`, given `I`'s name. -/ meta def get_inductive_info (I : name) : tactic inductive_info := do env ← get_env, when (¬ env.is_inductive I) $ fail! "Expected {I} to be an inductive type.", decl ← env.get I, let type := decl.type, let num_params := env.inductive_num_params I, let num_indices := env.inductive_num_indices I, let constructor_names := env.constructors_of I, constructors ← constructor_names.mmap (get_constructor_info I num_params), pure { iname := I, constructors := constructors, num_constructors := constructors.length, type := type, num_params := num_params, num_indices := num_indices } /-- Get information about a major premise. The given `expr` must be a local hypothesis. -/ meta def get_major_premise_info (major_premise : expr) : tactic major_premise_info := do type ← infer_type major_premise, ⟨f, args⟩ ← get_app_fn_args_whnf type, pure { mpname := major_premise.local_pp_name, mpexpr := major_premise, type := type, args := args.to_rb_map } /-! ## Constructor Argument Naming We define the algorithm for naming constructor arguments (which is a remarkably big part of the tactic). -/ /-- Information used when naming a constructor argument. -/ meta structure constructor_argument_naming_info := (mpinfo : major_premise_info) (iinfo : inductive_info) (cinfo : constructor_info) (ainfo : constructor_argument_info) /-- A constructor argument naming rule takes a `constructor_argument_naming_info` structure and returns a list of suitable names for the argument. If the rule is not applicable to the given constructor argument, the returned list is empty. -/ @[reducible] meta def constructor_argument_naming_rule : Type := constructor_argument_naming_info → tactic (list name) /-- Naming rule for recursive constructor arguments. -/ meta def constructor_argument_naming_rule_rec : constructor_argument_naming_rule := λ i, pure $ if i.ainfo.is_recursive then [i.mpinfo.mpname] else [] /-- Naming rule for constructor arguments associated with an index. -/ meta def constructor_argument_naming_rule_index : constructor_argument_naming_rule := λ i, let index_occs := i.ainfo.index_occurrences in let major_premise_args := i.mpinfo.args in let get_major_premise_arg_local_names : ℕ → option (name × name) := λ i, do { arg ← major_premise_args.find i, (uname, ppname, _) ← arg.match_local_const, pure (uname, ppname) } in let local_index_instantiations := (index_occs.map get_major_premise_arg_local_names).all_some in /- Right now, this rule only triggers if the major premise arg is exactly a local const. We could consider a more permissive rule where the major premise arg can be an arbitrary term as long as that term *contains* only a single local const. -/ pure $ match local_index_instantiations with | none := [] | some [] := [] | some ((uname, ppname) :: is) := if is.all (λ ⟨uname', _⟩, uname' = uname) then [ppname] else [] end /-- Naming rule for constructor arguments which are named in the constructor declaration. -/ meta def constructor_argument_naming_rule_named : constructor_argument_naming_rule := λ i, let arg_name := i.ainfo.aname in let arg_dep := i.ainfo.dependent in pure $ if ! arg_dep && arg_name.is_likely_generated_binder_name then [] else [arg_name] /-- Naming rule for constructor arguments whose type is associated with a list of typical variable names. See `tactic.typical_variable_names`. -/ meta def constructor_argument_naming_rule_type : constructor_argument_naming_rule := λ i, typical_variable_names i.ainfo.type <|> pure [] /-- Naming rule for constructor arguments whose type is in `Prop`. -/ meta def constructor_argument_naming_rule_prop : constructor_argument_naming_rule := λ i, do (sort level.zero) ← infer_type i.ainfo.type | pure [], pure [`h] /-- Fallback constructor argument naming rule. This rule never fails. -/ meta def constructor_argument_naming_rule_fallback : constructor_argument_naming_rule := λ _, pure [`x] /-- `apply_constructor_argument_naming_rules info rules` applies the constructor argument naming rules in `rules` to the constructor argument given by `info`. Returns the result of the first applicable rule. Fails if no rule is applicable. -/ meta def apply_constructor_argument_naming_rules (info : constructor_argument_naming_info) (rules : list constructor_argument_naming_rule) : tactic (list name) := do names ← try_core $ rules.mfirst (λ r, do names ← r info, match names with | [] := failed | _ := pure names end), match names with | none := fail "apply_constructor_argument_naming_rules: no applicable naming rule" | (some names) := pure names end /-- Get possible names for a constructor argument. This tactic applies all the previously defined rules in order. It cannot fail and always returns a nonempty list. -/ meta def constructor_argument_names (info : constructor_argument_naming_info) : tactic (list name) := apply_constructor_argument_naming_rules info [ constructor_argument_naming_rule_rec , constructor_argument_naming_rule_index , constructor_argument_naming_rule_named , constructor_argument_naming_rule_type , constructor_argument_naming_rule_prop , constructor_argument_naming_rule_fallback ] /-- `intron_fresh n` introduces `n` hypotheses with names generated by `tactic.mk_fresh_name`. -/ meta def intron_fresh (n : ℕ) : tactic (list expr) := iterate_exactly n (mk_fresh_name >>= intro) /-- Introduce the new hypotheses generated by the minor premise for a given constructor. The new hypotheses are given fresh (unique, non-human-friendly) names. They are later renamed by `constructor_renames`. We delay the generation of the human-friendly names because when `constructor_renames` is called, more names may have become unused. Input: - `generate_induction_hyps`: whether we generate induction hypotheses (i.e. whether `eliminate_hyp` is in `induction` or `cases` mode). - `cinfo`: information about the constructor. Output: - For each constructor argument, the pretty name of the newly introduced hypothesis corresponding to the argument and its `constructor_argument_info`. - For each newly introduced induction hypothesis, its pretty name and the name of the recursive constructor argument from which it was derived. -/ meta def constructor_intros (generate_induction_hyps : bool) (cinfo : constructor_info) : tactic (list (name × constructor_argument_info) × list (name × name)) := do let args := cinfo.non_param_args, arg_hyps ← intron_fresh cinfo.num_non_param_args, let arg_hyp_names := list.map₂ (λ (h : expr) ainfo, (h.local_pp_name, ainfo)) arg_hyps args, tt ← pure generate_induction_hyps | pure (arg_hyp_names, []), let rec_args := arg_hyp_names.filter $ λ x, x.2.is_recursive, ih_hyps ← intron_fresh cinfo.num_rec_args, let ih_hyp_names := list.map₂ (λ (h : expr) (arg : name × constructor_argument_info), (h.local_pp_name, arg.1)) ih_hyps rec_args, pure (arg_hyp_names, ih_hyp_names) /-- `ih_name arg_name` is the name `ih_<arg_name>`. -/ meta def ih_name (arg_name : name) : name := mk_simple_name ("ih_" ++ arg_name.to_string) private meta def get_with_name : option name → option name | (some `_) := none | (some n) := some n | none := none /-- Rename the new hypotheses in the goal for a minor premise. Input: - `generate_induction_hyps`: whether we generate induction hypotheses (i.e. whether `eliminate_hyp` is in `induction` or `cases` mode). - `mpinfo`: information about the major premise. - `iinfo`: information about the inductive type. - `cinfo`: information about the constructor whose minor premise we are processing. - `with_names`: a list of names given by the user. These are used to name constructor arguments and induction hypotheses. Our own naming logic only kicks in if this list does not contain enough names. - `args` and `ihs`: the output of `constructor_intros`. Output: - The newly introduced hypotheses corresponding to constructor arguments. - The newly introduced induction hypotheses. -/ meta def constructor_renames (generate_induction_hyps : bool) (mpinfo : major_premise_info) (iinfo : inductive_info) (cinfo : constructor_info) (with_names : list name) (args : list (name × constructor_argument_info)) (ihs : list (name × name)) : tactic (list expr × list expr) := do -- Rename constructor arguments let arg_pp_name_set := name_set.of_list $ args.map prod.fst, let iname := iinfo.iname, let ⟨args, with_names⟩ := args.zip_left' with_names, arg_renames : list (name × list name) ← args.mmap_filter $ λ ⟨⟨old_ppname, ainfo⟩, with_name⟩, do { new ← match get_with_name with_name with | some with_name := pure [with_name] | none := constructor_argument_names ⟨mpinfo, iinfo, cinfo, ainfo⟩ end, -- Some of the arg hyps may have been cleared by earlier simplification -- steps, so get_local may fail. (some old) ← try_core $ get_local old_ppname | pure none, pure $ some (old.local_uniq_name, new) }, let arg_renames := rb_map.of_list arg_renames, arg_hyp_map ← rename_fresh arg_renames mk_name_set, let new_arg_hyps := arg_hyp_map.filter_map $ λ ⟨old, new⟩, if arg_pp_name_set.contains old.local_pp_name then some new else none, let arg_hyp_map : name_map expr := rb_map.of_list $ arg_hyp_map.map $ λ ⟨old, new⟩, (old.local_pp_name, new), -- Rename induction hypotheses (if we generated them) tt ← pure generate_induction_hyps | pure (new_arg_hyps, []), let ih_pp_name_set := name_set.of_list $ ihs.map prod.fst, let ihs := ihs.zip_left with_names, ih_renames ← ihs.mmap_filter $ λ ⟨⟨ih_hyp_ppname, arg_hyp_ppname⟩, with_name⟩, do { some arg_hyp ← pure $ arg_hyp_map.find arg_hyp_ppname | fail! "internal error in constructor_renames", let new := match get_with_name with_name with | some with_name := sum.inl with_name | none := sum.inr $ ih_name arg_hyp.local_pp_name end, (some ih_hyp) ← try_core $ get_local ih_hyp_ppname | pure none, pure $ some (ih_hyp.local_uniq_name, new) }, let ih_renames : list (name × list name) := -- Special case: When there's only one IH and it hasn't been named -- explicitly in a "with" clause, we call it simply "ih" (unless that name -- is already taken). match ih_renames with | [(h, sum.inr n)] := [(h, ["ih", n])] | ns := ns.map (λ ⟨h, n⟩, (h, [n.elim id id])) end, ih_hyp_map ← rename_fresh (rb_map.of_list ih_renames) mk_name_set, let new_ih_hyps := ih_hyp_map.filter_map $ λ ⟨old, new⟩, if ih_pp_name_set.contains old.local_pp_name then some new else none, pure (new_arg_hyps, new_ih_hyps) /-! ## Generalisation `induction'` can generalise the goal before performing an induction, which gives us a more general induction hypothesis. We call this 'auto-generalisation'. -/ /-- A value of `generalization_mode` describes the behaviour of the auto-generalisation functionality: - `generalize_all_except hs` means that the `hs` remain fixed and all other hypotheses are generalised. However, there are three exceptions: * Hypotheses depending on any `h` in `hs` also remain fixed. If we were to generalise them, we would have to generalise `h` as well. * Hypotheses which do not occur in the target and which do not mention the major premise or its dependencies are never generalised. Generalising them would not lead to a more general induction hypothesis. * Frozen local instances and their dependencies are never generalised. - `generalize_only hs` means that only the `hs` are generalised. Exception: hypotheses which depend on the major premise are generalised even if they do not appear in `hs`. -/ @[derive has_reflect] inductive generalization_mode | generalize_all_except (hs : list name) : generalization_mode | generalize_only (hs : list name) : generalization_mode instance : inhabited generalization_mode := ⟨ generalization_mode.generalize_all_except []⟩ namespace generalization_mode /-- Given the major premise and a generalization_mode, this function returns the unique names of the hypotheses that should be generalized. See `generalization_mode` for what these are. -/ meta def to_generalize (major_premise : expr) : generalization_mode → tactic name_set | (generalize_only ns) := do major_premise_rev_deps ← reverse_dependencies_of_hyps [major_premise], let major_premise_rev_deps := name_set.of_list $ major_premise_rev_deps.map local_uniq_name, ns ← ns.mmap (functor.map local_uniq_name ∘ get_local), pure $ major_premise_rev_deps.insert_list ns | (generalize_all_except fixed) := do fixed ← fixed.mmap get_local, tgt ← target, let tgt_dependencies := tgt.list_local_const_unique_names, major_premise_type ← infer_type major_premise, major_premise_dependencies ← dependency_name_set_of_hyp_inclusive major_premise, fixed_dependencies ← (major_premise :: fixed).mmap dependency_name_set_of_hyp_inclusive, let fixed_dependencies := fixed_dependencies.foldl name_set.union mk_name_set, ctx ← revertible_local_context, to_revert ← ctx.mmap_filter $ λ h, do { h_depends_on_major_premise_deps ← -- TODO `hyp_depends_on_local_name_set` is somewhat expensive hyp_depends_on_local_name_set h major_premise_dependencies, let h_name := h.local_uniq_name, let rev := ¬ fixed_dependencies.contains h_name ∧ (h_depends_on_major_premise_deps ∨ tgt_dependencies.contains h_name), /- I think `h_depends_on_major_premise_deps` is an overapproximation. What we actually want is any hyp that depends either on the major_premise or on one of the major_premise's index args. (But the overapproximation seems to work okay in practice as well.) -/ pure $ if rev then some h_name else none }, pure $ name_set.of_list to_revert end generalization_mode /-- Generalize hypotheses for the given major premise and generalization mode. See `generalization_mode` and `to_generalize`. -/ meta def generalize_hyps (major_premise : expr) (gm : generalization_mode) : tactic ℕ := do to_revert ← gm.to_generalize major_premise, ⟨n, _⟩ ← revert_name_set to_revert, pure n /-! ## Complex Index Generalisation A *complex* expression is any expression that is not merely a local constant. When such a complex expression appears as an argument of the major premise, and when that argument is an index of the inductive type, we must generalise the complex expression. E.g. when we operate on the major premise `fin (2 + n)` (assuming that `fin` is encoded as an inductive type), the `2 + n` is a complex index argument. To generalise it, we replace it with a new hypothesis `index : ℕ` and add an equation `induction_eq : index = 2 + n`. -/ /-- Generalise the complex index arguments. Input: - `major premise`: the major premise. - `num_params`: the number of parameters of the inductive type. - `generate_induction_hyps`: whether we generate induction hypotheses (i.e. whether `eliminate_hyp` is in `induction` or `cases` mode). Output: - The new major premise. This procedure may change the major premise's type signature, so the old major premise hypothesis is invalidated. - The number of index placeholder hypotheses we introduced. - The index placeholder hypotheses we introduced. - The number of hypotheses which were reverted because they contain complex indices. -/ /- TODO The following function currently replaces complex index arguments everywhere in the goal, not only in the major premise. Such replacements are sometimes necessary to make sure that the goal remains type-correct. However, the replacements can also have the opposite effect, yielding unprovable subgoals. The test suite contains one such case. There is probably a middle ground between 'replace everywhere' and 'replace only in the major premise', but I don't know what exactly this middle ground is. See also the discussion at https://github.com/leanprover-community/mathlib/pull/5027#discussion_r538902424 -/ meta def generalize_complex_index_args (major_premise : expr) (num_params : ℕ) (generate_induction_hyps : bool) : tactic (expr × ℕ × list name × ℕ) := focus1 $ do major_premise_type ← infer_type major_premise, (major_premise_head, major_premise_args) ← get_app_fn_args_whnf major_premise_type, let ⟨major_premise_param_args, major_premise_index_args⟩ := major_premise_args.split_at num_params, -- TODO Add equations only for complex index args (not all index args). -- This shouldn't matter semantically, but we'd get simpler terms. let js := major_premise_index_args, ctx ← revertible_local_context, tgt ← target, major_premise_deps ← dependency_name_set_of_hyp_inclusive major_premise, -- Revert the hypotheses which depend on the index args or the major_premise. -- We exclude dependencies of the major premise because we can't replace their -- index occurrences anyway when we apply the recursor. relevant_ctx ← ctx.mfilter $ λ h, do { let dep_of_major_premise := major_premise_deps.contains h.local_uniq_name, dep_on_major_premise ← hyp_depends_on_locals h [major_premise], H ← infer_type h, dep_of_index ← js.many $ λ j, kdepends_on H j, -- TODO We need a variant of `kdepends_on` that takes local defs into account. pure $ (dep_on_major_premise ∧ h ≠ major_premise) ∨ (dep_of_index ∧ ¬ dep_of_major_premise) }, ⟨relevant_ctx_size, relevant_ctx⟩ ← revert_lst' relevant_ctx, revert major_premise, -- Create the local constants that will replace the index args. We have to be -- careful to get the right types. let go : expr → list expr → tactic (list expr) := λ j ks, do { J ← infer_type j, k ← mk_local' `index binder_info.default J, ks ← ks.mmap $ λ k', kreplace k' j k, pure $ k :: ks }, ks ← js.mfoldr go [], let js_ks := js.zip ks, -- Replace the index args in the relevant context. new_ctx ← relevant_ctx.mmap $ λ h, js_ks.mfoldr (λ ⟨j, k⟩ h, kreplace h j k) h, -- Replace the index args in the major premise. let new_major_premise_type := major_premise_head.mk_app (major_premise_param_args ++ ks), let new_major_premise := local_const major_premise.local_uniq_name major_premise.local_pp_name major_premise.binding_info new_major_premise_type, -- Replace the index args in the target. new_tgt ← js_ks.mfoldr (λ ⟨j, k⟩ tgt, kreplace tgt j k) tgt, let new_tgt := new_tgt.pis (new_major_premise :: new_ctx), -- Generate the index equations and their proofs. let eq_name := if generate_induction_hyps then `induction_eq else `cases_eq, let step2_input := js_ks.map $ λ ⟨j, k⟩, (eq_name, j, k), eqs_and_proofs ← generalizes.step2 reducible step2_input, let eqs := eqs_and_proofs.map prod.fst, let eq_proofs := eqs_and_proofs.map prod.snd, -- Assert the generalized goal and derive the current goal from it. generalizes.step3 new_tgt js ks eqs eq_proofs, -- Introduce the index variables and major premise. The index equations -- and the relevant context remain reverted. let num_index_vars := js.length, index_vars ← intron' num_index_vars, index_equations ← intron' num_index_vars, major_premise ← intro1, revert_lst index_equations, let index_vars := index_vars.map local_pp_name, pure (major_premise, index_vars.length, index_vars, relevant_ctx_size) /-! ## Simplification of Induction Hypotheses Auto-generalisation and complex index generalisation may produce unnecessarily complex induction hypotheses. We define a simplification algorithm that recovers understandable induction hypotheses in many practical cases. -/ /-- Process one index equation for `simplify_ih`. Input: a local constant `h : x = y` or `h : x == y`. Output: A proof of `x = y` or `x == y` and possibly a local constant of type `x = y` or `x == y` used in the proof. More specifically: - For `h : x = y` and `x` defeq `y`, we return the proof of `x = y` by reflexivity and `none`. - For `h : x = y` and `x` not defeq `y`, we return `h` and `h`. - For `h : x == y` where `x` and `y` have defeq types: - If `x` defeq `y`, we return the proof of `x == y` by reflexivity and `none`. - If `x` not defeq `y`, we return `heq_of_eq h'` and a fresh local constant `h' : x = y`. - For `h : x == y` where `x` and `y` do not have defeq types, we return `h` and `h`. Checking for definitional equality of the left- and right-hand sides may assign metavariables. -/ meta def process_index_equation : expr → tactic (expr × option expr) | h@(local_const _ ppname binfo T@(app (app (app (const `eq [u]) type) lhs) rhs)) := do rhs_eq_lhs ← succeeds $ unify lhs rhs, if rhs_eq_lhs then pure ((const `eq.refl [u]) type lhs, none) else do pure (h, some h) | h@(local_const uname ppname binfo T@(app (app (app (app (const `heq [u]) lhs_type) lhs) rhs_type) rhs)) := do lhs_type_eq_rhs_type ← succeeds $ is_def_eq lhs_type rhs_type, if ¬ lhs_type_eq_rhs_type then do pure (h, some h) else do lhs_eq_rhs ← succeeds $ unify lhs rhs, if lhs_eq_rhs then pure ((const `heq.refl [u]) lhs_type lhs, none) else do c ← mk_local' ppname binfo $ (const `eq [u]) lhs_type lhs rhs, let arg := (const `heq_of_eq [u]) lhs_type lhs rhs c, pure (arg, some c) | (local_const _ _ _ T) := fail! "process_index_equation: expected a homogeneous or heterogeneous equation, but got:\n{T}" | e := fail! "process_index_equation: expected a local constant, but got:\n{e}" /-- `assign_local_to_unassigned_mvar mv pp_name binfo`, where `mv` is a metavariable, acts as follows: - If `mv` is assigned, it is not changed and the tactic returns `none`. - If `mv` is not assigned, it is assigned a fresh local constant with the type of `mv`, pretty name `pp_name` and binder info `binfo`. This local constant is returned. -/ meta def assign_local_to_unassigned_mvar (mv : expr) (pp_name : name) (binfo : binder_info) : tactic (option expr) := do ff ← is_assigned mv | pure none, type ← infer_type mv, c ← mk_local' pp_name binfo type, unify mv c, pure c /-- Apply `assign_local_to_unassigned_mvar` to a list of metavariables. Returns the newly created local constants. -/ meta def assign_locals_to_unassigned_mvars (mvars : list (expr × name × binder_info)) : tactic (list expr) := mvars.mmap_filter $ λ ⟨mv, pp_name, binfo⟩, assign_local_to_unassigned_mvar mv pp_name binfo /-- Simplify an induction hypothesis. Input: a local constant ``` ih : ∀ (x₁ : T₁) ... (xₙ : Tₙ) (eq₁ : y₁ = z₁) ... (eqₘ : yₘ = zₘ), P ``` where `n = num_generalized` and `m = num_index_vars`. The `xᵢ` are hypotheses that we generalised over before performing induction. The `eqᵢ` are index equations. Output: a new local constant ``` ih' : ∀ (x'₁ : T'₁) ... (x'ₖ : T'ₖ) (eq'₁ : y'₁ = z'₁) ... (eq'ₗ : y'ₗ = z'ₗ), P' ``` This new induction hypothesis is derived from `ih` by removing those `eqᵢ` whose left- and right-hand sides can be unified. This unification may also determine some of the `xᵢ`. The `x'ᵢ` and `eq'ᵢ` are those `xᵢ` and `eqᵢ` that were not removed by this process. Some of the `eqᵢ` may be heterogeneous: `eqᵢ : yᵢ == zᵢ`. In this case, we proceed as follows: - If `yᵢ` and `zᵢ` are defeq, then `eqᵢ` is removed. - If `yᵢ` and `zᵢ` are not defeq but their types are, then `eqᵢ` is replaced by `eq'ᵢ : x = y`. - Otherwise `eqᵢ` remains unchanged. -/ /- TODO `simplify_ih` currently uses Lean's builtin unification procedure to process the index equations. This procedure has some limitations. For example, we would like to clear an IH that assumes `0 = 1` since this IH can never be applied, but Lean's unification doesn't allow us to conclude this. It would therefore be preferable to use the algorithm from `tactic.unify_equations` instead. There is no problem with this in principle, but it requires a complete refactoring of `unify_equations` so that it works not only on hypotheses but on arbitrary terms. -/ meta def simplify_ih (num_generalized : ℕ) (num_index_vars : ℕ) (ih : expr) : tactic expr := do T ← infer_type ih, -- Replace the `xᵢ` with fresh metavariables. (generalized_arg_mvars, body) ← open_n_pis_metas' T num_generalized, -- Replace the `eqᵢ` with fresh local constants. (index_eq_lcs, body) ← open_n_pis body num_index_vars, -- Process the `eqᵢ` local constants, yielding -- - `new_args`: proofs of `yᵢ = zᵢ`. -- - `new_index_eq_lcs`: local constants of type `yᵢ = zᵢ` or `yᵢ == zᵢ` used -- in `new_args`. new_index_eq_lcs_new_args ← index_eq_lcs.mmap process_index_equation, let (new_args, new_index_eq_lcs) := new_index_eq_lcs_new_args.unzip, let new_index_eq_lcs := new_index_eq_lcs.reduce_option, -- Assign fresh local constants to those `xᵢ` metavariables that were not -- assigned by the previous step. new_generalized_arg_lcs ← assign_locals_to_unassigned_mvars generalized_arg_mvars, -- Instantiate the metavariables assigned in the previous steps. new_generalized_arg_lcs ← new_generalized_arg_lcs.mmap instantiate_mvars, new_index_eq_lcs ← new_index_eq_lcs.mmap instantiate_mvars, -- Construct a proof of the new induction hypothesis by applying `ih` to the -- `xᵢ` metavariables and the `new_args`, then abstracting over the -- `new_index_eq_lcs` and the `new_generalized_arg_lcs`. b ← instantiate_mvars $ ih.mk_app (generalized_arg_mvars.map prod.fst ++ new_args), new_ih ← lambdas (new_generalized_arg_lcs ++ new_index_eq_lcs) b, -- Type-check the new induction hypothesis as a sanity check. type_check new_ih <|> fail! "internal error in simplify_ih: constructed term does not type check:\n{new_ih}", -- Replace the old induction hypothesis with the new one. ih' ← note ih.local_pp_name none new_ih, clear ih, pure ih' /-! ## Temporary utilities The utility functions in this section should be removed pending certain changes to Lean's standard library. -/ /-- Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag` is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was applied. `rs` should contain, for each subgoal, the constructor name associated with that goal and the hypotheses that were introduced. -/ -- TODO Copied from init.meta.interactive. Make that function non-private. meta def set_cases_tags (in_tag : tag) (rs : list (name × list expr)) : tactic unit := do gs ← get_goals, match gs with -- if only one goal was produced, we should not make the tag longer | [g] := set_tag g in_tag | _ := let tgs : list (name × list expr × expr) := rs.map₂ (λ ⟨n, new_hyps⟩ g, ⟨n, new_hyps, g⟩) gs in tgs.mmap' $ λ ⟨n, new_hyps, g⟩, with_enable_tags $ set_tag g $ (case_tag.from_tag_hyps (n :: in_tag) (new_hyps.map expr.local_uniq_name)).render end end eliminate /-! ## The Elimination Tactics Finally, we define the tactics `induction'` and `cases'` tactics as well as the non-interactive variant `eliminate_hyp.` -/ open eliminate /-- `eliminate_hyp generate_ihs h gm with_names` performs induction or case analysis on the hypothesis `h`. If `generate_ihs` is true, the tactic performs induction, otherwise case analysis. In case analysis mode, `eliminate_hyp` is very similar to `tactic.cases`. The only differences (assuming no bugs in `eliminate_hyp`) are that `eliminate_hyp` can do case analysis on a slightly larger class of hypotheses and that it generates more human-friendly names. In induction mode, `eliminate_hyp` is similar to `tactic.induction`, but with more significant differences: - If `h` (the hypothesis we are performing induction on) has complex indices, `eliminate_hyp` 'remembers' them. A complex expression is any expression that is not merely a local hypothesis. A hypothesis `h : I p₁ ... pₙ j₁ ... jₘ`, where `I` is an inductive type with `n` parameters and `m` indices, has a complex index if any of the `jᵢ` are complex. In this situation, standard `induction` effectively forgets the exact values of the complex indices, which often leads to unprovable goals. `eliminate_hyp` 'remembers' them by adding propositional equalities. As a result, you may find equalities named `induction_eq` in your goal, and the induction hypotheses may also quantify over additional equalities. - `eliminate_hyp` generalises induction hypotheses as much as possible by default. This means that if you eliminate `n` in the goal ``` n m : ℕ ⊢ P n m ``` the induction hypothesis is `∀ m, P n m` instead of `P n m`. You can modify this behaviour by giving a different generalisation mode `gm`; see `tactic.eliminate.generalization_mode`. - `eliminate_hyp` generates much more human-friendly names than `induction`. It also clears more redundant hypotheses. - `eliminate_hyp` currently does not support custom induction principles a la `induction using`. If `with_names` is nonempty, `eliminate_hyp` uses the given names for the new hypotheses it introduces (like `cases with` and `induction with`). To debug this tactic, use ``` set_option trace.eliminate_hyp true ``` -/ meta def eliminate_hyp (generate_ihs : bool) (major_premise : expr) (gm := generalization_mode.generalize_all_except []) (with_names : list name := []) : tactic unit := focus1 $ do mpinfo ← get_major_premise_info major_premise, let major_premise_type := mpinfo.type, let major_premise_args := mpinfo.args.values.reverse, env ← get_env, -- Get info about the inductive type iname ← get_app_fn_const_whnf major_premise_type <|> fail! "The type of {major_premise} should be an inductive type, but it is\n{major_premise_type}", iinfo ← get_inductive_info iname, -- We would like to disallow mutual/nested inductive types, since these have -- complicated recursors which we probably don't support. However, there seems -- to be no way to find out whether an inductive type is mutual/nested. -- (`environment.is_ginductive` doesn't seem to work.) trace_state_eliminate_hyp "State before complex index generalisation:", -- Generalise complex indices (major_premise, num_index_vars, index_var_names, num_index_generalized) ← generalize_complex_index_args major_premise iinfo.num_params generate_ihs, trace_state_eliminate_hyp "State after complex index generalisation and before auto-generalisation:", -- Generalise hypotheses according to the given generalization_mode. num_auto_generalized ← generalize_hyps major_premise gm, let num_generalized := num_index_generalized + num_auto_generalized, -- NOTE: The previous step may have changed the unique names of all hyps in -- the context. -- Record the current case tag and the unique names of all hypotheses in the -- context. in_tag ← get_main_tag, trace_state_eliminate_hyp "State after auto-generalisation and before recursor application:", -- Apply the recursor. We first try the nondependent recursor, then the -- dependent recursor (if available). -- Construct a pexpr `@rec _ ... _ major_premise`. Why not -- ```(%%rec %%major_premise)?` Because for whatever reason, `false.rec_on` -- takes the motive not as an implicit argument, like any other recursor, but -- as an explicit one. Why not something based on `mk_app` or `mk_mapp`? -- Because we need the special elaborator support for `elab_as_eliminator` -- definitions. let rec_app : name → pexpr := λ rec_suffix, (unchecked_cast expr.mk_app : pexpr → list pexpr → pexpr) (pexpr.mk_explicit (const (iname ++ rec_suffix) [])) (list.repeat pexpr.mk_placeholder (major_premise_args.length + 1) ++ [to_pexpr major_premise]), let rec_suffix := if generate_ihs then "rec_on" else "cases_on", let drec_suffix := if generate_ihs then "drec_on" else "dcases_on", interactive.apply (rec_app rec_suffix) <|> interactive.apply (rec_app drec_suffix) <|> fail! "Failed to apply the (dependent) recursor for {iname} on {major_premise}.", -- Prepare the "with" names for each constructor case. let with_names := prod.fst $ with_names.take_list (iinfo.constructors.map constructor_info.num_nameable_hypotheses), let constrs := iinfo.constructors.zip with_names, -- For each case (constructor): cases : list (option (name × list expr)) ← focus $ constrs.map $ λ ⟨cinfo, with_names⟩, do { trace_eliminate_hyp "============", trace_eliminate_hyp $ format! "Case {cinfo.cname}", trace_state_eliminate_hyp "Initial state:", -- Get the major premise's arguments. (Some of these may have changed due -- to the generalising step above.) major_premise_type ← infer_type major_premise, major_premise_args ← get_app_args_whnf major_premise_type, -- Clear the eliminated hypothesis (if possible) try $ clear major_premise, -- Clear the index args (unless other stuff in the goal depends on them) major_premise_args.mmap' (try ∘ clear), trace_state_eliminate_hyp "State after clearing the major premise (and its arguments) and before introductions:", -- Introduce the constructor arguments (constructor_arg_names, ih_names) ← constructor_intros generate_ihs cinfo, -- Introduce the auto-generalised hypotheses. intron num_auto_generalized, -- Introduce the index equations index_equations ← intron' num_index_vars, let index_equations := index_equations.map local_pp_name, -- Introduce the hypotheses that were generalised during index -- generalisation. intron num_index_generalized, trace_state_eliminate_hyp "State after introductions and before simplifying index equations:", -- Simplify the index equations. Stop after this step if the goal has been -- solved by the simplification. ff ← unify_equations index_equations | trace_eliminate_hyp "Case solved while simplifying index equations." >> pure none, trace_state_eliminate_hyp "State after simplifying index equations and before simplifying IHs:", -- Simplify the induction hypotheses -- NOTE: The previous step may have changed the unique names of the -- induction hypotheses, so we have to locate them again. Their pretty -- names should be unique in the context, so we can use these. (ih_names.map prod.fst).mmap' (get_local >=> simplify_ih num_auto_generalized num_index_vars), trace_state_eliminate_hyp "State after simplifying IHs and before clearing index variables:", -- Try to clear the index variables. These often become unused during -- the index equation simplification step. index_var_names.mmap $ λ h, try (get_local h >>= clear), trace_state_eliminate_hyp "State after clearing index variables and before renaming:", -- Rename the constructor names and IHs. We do this here (rather than -- earlier, when we introduced them) because there may now be less -- hypotheses in the context, and therefore more of the desired -- names may be free. (constructor_arg_hyps, ih_hyps) ← constructor_renames generate_ihs mpinfo iinfo cinfo with_names constructor_arg_names ih_names, trace_state_eliminate_hyp "Final state:", -- Return the constructor name and the renamable new hypotheses. These are -- the hypotheses that can later be renamed by the `case` tactic. Note -- that index variables and index equations are not renamable. This may be -- counterintuitive in some cases, but it's surprisingly difficult to -- catch exactly the relevant hyps here. pure $ some (cinfo.cname, constructor_arg_hyps ++ ih_hyps) }, set_cases_tags in_tag cases.reduce_option, pure () /-- A variant of `tactic.eliminate_hyp` which performs induction or case analysis on an arbitrary expression. `eliminate_hyp` requires that the major premise is a hypothesis. `eliminate_expr` lifts this restriction by generalising the goal over the major premise before calling `eliminate_hyp`. The generalisation replaces the major premise with a new hypothesis `x` everywhere in the goal. If `eq_name` is `some h`, an equation `h : major_premise = x` is added to remember the value of the major premise. -/ meta def eliminate_expr (generate_induction_hyps : bool) (major_premise : expr) (eq_name : option name := none) (gm := generalization_mode.generalize_all_except []) (with_names : list name := []) : tactic unit := do num_reverted ← revert_reverse_dependencies_of_hyp major_premise, hyp ← match eq_name with | some h := do x ← get_unused_name `x, interactive.generalize h () (to_pexpr major_premise, x), get_local x | none := do if major_premise.is_local_constant then pure major_premise else do x ← get_unused_name `x, generalize' major_premise x end, intron num_reverted, eliminate_hyp generate_induction_hyps hyp gm with_names end tactic namespace tactic.interactive open tactic tactic.eliminate interactive interactive.types lean.parser /-- Parse a `fixing` or `generalizing` clause for `induction'` or `cases'`. -/ meta def generalisation_mode_parser : lean.parser generalization_mode := (tk "fixing" *> ((tk "*" *> pure (generalization_mode.generalize_only [])) <|> generalization_mode.generalize_all_except <$> many ident)) <|> (tk "generalizing" *> generalization_mode.generalize_only <$> many ident) <|> pure (generalization_mode.generalize_all_except []) precedence `fixing`:0 /-- A variant of `tactic.interactive.induction`, with the following differences: - If the major premise (the hypothesis we are performing induction on) has complex indices, `induction'` 'remembers' them. A complex expression is any expression that is not merely a local hypothesis. A major premise `h : I p₁ ... pₙ j₁ ... jₘ`, where `I` is an inductive type with `n` parameters and `m` indices, has a complex index if any of the `jᵢ` are complex. In this situation, standard `induction` effectively forgets the exact values of the complex indices, which often leads to unprovable goals. `induction'` 'remembers' them by adding propositional equalities. As a result, you may find equalities named `induction_eq` in your goal, and the induction hypotheses may also quantify over additional equalities. - `induction'` generalises induction hypotheses as much as possible by default. This means that if you eliminate `n` in the goal ``` n m : ℕ ⊢ P n m ``` the induction hypothesis is `∀ m, P n m` instead of `P n m`. - `induction'` generates much more human-friendly names than `induction`. It also clears redundant hypotheses more aggressively. - `induction'` currently does not support custom induction principles a la `induction using`. Like `induction`, `induction'` supports some modifiers: `induction' e with n₁ ... nₘ` uses the names `nᵢ` for the new hypotheses. `induction' e fixing h₁ ... hₙ` fixes the hypotheses `hᵢ`, so the induction hypothesis is not generalised over these hypotheses. `induction' e fixing *` fixes all hypotheses. This disables the generalisation functionality, so this mode behaves like standard `induction`. `induction' e generalizing h₁ ... hₙ` generalises only the hypotheses `hᵢ`. This mode behaves like `induction e generalizing h₁ ... hₙ`. `induction' t`, where `t` is an arbitrary term (rather than a hypothesis), generalises the goal over `t`, then performs induction on the generalised goal. `induction' h : t = x` is similar, but also adds an equation `h : t = x` to remember the value of `t`. To debug this tactic, use ``` set_option trace.eliminate_hyp true ``` -/ meta def induction' (major_premise : parse cases_arg_p) (gm : parse generalisation_mode_parser) (with_names : parse (optional with_ident_list)) : tactic unit := do let ⟨eq_name, e⟩ := major_premise, e ← to_expr e, eliminate_expr tt e eq_name gm (with_names.get_or_else []) /-- A variant of `tactic.interactive.cases`, with minor changes: - `cases'` can perform case analysis on some (rare) goals that `cases` does not support. - `cases'` generates much more human-friendly names for the new hypotheses it introduces. This tactic supports the same modifiers as `cases`, e.g. ``` cases' H : e = x with n m o ``` This is almost exactly the same as `tactic.interactive.induction'`, only that no induction hypotheses are generated. To debug this tactic, use ``` set_option trace.eliminate_hyp true ``` -/ meta def cases' (major_premise : parse cases_arg_p) (with_names : parse (optional with_ident_list)) : tactic unit := do let ⟨eq_name, e⟩ := major_premise, e ← to_expr e, eliminate_expr ff e eq_name (generalization_mode.generalize_only []) (with_names.get_or_else []) end tactic.interactive
ca369d2950ec25ab40d180f05eb38d2aa6885b86
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/data/padics/padic_integers.lean
9a9abfe1fec59361c7d3f3c0fe792fc94a30f93f
[ "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
9,316
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro Define the p-adic integers ℤ_p as a subtype of ℚ_p. Construct algebraic structures on ℤ_p. -/ import data.padics.padic_numbers ring_theory.ideals data.int.modeq import tactic.linarith open nat padic metric noncomputable theory local attribute [instance] classical.prop_decidable def padic_int (p : ℕ) [p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int variables {p : ℕ} [nat.prime p] def add : ℤ_[p] → ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩ def mul : ℤ_[p] → ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩ def neg : ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ := ⟨-x, by simpa⟩ instance : ring ℤ_[p] := begin refine { add := add, mul := mul, neg := neg, zero := ⟨0, by simp [zero_le_one]⟩, one := ⟨1, by simp⟩, .. }; {repeat {rintro ⟨_, _⟩}, simp [mul_assoc, left_distrib, right_distrib, add, mul, neg]} end lemma zero_def : ∀ x : ℤ_[p], x = 0 ↔ x.val = 0 | ⟨x, _⟩ := ⟨subtype.mk.inj, λ h, by simp at h; simp only [h]; refl⟩ @[simp] lemma add_def : ∀ (x y : ℤ_[p]), (x+y).val = x.val + y.val | ⟨x, hx⟩ ⟨y, hy⟩ := rfl @[simp] lemma mul_def : ∀ (x y : ℤ_[p]), (x*y).val = x.val * y.val | ⟨x, hx⟩ ⟨y, hy⟩ := rfl @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = ↑z := rfl @[simp] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), (↑(z1 + z2) : ℚ_[p]) = ↑z1 + ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), (↑(z1 * z2) : ℚ_[p]) = ↑z1 * ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma coe_neg : ∀ (z1 : ℤ_[p]), (↑(-z1) : ℚ_[p]) = -↑z1 | ⟨_, _⟩ := rfl @[simp] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma coe_one : (↑(1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp] lemma coe_coe : ∀ n : ℕ, (↑(↑n : ℤ_[p]) : ℚ_[p]) = (↑n : ℚ_[p]) | 0 := rfl | (k+1) := by simp [coe_coe] @[simp] lemma coe_zero : (↑(0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl @[simp] lemma cast_pow (x : ℤ_[p]) : ∀ (n : ℕ), (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n | 0 := by simp | (k+1) := by simp [monoid.pow, pow]; congr; apply cast_pow lemma mk_coe : ∀ (k : ℤ_[p]), (⟨↑k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 end padic_int section instances variables {p : ℕ} [nat.prime p] @[reducible] def padic_norm_z (z : ℤ_[p]) : ℝ := ∥z.val∥ instance : metric_space ℤ_[p] := metric_space_subtype instance : has_norm ℤ_[p] := ⟨padic_norm_z⟩ instance : normed_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul _ _ } instance padic_norm_z.is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero, padic_int.zero_def], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_triangle _ _, abv_mul := λ _ _, by unfold norm; simp [padic_norm_z] } protected lemma padic_int.pmul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [mul_comm] instance : comm_ring ℤ_[p] := { mul_comm := padic_int.pmul_comm, ..padic_int.ring } protected lemma padic_int.zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext.1 zero_ne_one protected lemma padic_int.eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext.1 h, (mul_eq_zero_iff_eq_zero_or_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := padic_int.eq_zero_or_eq_zero_of_mul_eq_zero, zero_ne_one := padic_int.zero_ne_one, ..padic_int.comm_ring } end instances namespace padic_norm_z variables {p : ℕ} [nat.prime p] lemma le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma one : ∥(1 : ℤ_[p])∥ = 1 := by simp [norm, padic_norm_z] @[simp] lemma mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by unfold norm; simp [padic_norm_z] @[simp] lemma pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw mul, congr, apply pow} theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne @[simp] lemma norm_one : ∥(1 : ℤ_[p])∥ = 1 := norm_one lemma eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm, padic_norm_z] @[simp] lemma padic_norm_z_eq_padic_norm_e {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl end padic_norm_z private lemma mul_lt_one {α} [decidable_linear_ordered_comm_ring α] {a b : α} (hbz : 0 < b) (ha : a < 1) (hb : b < 1) : a * b < 1 := suffices a*b < 1*1, by simpa, mul_lt_mul ha (le_of_lt hb) hbz zero_le_one private lemma mul_lt_one_of_le_of_lt {α} [decidable_linear_ordered_comm_ring α] {a b : α} (ha : a ≤ 1) (hbz : 0 ≤ b) (hb : b < 1) : a * b < 1 := if hb' : b = 0 then by simpa [hb'] using zero_lt_one else if ha' : a = 1 then by simpa [ha'] else mul_lt_one (lt_of_le_of_ne hbz (ne.symm hb')) (lt_of_le_of_ne ha ha') hb namespace padic_int variables {p : ℕ} [nat.prime p] local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (padic_norm_z.le_one _) _, have := mul_le_mul_of_nonneg_left (padic_norm_z.le_one w) (norm_nonneg z), rwa [mul_one, ← padic_norm_z.mul, ← eq, padic_norm_z.one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (padic_norm_z.nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_le_of_lt (padic_norm_z.le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [padic_norm_z.le_one z, nonunits, is_unit_iff] instance : is_local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, padic_norm_z] using f.cauchy hε ⟩ instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, padic_norm_z.le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, padic_norm_z] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_norm_z variables {p : ℕ} [nat.prime p] lemma padic_val_of_cong_pow_p {z1 z2 : ℤ} {n : ℕ} (hz : z1 ≡ z2 [ZMOD ↑(p^n)]) : ∥(z1 - z2 : ℚ_[p])∥ ≤ ↑(↑p ^ (-n : ℤ) : ℚ) := have hdvd : ↑(p^n) ∣ z2 - z1, from int.modeq.modeq_iff_dvd.1 hz, have (↑(z2 - z1) : ℚ_[p]) = padic.of_rat p ↑(z2 - z1), by simp, begin rw [norm_sub_rev, ←int.cast_sub, this, padic_norm_e.eq_padic_norm], simpa using padic_norm.le_of_dvd p hdvd end end padic_norm_z