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
882dbc3ef5f4bf5d336cbfc78ae54ffba2b7ca2a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/nat/neg_elim.lean
fe4bd9edefa45c7fefeb8d35d2616ae476fbacd5
[]
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
1,819
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.nat.form import Mathlib.PostPort namespace Mathlib /- Negation elimination. -/ namespace omega namespace nat /-- push_neg p returns the result of normalizing ¬ p by pushing the outermost negation all the way down, until it reaches either a negation or an atom -/ @[simp] def push_neg : preform → preform := sorry theorem push_neg_equiv {p : preform} : preform.equiv (push_neg p) (preform.not p) := sorry /-- NNF transformation -/ def nnf : preform → preform := sorry /-- Asserts that the given preform is in NNF -/ def is_nnf : preform → Prop := sorry theorem is_nnf_push_neg (p : preform) : is_nnf p → is_nnf (push_neg p) := sorry theorem is_nnf_nnf (p : preform) : is_nnf (nnf p) := sorry theorem nnf_equiv {p : preform} : preform.equiv (nnf p) p := sorry @[simp] def neg_elim_core : preform → preform := sorry theorem neg_free_neg_elim_core (p : preform) : is_nnf p → preform.neg_free (neg_elim_core p) := sorry theorem le_and_le_iff_eq {α : Type} [partial_order α] {a : α} {b : α} : a ≤ b ∧ b ≤ a ↔ a = b := sorry theorem implies_neg_elim_core {p : preform} : preform.implies p (neg_elim_core p) := sorry /-- Eliminate all negations in a preform -/ def neg_elim : preform → preform := neg_elim_core ∘ nnf theorem neg_free_neg_elim {p : preform} : preform.neg_free (neg_elim p) := neg_free_neg_elim_core (nnf p) (is_nnf_nnf p) theorem implies_neg_elim {p : preform} : preform.implies p (neg_elim p) := id fun (v : ℕ → ℕ) (h1 : preform.holds v p) => implies_neg_elim_core v (iff.elim_right (nnf_equiv v) h1)
0ba9a072fef982abcbae531797f52350ec0d9833
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/polar_coord.lean
05cc1d283346ee238be474c7224af241c2524a9b
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
6,693
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.function.jacobian /-! # Polar coordinates We define polar coordinates, as a local homeomorphism in `ℝ^2` between `ℝ^2 - (-∞, 0]` and `(0, +∞) × (-π, π)`. Its inverse is given by `(r, θ) ↦ (r cos θ, r sin θ)`. It satisfies the following change of variables formula (see `integral_comp_polar_coord_symm`): `∫ p in polar_coord.target, p.1 • f (polar_coord.symm p) = ∫ p, f p` -/ noncomputable theory open real set measure_theory open_locale real topology /-- The polar coordinates local homeomorphism in `ℝ^2`, mapping `(r cos θ, r sin θ)` to `(r, θ)`. It is a homeomorphism between `ℝ^2 - (-∞, 0]` and `(0, +∞) × (-π, π)`. -/ @[simps] def polar_coord : local_homeomorph (ℝ × ℝ) (ℝ × ℝ) := { to_fun := λ q, (real.sqrt (q.1^2 + q.2^2), complex.arg (complex.equiv_real_prod.symm q)), inv_fun := λ p, (p.1 * cos p.2, p.1 * sin p.2), source := {q | 0 < q.1} ∪ {q | q.2 ≠ 0}, target := Ioi (0 : ℝ) ×ˢ Ioo (-π) π, map_target' := begin rintros ⟨r, θ⟩ ⟨hr, hθ⟩, dsimp at hr hθ, rcases eq_or_ne θ 0 with rfl|h'θ, { simpa using hr }, { right, simpa only [ne_of_gt hr, ne.def, mem_set_of_eq, mul_eq_zero, false_or, sin_eq_zero_iff_of_lt_of_lt hθ.1 hθ.2] using h'θ } end, map_source' := begin rintros ⟨x, y⟩ hxy, simp only [prod_mk_mem_set_prod_eq, mem_Ioi, sqrt_pos, mem_Ioo, complex.neg_pi_lt_arg, true_and, complex.arg_lt_pi_iff], split, { cases hxy, { dsimp at hxy, linarith [sq_pos_of_ne_zero _ (hxy.ne'), sq_nonneg y] }, { linarith [sq_nonneg x, sq_pos_of_ne_zero _ hxy] } }, { cases hxy, { exact or.inl (le_of_lt hxy) }, { exact or.inr hxy } } end, right_inv' := begin rintros ⟨r, θ⟩ ⟨hr, hθ⟩, dsimp at hr hθ, simp only [prod.mk.inj_iff], split, { conv_rhs { rw [← sqrt_sq (le_of_lt hr), ← one_mul (r^2), ← sin_sq_add_cos_sq θ], }, congr' 1, ring_exp }, { convert complex.arg_mul_cos_add_sin_mul_I hr ⟨hθ.1, hθ.2.le⟩, simp only [complex.equiv_real_prod_symm_apply, complex.of_real_mul, complex.of_real_cos, complex.of_real_sin], ring } end, left_inv' := begin rintros ⟨x, y⟩ hxy, have A : sqrt (x ^ 2 + y ^ 2) = complex.abs (x + y * complex.I), by simp only [complex.abs_def, complex.norm_sq, pow_two, monoid_with_zero_hom.coe_mk, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, mul_zero, complex.of_real_im, complex.I_im, sub_self, add_zero, complex.add_im, complex.mul_im, mul_one, zero_add], have Z := complex.abs_mul_cos_add_sin_mul_I (x + y * complex.I), simp only [← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc] at Z, simpa [A, -complex.of_real_cos, -complex.of_real_sin] using complex.ext_iff.1 Z, end, open_target := is_open_Ioi.prod is_open_Ioo, open_source := (is_open_lt continuous_const continuous_fst).union (is_open_ne_fun continuous_snd continuous_const), continuous_inv_fun := ((continuous_fst.mul (continuous_cos.comp continuous_snd)).prod_mk (continuous_fst.mul (continuous_sin.comp continuous_snd))).continuous_on, continuous_to_fun := begin apply ((continuous_fst.pow 2).add (continuous_snd.pow 2)).sqrt.continuous_on.prod, have A : maps_to complex.equiv_real_prod.symm ({q : ℝ × ℝ | 0 < q.1} ∪ {q : ℝ × ℝ | q.2 ≠ 0}) {z | 0 < z.re ∨ z.im ≠ 0}, { rintros ⟨x, y⟩ hxy, simpa only using hxy }, apply continuous_on.comp (λ z hz, _) _ A, { exact (complex.continuous_at_arg hz).continuous_within_at }, { exact complex.equiv_real_prod_clm.symm.continuous.continuous_on } end } lemma has_fderiv_at_polar_coord_symm (p : ℝ × ℝ) : has_fderiv_at polar_coord.symm (matrix.to_lin (basis.fin_two_prod ℝ) (basis.fin_two_prod ℝ) (!![cos p.2, -p.1 * sin p.2; sin p.2, p.1 * cos p.2])).to_continuous_linear_map p := begin rw matrix.to_lin_fin_two_prod_to_continuous_linear_map, convert has_fderiv_at.prod (has_fderiv_at_fst.mul ((has_deriv_at_cos p.2).comp_has_fderiv_at p has_fderiv_at_snd)) (has_fderiv_at_fst.mul ((has_deriv_at_sin p.2).comp_has_fderiv_at p has_fderiv_at_snd)) using 2; simp only [smul_smul, add_comm, neg_mul, neg_smul, smul_neg], end lemma polar_coord_source_ae_eq_univ : polar_coord.source =ᵐ[volume] univ := begin have A : polar_coord.sourceᶜ ⊆ (linear_map.snd ℝ ℝ ℝ).ker, { assume x hx, simp only [polar_coord_source, compl_union, mem_inter_iff, mem_compl_iff, mem_set_of_eq, not_lt, not_not] at hx, exact hx.2 }, have B : volume ((linear_map.snd ℝ ℝ ℝ).ker : set (ℝ × ℝ)) = 0, { apply measure.add_haar_submodule, rw [ne.def, linear_map.ker_eq_top], assume h, have : (linear_map.snd ℝ ℝ ℝ) (0, 1) = (0 : (ℝ × ℝ →ₗ[ℝ] ℝ)) (0, 1), by rw h, simpa using this }, simp only [ae_eq_univ], exact le_antisymm ((measure_mono A).trans (le_of_eq B)) bot_le, end theorem integral_comp_polar_coord_symm {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] (f : ℝ × ℝ → E) : ∫ p in polar_coord.target, p.1 • f (polar_coord.symm p) = ∫ p, f p := begin set B : (ℝ × ℝ) → ((ℝ × ℝ) →L[ℝ] (ℝ × ℝ)) := λ p, (matrix.to_lin (basis.fin_two_prod ℝ) (basis.fin_two_prod ℝ) !![cos p.2, -p.1 * sin p.2; sin p.2, p.1 * cos p.2]).to_continuous_linear_map with hB, have A : ∀ p ∈ polar_coord.symm.source, has_fderiv_at polar_coord.symm (B p) p := λ p hp, has_fderiv_at_polar_coord_symm p, have B_det : ∀ p, (B p).det = p.1, { assume p, conv_rhs {rw [← one_mul p.1, ← cos_sq_add_sin_sq p.2] }, simp only [neg_mul, linear_map.det_to_continuous_linear_map, linear_map.det_to_lin, matrix.det_fin_two_of, sub_neg_eq_add], ring_exp }, symmetry, calc ∫ p, f p = ∫ p in polar_coord.source, f p : begin rw ← integral_univ, apply set_integral_congr_set_ae, exact polar_coord_source_ae_eq_univ.symm end ... = ∫ p in polar_coord.target, abs ((B p).det) • f (polar_coord.symm p) : by apply integral_target_eq_integral_abs_det_fderiv_smul volume A ... = ∫ p in polar_coord.target, p.1 • f (polar_coord.symm p) : begin apply set_integral_congr (polar_coord.open_target.measurable_set) (λ x hx, _), rw [B_det, abs_of_pos], exact hx.1, end end
ddd976fb0a8670dc03cc0c0b137640240e17c66b
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/analysis/calculus/extend_deriv.lean
3f2d7b8136e322283df234ebcc983fa41a1f558c
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
11,224
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 analysis.calculus.mean_value import tactic.monotonicity /-! # Extending differentiability to the boundary We investigate how differentiable functions inside a set extend to differentiable functions on the boundary. For this, it suffices that the function and its derivative admit limits there. A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`. One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or the right endpoint of an interval, are given in `has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and `has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms of the one-dimensional derivative `deriv ℝ f`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open filter set metric continuous_linear_map open_locale topological_space local attribute [mono] prod_mono /-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its derivative converges to `0` at a point on the boundary, then `f` is differentiable there with derivative `0`. This is an auxiliary statement to prove the same result for any value of the derivative, in `has_fderiv_at_boundary_of_tendsto_fderiv`. -/ theorem has_fderiv_at_boundary_of_tendsto_fderiv_aux {f : E → F} {s : set E} {x : E} (f_diff : differentiable_on ℝ f s) (s_conv : convex s) (s_open : is_open s) (f_cont : ∀y ∈ closure s, continuous_within_at f s y) (h : tendsto (λy, fderiv ℝ f y) (nhds_within x s) (𝓝 0)) : has_fderiv_within_at f (0 : E →L[ℝ] F) (closure s) x := begin classical, -- one can assume without loss of generality that `x` belongs to the closure of `s`, as the -- statement is empty otherwise by_cases hx : x ∉ closure s, { rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx }, push_neg at hx, rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff], /- One needs to show that `∥f y - f x∥ ≤ ε ∥y - x∥` for `y` close to `x` in `closure s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is arbitrarily small by assumption. The mean value inequality ensures that `f` is `ε`-Lipschitz there, concluding the proof. -/ assume ε ε_pos, obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ∥fderiv ℝ f y∥ < ε, by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos, set B := ball x δ, suffices : ∀ y ∈ B ∩ (closure s), ∥f y - f x∥ ≤ ε * ∥y - x∥, from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩, suffices : ∀ p : E × E, p ∈ closure ((B ∩ s).prod (B ∩ s)) → ∥f p.2 - f p.1∥ ≤ ε * ∥p.2 - p.1∥, { rw closure_prod_eq at this, intros y y_in, apply this ⟨x, y⟩, have : B ∩ closure s ⊆ closure (B ∩ s), from closure_inter_open is_open_ball, exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ }, have key : ∀ p : E × E, p ∈ (B ∩ s).prod (B ∩ s) → ∥f p.2 - f p.1∥ ≤ ε * ∥p.2 - p.1∥, { rintros ⟨u, v⟩ ⟨u_in, v_in⟩, have conv : convex (B ∩ s) := (convex_ball _ _).inter s_conv, have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _), refine conv.norm_image_sub_le_of_norm_deriv_le diff (λz z_in, _) u_in v_in, convert le_of_lt (hδ _ z_in.2 z_in.1), have op : is_open (B ∩ s) := is_open_inter is_open_ball s_open, rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in), exact (diff z z_in).differentiable_at (mem_nhds_sets op z_in) }, rintros ⟨u, v⟩ uv_in, refine continuous_within_at.closure_le uv_in _ _ key, all_goals { -- common start for both continuity proofs have : (B ∩ s).prod (B ∩ s) ⊆ s.prod s, by mono ; exact inter_subset_right _ _, obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s, by simpa [closure_prod_eq] using closure_mono this uv_in, apply continuous_within_at.mono _ this, simp only [continuous_within_at, nhds_prod_eq] }, { rw nhds_within_prod_eq, exact tendsto.comp continuous_norm.continuous_at ((tendsto.comp (f_cont v v_in) tendsto_snd).sub $ tendsto.comp (f_cont u u_in) tendsto_fst) }, { apply tendsto_nhds_within_of_tendsto_nhds, rw nhds_prod_eq, exact tendsto_const_nhds.mul (tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) }, end /-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there with derivative `f'`. -/ theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F} (f_diff : differentiable_on ℝ f s) (s_conv : convex s) (s_open : is_open s) (f_cont : ∀y ∈ closure s, continuous_within_at f s y) (h : tendsto (λy, fderiv ℝ f y) (nhds_within x s) (𝓝 f')) : has_fderiv_within_at f f' (closure s) x := begin /- We subtract `f'` to define a new function `g` for which `g' = 0`, for which differentiability is proved `has_fderiv_at_boundary_of_differentiable_aux`. Then, we just need to glue together the pieces, expressing back `f` in terms of `g`. -/ let g := λy, f y - f' y, have diff_g : differentiable_on ℝ g s := f_diff.sub (f'.differentiable.comp differentiable_id).differentiable_on, have cont_g : ∀y ∈ closure s, continuous_within_at g s y := λy hy, tendsto.sub (f_cont y hy) (f'.continuous.comp continuous_id).continuous_within_at, have A : ∀y ∈ s, fderiv ℝ f y - f' = fderiv ℝ g y, { assume y hy, have : has_fderiv_at f (fderiv ℝ f y) y := (differentiable_within_at.differentiable_at (f_diff y hy) (mem_nhds_sets s_open hy)).has_fderiv_at, have : has_fderiv_at g (fderiv ℝ f y - f') y := this.sub (f'.has_fderiv_at.comp y (has_fderiv_at_id y)), exact this.fderiv.symm }, have B : tendsto (λy, fderiv ℝ f y - f') (nhds_within x s) (𝓝 (f' - f')) := h.sub tendsto_const_nhds, have : tendsto (λy, fderiv ℝ g y) (nhds_within x s) (𝓝 0), { have : f' - f' = 0, by simp, rw this at B, apply tendsto.congr' _ B, filter_upwards [self_mem_nhds_within] A }, have : has_fderiv_within_at g (0 : E →L[ℝ] F) (closure s) x := has_fderiv_at_boundary_of_tendsto_fderiv_aux diff_g s_conv s_open cont_g this, convert this.add f'.has_fderiv_within_at, { ext y, simp [g] }, { simp } end /-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/ lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ nhds_within a (Ioi a)) (f_lim' : tendsto (λx, deriv f x) (nhds_within a (Ioi a)) (𝓝 e)) : has_deriv_within_at f e (Ici a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ab, sab⟩ : ∃ b ∈ Ioi a, Ioc a b ⊆ s := mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs, let t := Ioo a b, have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex t := convex_Ioo a b, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc a b := closure_Ioo ab, have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (nhds_within a t) (𝓝 (smul_right 1 e)), { simp [deriv_fderiv.symm], refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _, exact tendsto_le_left (nhds_within_mono _ Ioo_subset_Ioi_self) f_lim' }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc a b) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (mem_nhds_within_Ici_iff_exists_Icc_subset.2 ⟨b, ab, subset.refl _⟩) end /-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/ lemma has_fderiv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ nhds_within a (Iio a)) (f_lim' : tendsto (λx, deriv f x) (nhds_within a (Iio a)) (𝓝 e)) : has_deriv_within_at f e (Iic a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s := mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs, let t := Ioo b a, have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex t := convex_Ioo b a, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc b a := closure_Ioo ba, have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (nhds_within a t) (𝓝 (smul_right 1 e)), { simp [deriv_fderiv.symm], refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _, exact tendsto_le_left (nhds_within_mono _ Ioo_subset_Iio_self) f_lim' }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc b a) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (mem_nhds_within_Iic_iff_exists_Icc_subset.2 ⟨b, ba, subset.refl _⟩) end
b356ac15b34219de3b9992401fc8a0ecd553ffdd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/modBug.lean
61b5357d2306b3cca672f0513e25cd37c872d338
[ "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
65
lean
theorem proofOfFalse : False := Nat.zero_ne_one (Nat.mod_zero 1)
6c3fa0e76803a5e61dcba3415477870c532174b7
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/finset/partition.lean
49de48afb7147fada38736815a70b1c7a0e00418
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,861
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Haitao Zhang Partitions of a type A into finite subsets of A. Such a partition is represented by a function f : A → finset A which maps every element a : A to its equivalence class. -/ import .card open function eq.ops variable {A : Type} variable [deceqA : decidable_eq A] include deceqA namespace finset definition is_partition (f : A → finset A) := ∀ a b, a ∈ f b = (f a = f b) structure partition : Type := (set : finset A) (part : A → finset A) (is_part : is_partition part) (complete : set = Union set part) attribute partition.part [coercion] namespace partition definition equiv_classes (f : partition) : finset (finset A) := image (partition.part f) (partition.set f) lemma equiv_class_disjoint (f : partition) (a1 a2 : finset A) (Pa1 : a1 ∈ equiv_classes f) (Pa2 : a2 ∈ equiv_classes f) : a1 ≠ a2 → a1 ∩ a2 = ∅ := assume Pne, assert Pe1 : _, from exists_of_mem_image Pa1, obtain g1 Pg1, from Pe1, assert Pe2 : _, from exists_of_mem_image Pa2, obtain g2 Pg2, from Pe2, begin apply inter_eq_empty_of_disjoint, apply disjoint.intro, rewrite [eq.symm (and.right Pg1), eq.symm (and.right Pg2)], intro x, rewrite [*partition.is_part f], intro Pxg1, rewrite [Pxg1, and.right Pg1, and.right Pg2], intro Pe, exact absurd Pe Pne end theorem class_equation (f : @partition A _) : card (partition.set f) = nat.finset.Sum (equiv_classes f) card := let s := (partition.set f), p := (partition.part f), img := image p s in calc card s = card (Union s p) : partition.complete f ... = card (Union img id) : image_eq_Union_index_image s p ... = card (Union (equiv_classes f) id) : rfl ... = nat.finset.Sum (equiv_classes f) card : card_Union_of_disjoint _ id (equiv_class_disjoint f) lemma equiv_class_refl {f : A → finset A} (Pequiv : is_partition f) : ∀ a, a ∈ f a := take a, by rewrite [Pequiv a a] -- make it a little easier to prove union from restriction lemma restriction_imp_union {s : finset A} (f : A → finset A) (Pequiv : is_partition f) (Psub : ∀{a}, a ∈ s → f a ⊆ s) : s = Union s f := ext (take a, iff.intro (assume Pains, begin rewrite [(Union_insert_of_mem f Pains)⁻¹, Union_insert], apply mem_union_l, exact equiv_class_refl Pequiv a end) (assume Painu, have Pclass : ∃ x, x ∈ s ∧ a ∈ f x, from iff.elim_left (mem_Union_iff s f _) Painu, obtain x Px, from Pclass, have Pfx : f x ⊆ s, from Psub (and.left Px), mem_of_subset_of_mem Pfx (and.right Px))) lemma binary_union (P : A → Prop) [decP : decidable_pred P] {S : finset A} : S = {a ∈ S | P a} ∪ {a ∈ S | ¬(P a)} := ext take a, iff.intro (suppose a ∈ S, decidable.by_cases (suppose P a, mem_union_l (mem_sep_of_mem `a ∈ S` this)) (suppose ¬ P a, mem_union_r (mem_sep_of_mem `a ∈ S` this))) (suppose a ∈ sep P S ∪ {a ∈ S | ¬ P a}, or.elim (mem_or_mem_of_mem_union this) (suppose a ∈ sep P S, mem_of_mem_sep this) (suppose a ∈ {a ∈ S | ¬ P a}, mem_of_mem_sep this)) lemma binary_inter_empty {P : A → Prop} [decP : decidable_pred P] {S : finset A} : {a ∈ S | P a} ∩ {a ∈ S | ¬(P a)} = ∅ := inter_eq_empty (take a, assume Pa nPa, absurd (of_mem_sep Pa) (of_mem_sep nPa)) definition disjoint_sets (S : finset (finset A)) : Prop := ∀ s₁ s₂ (P₁ : s₁ ∈ S) (P₂ : s₂ ∈ S), s₁ ≠ s₂ → s₁ ∩ s₂ = ∅ lemma disjoint_sets_sep_of_disjoint_sets {P : finset A → Prop} [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → disjoint_sets {s ∈ S | P s} := assume Pds, take s₁ s₂, assume P₁ P₂, Pds s₁ s₂ (mem_of_mem_sep P₁) (mem_of_mem_sep P₂) lemma binary_inter_empty_Union_disjoint_sets {P : finset A → Prop} [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → Union {s ∈ S | P s} id ∩ Union {s ∈ S | ¬P s} id = ∅ := assume Pds, inter_eq_empty (take a, assume Pa nPa, obtain s Psin Pains, from iff.elim_left !mem_Union_iff Pa, obtain t Ptin Paint, from iff.elim_left !mem_Union_iff nPa, assert s ≠ t, from assume Peq, absurd (Peq ▸ of_mem_sep Psin) (of_mem_sep Ptin), Pds s t (mem_of_mem_sep Psin) (mem_of_mem_sep Ptin) `s ≠ t` ▸ mem_inter Pains Paint) section variables {B: Type} [deceqB : decidable_eq B] include deceqB lemma binary_Union (f : A → finset B) {P : A → Prop} [decP : decidable_pred P] {s : finset A} : Union s f = Union {a ∈ s | P a} f ∪ Union {a ∈ s | ¬P a} f := begin rewrite [binary_union P at {1}], apply Union_union, exact binary_inter_empty end end open nat nat.finset section open algebra algebra.finset variables {B : Type} [acmB : add_comm_monoid B] include acmB lemma Sum_binary_union (f : A → B) (P : A → Prop) [decP : decidable_pred P] {S : finset A} : Sum S f = Sum {s ∈ S | P s} f + Sum {s ∈ S | ¬P s} f := calc Sum S f = Sum ({s ∈ S | P s} ∪ {s ∈ S | ¬(P s)}) f : binary_union ... = Sum {s ∈ S | P s} f + Sum {s ∈ S | ¬P s} f : Sum_union f binary_inter_empty end lemma card_binary_Union_disjoint_sets (P : finset A → Prop) [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → card (Union S id) = Sum {s ∈ S | P s} card + Sum {s ∈ S | ¬P s} card := assume Pds, calc card (Union S id) = card (Union {s ∈ S | P s} id ∪ Union {s ∈ S | ¬P s} id) : binary_Union ... = card (Union {s ∈ S | P s} id) + card (Union {s ∈ S | ¬P s} id) : card_union_of_disjoint (binary_inter_empty_Union_disjoint_sets Pds) ... = Sum {s ∈ S | P s} card + Sum {s ∈ S | ¬P s} card : by rewrite [*(card_Union_of_disjoint _ id (disjoint_sets_sep_of_disjoint_sets Pds))] end partition end finset
a11533325510b71501bb8b2bf1822f454b3a1094
883eaea6bef0d3c38f46c45d3454e0af631a6e61
/src/inClassNotes/final/imp.lean
5a1b3c2897f794c1186ef4045a3a41125bfab143
[]
no_license
hannahbrooke720/complogic-s21
bd3c4981cfeb8642654d83ce874a5c50a3077948
3f4098b174c54e1699a07222662ffec7e14223f2
refs/heads/master
1,681,504,336,289
1,620,140,677,000
1,620,140,677,000
335,838,993
0
0
null
1,620,140,678,000
1,612,413,391,000
Lean
UTF-8
Lean
false
false
1,920
lean
import .arith_expr import .bool_expr /- Syntax of our little language (OLL). OLL supports mutable variables and values of types arithmetic (bool) and arithmetic (nat). It has an assignment command for each of these two types. It also supports sequential composition of smaller programs into larger ones. -/ inductive cmd : Type | skip | a_assn (v : var nat) (e : arith_expr) | b_assn (v : var bool) (e : bool_expr) | seq (c1 c2 : cmd) : cmd | ifelse (b : bool_expr) (c1 c2 : cmd) -- | cond (b : bool_expr) (c1 c2 : cmd) : cmd -- | while (b : bool_expr) (c : cmd) : cmd open cmd notation v = e := b_assn v e notation v = a := a_assn v a notation c1 ; c2 := seq c1 c2 notation `cond ` b ` then ` c1 ` else ` c2 := ifelse b c1 c2 def c_eval : cmd → env → env | skip st := st | (b_assn v e) st := override_bool st v e | (a_assn v e) st := override_nat st v e | (c1 ; c2) st := c_eval c2 (c_eval c1 st) -- new | (cond b then c1 else c2) st := if (bool_eval b st) then c_eval c1 st else c_eval c2 st inductive c_sem : cmd → env → env → Prop | c_sem_skip : ∀ (st : env), c_sem skip st st | c_sem_arith_assn : ∀ (pre post : env) (v : var nat) (e : arith_expr), (override_nat pre v e = post) → c_sem (a_assn v e) pre post | c_sem_bool_assn : ∀ (pre post : env) (v : var bool) (e : bool_expr), (override_bool pre v e = post) → c_sem (b_assn v e) pre post | c_sem_seq : ∀ (pre is post : env) (c1 c2 : cmd), c_sem c1 pre is → c_sem c2 is post → c_sem (c1 ; c2) pre post -- New | c_sem_if_false : ∀ (pre is post : env) (b : bool_expr) (c1 c2 : cmd), bool_eval b pre = ff → c_sem c2 pre post → c_sem (ifelse b c1 c2) pre post | c_sem_if_true : ∀ (pre is post : env) (b : bool_expr) (c1 c2 : cmd), bool_eval b pre = ff → c_sem c1 pre post → c_sem (ifelse b c1 c2) pre post
05f4fde06c5642cfe8c0a76ce4949249d815a79b
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/set_theory/schroeder_bernstein.lean
27b4b3576cd14dab42cbfac11b887afb9b5d2a22
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
5,085
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 The Schröder-Bernstein theorem, and well ordering of cardinals. -/ import order.fixed_points data.set.lattice logic.function logic.embedding order.zorn open lattice set classical local attribute [instance] prop_decidable universes u v namespace function namespace embedding section antisymm variables {α : Type u} {β : Type v} theorem schroeder_bernstein {f : α → β} {g : β → α} (hf : injective f) (hg : injective g) : ∃h:α→β, bijective h := let s : set α := lfp $ λs, - (g '' - (f '' s)) in have hs : s = - (g '' - (f '' s)), from lfp_eq $ assume s t h, compl_subset_compl.mpr $ image_subset _ $ compl_subset_compl.mpr $ image_subset _ h, have hns : - s = g '' - (f '' s), from lattice.neg_eq_neg_of_eq $ by simp [hs.symm], let g' := λa, @inv_fun β ⟨f a⟩ α g a in have g'g : g' ∘ g = id, from funext $ assume b, @left_inverse_inv_fun _ ⟨f (g b)⟩ _ _ hg b, have hg'ns : g' '' (-s) = - (f '' s), by rw [hns, ←image_comp, g'g, image_id], let h := λa, if a ∈ s then f a else g' a in have h '' univ = univ, from calc h '' univ = h '' s ∪ h '' (- s) : by rw [←image_union, union_compl_self] ... = f '' s ∪ g' '' (-s) : congr (congr_arg (∪) (image_congr $ by simp [h, if_pos] {contextual := tt})) (image_congr $ by simp [h, if_neg] {contextual := tt}) ... = univ : by rw [hg'ns, union_compl_self], have surjective h, from assume b, have b ∈ h '' univ, by rw [this]; trivial, let ⟨a, _, eq⟩ := this in ⟨a, eq⟩, have split : ∀x∈s, ∀y∉s, h x = h y → false, from assume x hx y hy eq, have y ∈ g '' - (f '' s), by rwa [←hns], let ⟨y', hy', eq_y'⟩ := this in have f x = y', from calc f x = g' y : by simp [h, hx, hy, if_pos, if_neg] at eq; assumption ... = (g' ∘ g) y' : by simp [(∘), eq_y'] ... = _ : by simp [g'g], have y' ∈ f '' s, from this ▸ mem_image_of_mem _ hx, hy' this, have injective h, from assume x y eq, by_cases (assume hx : x ∈ s, by_cases (assume hy : y ∈ s, by simp [h, hx, hy, if_pos, if_neg] at eq; exact hf eq) (assume hy : y ∉ s, (split x hx y hy eq).elim)) (assume hx : x ∉ s, by_cases (assume hy : y ∈ s, (split y hy x hx eq.symm).elim) (assume hy : y ∉ s, have x ∈ g '' - (f '' s), by rwa [←hns], let ⟨x', hx', eqx⟩ := this in have y ∈ g '' - (f '' s), by rwa [←hns], let ⟨y', hy', eqy⟩ := this in have g' x = g' y, by simp [h, hx, hy, if_pos, if_neg] at eq; assumption, have (g' ∘ g) x' = (g' ∘ g) y', by simp [(∘), eqx, eqy, this], have x' = y', by rwa [g'g] at this, calc x = g x' : eqx.symm ... = g y' : by rw [this] ... = y : eqy)), ⟨h, ‹injective h›, ‹surjective h›⟩ theorem antisymm : (α ↪ β) → (β ↪ α) → nonempty (α ≃ β) | ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ := let ⟨f, hf⟩ := schroeder_bernstein h₁ h₂ in ⟨equiv.of_bijective hf⟩ end antisymm section wo parameters {ι : Type u} {β : ι → Type v} @[reducible] private def sets := {s : set (∀ i, β i) | ∀ (x ∈ s) (y ∈ s) i, (x : ∀ i, β i) i = y i → x = y} theorem injective_min (I : nonempty ι) : ∃ i, nonempty (∀ j, β i ↪ β j) := let ⟨s, hs, ms⟩ := show ∃s∈sets, ∀a∈sets, s ⊆ a → a = s, from zorn.zorn_subset sets (λ c hc hcc, ⟨⋃₀ c, λ x ⟨p, hpc, hxp⟩ y ⟨q, hqc, hyq⟩ i hi, (hcc.total hpc hqc).elim (λ h, hc hqc x (h hxp) y hyq i hi) (λ h, hc hpc x hxp y (h hyq) i hi), λ _, subset_sUnion_of_mem⟩) in let ⟨i, e⟩ := show ∃ i, ∀ y, ∃ x ∈ s, (x : ∀ i, β i) i = y, from classical.by_contradiction $ λ h, have h : ∀ i, ∃ y, ∀ x ∈ s, (x : ∀ i, β i) i ≠ y, by simpa only [not_exists, classical.not_forall] using h, let ⟨f, hf⟩ := axiom_of_choice h in have f ∈ s, from have insert f s ∈ sets := λ x hx y hy, begin cases hx; cases hy, {simp [hx, hy]}, { subst x, exact λ i e, (hf i y hy e.symm).elim }, { subst y, exact λ i e, (hf i x hx e).elim }, { exact hs x hx y hy } end, ms _ this (subset_insert f s) ▸ mem_insert _ _, let ⟨i⟩ := I in hf i f this rfl in let ⟨f, hf⟩ := axiom_of_choice e in ⟨i, ⟨λ j, ⟨λ a, f a j, λ a b e', let ⟨sa, ea⟩ := hf a, ⟨sb, eb⟩ := hf b in by rw [← ea, ← eb, hs _ sa _ sb _ e']⟩⟩⟩ end wo theorem total {α : Type u} {β : Type v} : nonempty (α ↪ β) ∨ nonempty (β ↪ α) := match @injective_min bool (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) ⟨tt⟩ with | ⟨tt, ⟨h⟩⟩ := let ⟨f, hf⟩ := h ff in or.inl ⟨embedding.congr equiv.ulift equiv.ulift ⟨f, hf⟩⟩ | ⟨ff, ⟨h⟩⟩ := let ⟨f, hf⟩ := h tt in or.inr ⟨embedding.congr equiv.ulift equiv.ulift ⟨f, hf⟩⟩ end end embedding end function
77ea33fb1d8ac74a3cef6cd2dc51f0da5ef53e40
0e175f34f8dca5ea099671777e8d7446d7d74227
/library/init/logic.lean
556e9fd3404b5740a0e8420df00a5a48165d3c71
[ "Apache-2.0" ]
permissive
utensil-contrib/lean
b31266738071c654d96dac8b35d9ccffc8172fda
a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8
refs/heads/master
1,670,045,564,075
1,597,397,599,000
1,597,397,599,000
287,528,503
0
0
Apache-2.0
1,597,408,338,000
1,597,408,337,000
null
UTF-8
Lean
false
false
38,243
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.core universes u v w @[simp] lemma opt_param_eq (α : Sort u) (default : α) : opt_param α default = α := rfl @[inline] def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) def trivial : true := ⟨⟩ /-- We can't have `a` and `¬a`, that would be absurd!-/ @[inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h /-- Modus tollens.-/ lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, h₂ (h₁ ha) /- not -/ lemma not_false : ¬false := id def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ @[inline] def false.elim {C : Sort u} (h : false) : C := false.rec C h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Sort u} (a : α) : id a = a := rfl @[inline] def eq.mp {α β : Sort u} : (α = β) → α → β := eq.rec_on @[inline] def eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ @[elab_as_eliminator] lemma eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Sort u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Sort u} (a b : α) := ¬(a = b) notation a ≠ b := ne a b @[simp] lemma ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Sort u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁.symm) end ne lemma false_of_ne {α : Sort u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} lemma heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Sort u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a _ rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α _ _ rfl rfl a := rfl lemma cast_heq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a == a | α _ rfl a := heq.refl a /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ def and.symm := @and.swap /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em def not_not_em := non_contradictory_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl def or.symm := @or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) notation a <-> b := iff a b notation a ↔ b := iff a b lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := iff.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := iff.mp lemma iff.elim_right : (a ↔ b) → b → a := iff.mpr lemma iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff.intro (λ h, and.intro h.mp h.mpr) (λ h, iff.intro h.left h.right) @[refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a @[trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) @[symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd def not_not_not_iff := not_non_contradictory_iff_absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (assume hab ha, iff.elim_left (h ha) (hab ha)) (assume hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) def not_true_iff := not_true @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) @[simp] lemma ne_self_iff_false {α : Sort u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Sort u} (a : α) : (a = a) ↔ true := iff_true_intro rfl @[simp] lemma heq_self_iff_true {α : Sort u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) @[simp] lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) @[simp] lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim lemma eq_comm {α : Sort u} {a b : α} : a = b ↔ b = a := ⟨eq.symm, eq.symm⟩ /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ def and_implies := @and.imp @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp (ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec ha id) or.inr theorem or_iff_left_of_imp (hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec id hb) or.inl @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ def or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id def or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id def or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) def or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro iff.mp iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := (iff_iff_implies_and_implies a b).trans ((and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)).trans (iff_iff_implies_and_implies c d).symm) /- implies simp rule -/ @[simp] lemma implies_true_iff (α : Sort u) : (α → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) @[simp] lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) @[simp] theorem true_implies_iff (α : Prop) : (true → α) ↔ α := iff.intro (λ h, h trivial) (λ h h', h) /- exists -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists attribute [intro] Exists.intro @[pattern] def exists.intro := @Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r lemma exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r @[intro] lemma exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (assume y, assume : p y, hunique y x this px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (assume x, assume : p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Sort u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Sort u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) @[simp] lemma to_bool_true_eq_tt (h : decidable true) : @to_bool true h = tt := decidable.cases_on h (λ h, false.elim (iff.mp not_true h)) (λ _, rfl) @[simp] lemma to_bool_false_eq_ff (h : decidable false) : @to_bool false h = ff := decidable.cases_on h (λ h, rfl) (λ h, false.elim h) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite (c : Prop) [h : decidable c] {α : Sort u} : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite (c : Prop) [h : decidable c] {α : Sort u} (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Sort u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ /-- Law of Excluded Middle. -/ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) lemma of_not_not [decidable p] : ¬ ¬ p → p := λ hnn, by_contradiction (λ hn, absurd hn hnn) lemma not_not_iff (p) [decidable p] : (¬ ¬ p) ↔ p := iff.intro of_not_not not_not_intro lemma not_and_iff_or_not (p q : Prop) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := match d₂ with | is_true h₂ := absurd (and.intro h₁ h₂) h | is_false h₂ := or.inr h₂ end | is_false h₁ := or.inl h₁ end) (λ h ⟨hp, hq⟩, or.elim h (λ h, h hp) (λ h, h hq)) lemma not_or_iff_and_not (p q) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := false.elim $ h (or.inl h₁) | is_false h₁ := match d₂ with | is_true h₂ := false.elim $ h (or.inr h₂) | is_false h₂ := ⟨h₁, h₂⟩ end end) (λ ⟨np, nq⟩ h, or.elim h np nq) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := if hp : p then if hq : q then is_true ⟨λ_, hq, λ_, hp⟩ else is_false $ λh, hq (h.1 hp) else if hq : q then is_false $ λh, hp (h.2 hq) else is_true $ ⟨λh, absurd h hp, λh, absurd h hq⟩ instance [decidable p] [decidable q] : decidable (xor p q) := if hp : p then if hq : q then is_false (or.rec (λ ⟨_, h⟩, h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩, h hp : ¬(q ∧ ¬ p))) else is_true $ or.inl ⟨hp, hq⟩ else if hq : q then is_true $ or.inr ⟨hq, hp⟩ else is_false (or.rec (λ ⟨h, _⟩, hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩, hq h : ¬(q ∧ ¬ p))) instance exists_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∃ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2, ⟨h, h2⟩, λ⟨h', h2⟩, h2⟩ else is_false (mt (λ⟨h, _⟩, h) h) instance forall_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∀ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2 _, h2, λal, al h⟩ else is_true (λ h2, absurd h2 h) end instance {α : Sort u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Sort u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := assume x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Sort u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Sort u) := (default [] : α) export inhabited (default) @[inline, irreducible] def arbitrary (α : Sort u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance pi.inhabited (α : Sort u) {β : α → Sort v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited true := ⟨trivial⟩ class inductive nonempty (α : Sort u) : Prop | intro (val : α) : nonempty protected def nonempty.elim {α : Sort u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ instance nonempty_of_inhabited {α : Sort u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Sort u) : Prop | intro (h : ∀ a b : α, a = b) : subsingleton protected def subsingleton.elim {α : Sort u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected def subsingleton.helim {α β : Sort u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] lemma if_true {α : Sort u} {h : decidable true} (t e : α) : (@ite true h α t e) = t := if_pos trivial @[simp] lemma if_false {α : Sort u} {h : decidable false} (t e : α) : (@ite false h α t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) @[simp] lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end @[simp] lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[congr] lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c dec_c α u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dif_eq_if (c : Prop) [h : decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end instance {c t e : Prop} [d_c : decidable c] [d_t : decidable t] [d_e : decidable e] : decidable (if c then t else e) := match d_c with | (is_true hc) := d_t | (is_false hc) := d_e end instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : decidable c] [d_t : ∀ h, decidable (t h)] [d_e : ∀ h, decidable (e h)] : decidable (if h : c then t h else e h) := match d_c with | (is_true hc) := d_t hc | (is_false hc) := d_e hc end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true def of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /-- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and plift α -/ lemma up_down {α : Sort u} : ∀ (b : plift α), up (down b) = b | (up a) := rfl lemma down_up {α : Sort u} (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x def mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, assume a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, assume a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
05509e1e78ef09c4a9751c7a2139b6138489360e
9028d228ac200bbefe3a711342514dd4e4458bff
/src/ring_theory/witt_vector/structure_polynomial.lean
0687358c5ac85d4841524694d464a67e10b1a636
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,080
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.matrix.notation import field_theory.mv_polynomial import field_theory.finite.polynomial import number_theory.basic import ring_theory.witt_vector.witt_polynomial /-! # Witt structure polynomials In this file we prove the main theorem that makes the whole theory of Witt vectors work. Briefly, consider a polynomial `Φ : mv_polynomial idx ℤ` over the integers, with polynomials variables indexed by an arbitrary type `idx`. Then there exists a unique family of polynomials `φ : ℕ → mv_polynomial (idx × ℕ) Φ` such that for all `n : ℕ` we have (`witt_structure_int_exists_unique`) ``` bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℤ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. N.b.: As far as we know, these polynomials do not have a name in the literature, so we have decided to call them the “Witt structure polynomials”. See `witt_structure_int`. ## Special cases With the main result of this file in place, we apply it to certain special polynomials. For example, by taking `Φ = X tt + X ff` resp. `Φ = X tt * X ff` we obtain families of polynomials `witt_add` resp. `witt_mul` (with type `ℕ → mv_polynomial (bool × ℕ) ℤ`) that will be used in later files to define the addition and multiplication on the ring of Witt vectors. ## Outline of the proof The proof of `witt_structure_int_exists_unique` is rather technical, and takes up most of this file. We start by proving the analogous version for polynomials with rational coefficients, instead of integer coefficients. In this case, the solution is rather easy, since the Witt polynomials form a faithful change of coordinates in the polynomial ring `mv_polynomial ℕ ℚ`. We therefore obtain a family of polynomials `witt_structure_rat Φ` for every `Φ : mv_polynomial idx ℚ`. If `Φ` has integer coefficients, then the polynomials `witt_structure_rat Φ n` do so as well. Proving this claim is the essential core of this file, and culminates in `map_witt_structure_int`, which proves that upon mapping the coefficients of `witt_structure_int Φ n` from the integers to the rationals, one obtains `witt_structure_rat Φ n`. Ultimately, the proof of `map_witt_structure_int` relies on ``` dvd_sub_pow_of_dvd_sub {R : Type*} [comm_ring R] {p : ℕ} {a b : R} : (p : R) ∣ a - b → ∀ (k : ℕ), (p : R) ^ (k + 1) ∣ a ^ p ^ k - b ^ p ^ k ``` ## Main results * `witt_structure_rat Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` associated with `Φ : mv_polynomial idx ℚ` and satisfying the property explained above. * `witt_structure_rat_prop`: the proof that `witt_structure_rat` indeed satisfies the property. * `witt_structure_int Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℤ` associated with `Φ : mv_polynomial idx ℤ` and satisfying the property explained above. * `map_witt_structure_int`: the proof that the integral polynomials `with_structure_int Φ` are equal to `witt_structure_rat Φ` when mapped to polynomials with rational coefficients. * `witt_structure_int_prop`: the proof that `witt_structure_int` indeed satisfies the property. -/ open mv_polynomial open set open finset (range) open finsupp (single) -- This lemma reduces a bundled morphism to a "mere" function, -- and consequently the simplifier cannot use a lot of powerful simp-lemmas. -- We disable this locally, and probably it should be disabled globally in mathlib. local attribute [-simp] coe_eval₂_hom variables {p : ℕ} {R : Type*} {idx : Type*} [comm_ring R] open_locale witt open_locale big_operators section p_prime variables (p) [hp : fact p.prime] include hp /-- `witt_structure_rat Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that `bind₁ (witt_structure_rat p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ`. In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_rat Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_rat_prop` for this property, and `witt_structure_rat_exists_unique` for the fact that `witt_structure_rat` gives the unique family of polynomials with this property. These polynomials turn out to have integral coefficients, but it requires some effort to show this. See `witt_structure_int` for the version with integral coefficients, and `map_witt_structure_int` for the fact that it is equal to `witt_structure_rat` when mapped to polynomials over the rationals. -/ noncomputable def witt_structure_rat (Φ : mv_polynomial idx ℚ) (n : ℕ) : mv_polynomial (idx × ℕ) ℚ := bind₁ (λ k, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ) (X_in_terms_of_W p ℚ n) theorem witt_structure_rat_prop (Φ : mv_polynomial idx ℚ) (n : ℕ) : bind₁ (witt_structure_rat p Φ) (W_ ℚ n) = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ := calc bind₁ (witt_structure_rat p Φ) (W_ ℚ n) = bind₁ (λ k, bind₁ (λ i, (rename (prod.mk i)) (W_ ℚ k)) Φ) (bind₁ (X_in_terms_of_W p ℚ) (W_ ℚ n)) : by { rw bind₁_bind₁, apply eval₂_hom_congr (ring_hom.ext_rat _ _) rfl rfl } ... = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ : by rw [bind₁_X_in_terms_of_W_witt_polynomial p _ n, bind₁_X_right] theorem witt_structure_rat_exists_unique (Φ : mv_polynomial idx ℚ) : ∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℚ), ∀ (n : ℕ), bind₁ φ (W_ ℚ n) = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ := begin refine ⟨witt_structure_rat p Φ, _, _⟩, { intro n, apply witt_structure_rat_prop }, { intros φ H, funext n, rw show φ n = bind₁ φ (bind₁ (W_ ℚ) (X_in_terms_of_W p ℚ n)), { rw [bind₁_witt_polynomial_X_in_terms_of_W p, bind₁_X_right] }, rw [bind₁_bind₁], exact eval₂_hom_congr (ring_hom.ext_rat _ _) (funext H) rfl }, end lemma witt_structure_rat_rec_aux (Φ : mv_polynomial idx ℚ) (n : ℕ) : witt_structure_rat p Φ n * C (p ^ n : ℚ) = bind₁ (λ b, rename (λ i, (b, i)) (W_ ℚ n)) Φ - ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i) := begin have := X_in_terms_of_W_aux p ℚ n, replace := congr_arg (bind₁ (λ k : ℕ, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ)) this, rw [alg_hom.map_mul, bind₁_C_right] at this, convert this, clear this, conv_rhs { simp only [alg_hom.map_sub, bind₁_X_right] }, rw sub_right_inj, simp only [alg_hom.map_sum, alg_hom.map_mul, bind₁_C_right, alg_hom.map_pow], refl end /-- Write `witt_structure_rat p φ n` in terms of `witt_structure_rat p φ i` for `i < n`. -/ lemma witt_structure_rat_rec (Φ : mv_polynomial idx ℚ) (n : ℕ) : (witt_structure_rat p Φ n) = C (1 / p ^ n : ℚ) * (bind₁ (λ b, (rename (λ i, (b, i)) (W_ ℚ n))) Φ - ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i)) := begin calc witt_structure_rat p Φ n = C (1 / p ^ n : ℚ) * (witt_structure_rat p Φ n * C (p ^ n : ℚ)) : _ ... = _ : by rw witt_structure_rat_rec_aux, rw [mul_left_comm, ← C_mul, div_mul_cancel, C_1, mul_one], exact pow_ne_zero _ (nat.cast_ne_zero.2 $ ne_of_gt (nat.prime.pos ‹_›)), end /-- `witt_structure_int Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that `bind₁ (witt_structure_int p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ`. In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_int Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_int_prop` for this property, and `witt_structure_int_exists_unique` for the fact that `witt_structure_int` gives the unique family of polynomials with this property. -/ noncomputable def witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) : mv_polynomial (idx × ℕ) ℤ := finsupp.map_range rat.num (rat.coe_int_num 0) (witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n) variable {p} lemma bind₁_rename_expand_witt_polynomial (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ m : ℕ, m < (n + 1) → map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) : bind₁ (λ b, rename (λ i, (b, i)) (expand p (W_ ℤ n))) Φ = bind₁ (λ i, expand p (witt_structure_int p Φ i)) (W_ ℤ n) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_bind₁, map_rename, map_expand, rename_expand, map_witt_polynomial], have key := (witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n).symm, apply_fun expand p at key, simp only [expand_bind₁] at key, rw key, clear key, apply eval₂_hom_congr' rfl _ rfl, rintro i hi -, rw [witt_polynomial_vars, finset.mem_range] at hi, simp only [IH i hi], end lemma C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ m : ℕ, m < n → map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) : C ↑(p ^ n) ∣ (bind₁ (λ (b : idx), rename (λ i, (b, i)) (witt_polynomial p ℤ n)) Φ - ∑ i in range n, C (↑p ^ i) * witt_structure_int p Φ i ^ p ^ (n - i)) := begin cases n, { simp only [is_unit_one, int.coe_nat_zero, int.coe_nat_succ, zero_add, pow_zero, C_1, is_unit.dvd] }, -- prepare a useful equation for rewriting have key := bind₁_rename_expand_witt_polynomial Φ n IH, apply_fun (map (int.cast_ring_hom (zmod (p ^ (n + 1))))) at key, conv_lhs at key { simp only [map_bind₁, map_rename, map_expand, map_witt_polynomial] }, -- clean up and massage rw [nat.succ_eq_add_one, C_dvd_iff_zmod, ring_hom.map_sub, sub_eq_zero, map_bind₁], simp only [map_rename, map_witt_polynomial, witt_polynomial_zmod_self], rw key, clear key IH, rw [bind₁, aeval_witt_polynomial, ring_hom.map_sum, ring_hom.map_sum, finset.sum_congr rfl], intros k hk, rw finset.mem_range at hk, simp only [← sub_eq_zero, ← ring_hom.map_sub, ← C_dvd_iff_zmod, C_eq_coe_nat, ← mul_sub, ← int.nat_cast_eq_coe_nat, ← nat.cast_pow], rw show p ^ (n + 1) = p ^ k * p ^ (n - k + 1), { rw ← pow_add, congr' 1, omega }, rw [nat.cast_mul, nat.cast_pow, nat.cast_pow], apply mul_dvd_mul_left, rw show p ^ (n + 1 - k) = p * p ^ (n - k), { rw ← pow_succ, congr' 1, omega }, rw [pow_mul], -- the machine! apply dvd_sub_pow_of_dvd_sub, rw [← C_eq_coe_nat, int.nat_cast_eq_coe_nat, C_dvd_iff_zmod, ring_hom.map_sub, sub_eq_zero, map_expand, ring_hom.map_pow, mv_polynomial.expand_zmod], end variables (p) @[simp] lemma map_witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) : map (int.cast_ring_hom ℚ) (witt_structure_int p Φ n) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n := begin apply nat.strong_induction_on n, clear n, intros n IH, rw [witt_structure_int, map_map_range_eq_iff, int.coe_cast_ring_hom], intro c, rw [witt_structure_rat_rec, coeff_C_mul, mul_comm, mul_div_assoc', mul_one], have sum_induction_steps : map (int.cast_ring_hom ℚ) (∑ i in range n, C (p ^ i : ℤ) * (witt_structure_int p Φ i) ^ p ^ (n - i)) = ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) i) ^ p ^ (n - i), { rw [ring_hom.map_sum], apply finset.sum_congr rfl, intros i hi, rw finset.mem_range at hi, simp only [IH i hi, ring_hom.map_mul, ring_hom.map_pow, map_C], refl }, simp only [← sum_induction_steps, ← map_witt_polynomial p (int.cast_ring_hom ℚ), ← map_rename, ← map_bind₁, ← ring_hom.map_sub, coeff_map], rw show (p : ℚ)^n = ((p^n : ℕ) : ℤ), by norm_cast, rw [← rat.denom_eq_one_iff, ring_hom.eq_int_cast, rat.denom_div_cast_eq_one_iff], swap, { exact_mod_cast pow_ne_zero n hp.ne_zero }, revert c, rw [← C_dvd_iff_dvd_coeff], exact C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum Φ n IH, end variables (p) theorem witt_structure_int_prop (Φ : mv_polynomial idx ℤ) (n) : bind₁ (witt_structure_int p Φ) (witt_polynomial p ℤ n) = bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, have := witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n, simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename, map_witt_polynomial, alg_hom.coe_to_ring_hom, map_witt_structure_int], end lemma eq_witt_structure_int (Φ : mv_polynomial idx ℤ) (φ : ℕ → mv_polynomial (idx × ℕ) ℤ) (h : ∀ n, bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ) : φ = witt_structure_int p Φ := begin funext k, apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, rw map_witt_structure_int, refine congr_fun _ k, apply unique_of_exists_unique (witt_structure_rat_exists_unique p (map (int.cast_ring_hom ℚ) Φ)), { intro n, specialize h n, apply_fun map (int.cast_ring_hom ℚ) at h, simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename, map_witt_polynomial, alg_hom.coe_to_ring_hom] using h, }, { intro n, apply witt_structure_rat_prop } end theorem witt_structure_int_exists_unique (Φ : mv_polynomial idx ℤ) : ∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℤ), ∀ (n : ℕ), bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i : idx, (rename (prod.mk i) (W_ ℤ n))) Φ := ⟨witt_structure_int p Φ, witt_structure_int_prop _ _, eq_witt_structure_int _ _⟩ theorem witt_structure_prop (Φ : mv_polynomial idx ℤ) (n) : aeval (λ i, map (int.cast_ring_hom R) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) = aeval (λ i, rename (prod.mk i) (W n)) Φ := begin convert congr_arg (map (int.cast_ring_hom R)) (witt_structure_int_prop p Φ n); rw hom_bind₁; apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, { refl }, { simp only [map_rename, map_witt_polynomial] } end lemma witt_structure_int_rename {σ : Type*} (Φ : mv_polynomial idx ℤ) (f : idx → σ) (n : ℕ) : witt_structure_int p (rename f Φ) n = rename (prod.map f id) (witt_structure_int p Φ n) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_rename, map_witt_structure_int, witt_structure_rat, rename_bind₁, rename_rename, bind₁_rename], refl end end p_prime
b2eacba909b3f5a292d11667392522e79e51e61a
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/krein_milman.lean
3c51794d09acf71cab654c5523c2996ee100a2ec
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
5,409
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simplicial_complex.exposed import order.order_dual open_locale classical affine big_operators open set --TODO: Generalise to LCTVS variables {E : Type*} [normed_group E] [normed_space ℝ E] {x : E} {A B : set E} namespace affine --to move to mathlib theorem zorn.subset_reverse {α : Type*} (S : set (set α)) (h : ∀c ⊆ S, zorn.chain (⊆) c → ∃lb ∈ S, ∀ s ∈ c, lb ⊆ s) : ∃ m ∈ S, ∀ a ∈ S, a ⊆ m → a = m := begin let rev : S → S → Prop := λ X Y, Y.1 ⊆ X.1, have hS : ∀ (c : set S), zorn.chain rev c → ∃ ub, ∀ a ∈ c, rev a ub, { intros c hc, obtain ⟨t, ht₁, ht₂⟩ := h (coe '' c) (by simp) (by { rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ ne, apply (hc _ hx _ hy (λ t, ne (congr_arg coe t))).symm }), exact ⟨⟨_, ht₁⟩, λ a ha, ht₂ a ⟨_, ha, rfl⟩⟩ }, obtain ⟨m, hm₁⟩ := zorn.exists_maximal_of_chains_bounded hS _, { refine ⟨m, m.prop, λ a ha ha₂, set.subset.antisymm ha₂ (hm₁ ⟨a, ha⟩ ha₂)⟩ }, intros x y z xy yz, apply set.subset.trans yz xy end /-- The Krein-Milman lemma -/ lemma has_extreme_point_of_convex_of_compact_of_nonempty (hAnemp : A.nonempty) (hAcomp : is_compact A) (hAconv : convex A) : A.extreme_points.nonempty := begin sorry /- let S : set (set E) := {B | B.nonempty ∧ is_closed B ∧ is_extreme A B}, suffices h : ∃ B ∈ S, ∀ C ∈ S, C ⊆ B → C = B, { obtain ⟨B, ⟨hBnemp, hBclos, hAB⟩, hBmin⟩ := h, obtain ⟨x, hxB⟩ := hBnemp, refine ⟨x, mem_extreme_points_iff_extreme_singleton.2 _⟩, suffices h : B = {x}, { rw ←h, exact hAB }, refine eq_singleton_iff_unique_mem.2 ⟨hxB, λ y hyB, _⟩, by_contra hyx, obtain ⟨l, hl⟩ := geometric_hahn_banach_point_point hyx, obtain ⟨z, hzB, hz⟩ := is_compact.exists_forall_ge (compact_of_is_closed_subset hAcomp hBclos hAB.1) ⟨x, hxB⟩ (continuous.continuous_on l.continuous), rw ←hBmin {z ∈ B | ∀ w ∈ B, l w ≤ l z} ⟨⟨z, hzB, hz⟩, is_exposed.is_closed ⟨l, rfl⟩ hBclos, hAB.trans (is_exposed.is_extreme ⟨l, rfl⟩)⟩ (λ z hz, hz.1) at hyB, exact not_le.2 hl (hyB.2 x hxB) }, apply zorn.subset_reverse, rintro F hFS hF, cases F.eq_empty_or_nonempty with hFemp hFnemp, { rw hFemp, refine ⟨A, ⟨hAnemp, is_compact.is_closed hAcomp, is_extreme.refl _⟩, λ B hB, _⟩, exfalso, exact hB }, refine ⟨⋂₀ F, ⟨_, is_closed_sInter (λ B hB, (hFS hB).2.1), is_extreme.sInter hFnemp (λ B hB, (hFS hB).2.2)⟩, λ B hB, sInter_subset_of_mem hB⟩, rw sInter_eq_Inter, apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _, { rintro B C, cases zorn.chain.total_of_refl hF (subtype.mem _) (subtype.mem _) with hBC hCB, exacts [⟨B, subset.refl _, hBC⟩, ⟨C, hCB, subset.refl _⟩] }, exacts [λ B, (hFS (subtype.mem _)).1, λ B, compact_of_is_closed_subset hAcomp (hFS (subtype.mem _)).2.1 (hFS (subtype.mem _)).2.2.1, λ B, (hFS (subtype.mem _)).2.1, nonempty_subtype.2 hFnemp], -/ end /-- The Krein-Milman theorem -/ lemma eq_closure_convex_hull_extreme_points_of_compact_of_convex (hAcomp : is_compact A) (hAconv : convex A) : A = closure (convex_hull A.extreme_points) := begin sorry /- let B := closure (convex_hull A.extreme_points), have hBA : B ⊆ A := closure_minimal (convex_hull_min (λ x hx, hx.1) hAconv) (is_compact.is_closed hAcomp), refine subset.antisymm _ hBA, by_contra hAB, have hABdiff : (A \ B).nonempty := nonempty_diff.2 hAB, obtain ⟨x, hxA, hxB⟩ := id hABdiff, obtain ⟨l, s, hls, hsx⟩ := geometric_hahn_banach_closed_point (convex.closure (convex_convex_hull _)) is_closed_closure hxB, let C := {y ∈ A | ∀ z ∈ A, l z ≤ l y}, have hCexp : is_exposed A C := ⟨l, rfl⟩, obtain ⟨y, hyC⟩ := has_extreme_point_of_convex_of_compact_of_nonempty begin obtain ⟨z, hzA, hz⟩ := is_compact.exists_forall_ge hAcomp ⟨x, hxA⟩ (continuous.continuous_on l.continuous), exact ⟨z, hzA, hz⟩, end (hCexp.is_compact hAcomp) (hCexp.is_convex hAconv), linarith [hls _ (subset_closure (subset_convex_hull _ (hCexp.is_extreme.extreme_points_subset_extreme_points hyC))), hyC.1.2 x hxA], -/ end /-- Carathéodory's theorem, the extreme points way -/ lemma eq_convex_hull_extreme_points_of_compact_of_convex [finite_dimensional ℝ E] (hAcomp : is_compact A) (hAconv : convex A) : A = convex_hull A.extreme_points := begin sorry /-let B := convex_hull A.extreme_points, have hBA : B ⊆ A := convex_hull_min (λ x hx, hx.1) hAconv, refine subset.antisymm _ hBA, by_contra hAB, have hABdiff : (A \ B).nonempty := nonempty_diff.2 hAB, obtain ⟨x, hxA, hxB⟩ := id hABdiff, sorry-/ end lemma closed_convex_hull_extreme_points_of_compact_of_convex [finite_dimensional ℝ E] (hAcomp : is_compact A) (hAconv : convex A) : is_closed (convex_hull A.extreme_points) := closure_eq_iff_is_closed.1 (by rw [←eq_closure_convex_hull_extreme_points_of_compact_of_convex hAcomp hAconv, ←eq_convex_hull_extreme_points_of_compact_of_convex hAcomp hAconv]) end affine
0a6d1b9d7763216ae79c99089d9d30c1b3ef1de0
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Server/References.lean
21c551ca16db282335713a8f2c7802b26138712a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
12,132
lean
/- Copyright (c) 2021 Joscha Mennicken. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joscha Mennicken -/ import Lean.Server.Utils import Std.System.Uri /-! # Representing collected and deduplicated definitions and usages -/ namespace Lean.Server open Lsp Lean.Elab Std structure Reference where ident : RefIdent /-- FVarIds that are logically identical to this reference -/ aliases : Array RefIdent := #[] range : Lsp.Range stx : Syntax ci : ContextInfo info : Info isBinder : Bool deriving Inhabited structure RefInfo where definition : Option Reference usages : Array Reference namespace RefInfo def empty : RefInfo := ⟨ none, #[] ⟩ def addRef : RefInfo → Reference → RefInfo | i@{ definition := none, .. }, ref@{ isBinder := true, .. } => { i with definition := ref } | i@{ usages, .. }, ref@{ isBinder := false, .. } => { i with usages := usages.push ref } | i, _ => i instance : Coe RefInfo Lsp.RefInfo where coe self := { definition := self.definition.map (·.range) usages := self.usages.map (·.range) } end RefInfo def ModuleRefs := HashMap RefIdent RefInfo namespace ModuleRefs def addRef (self : ModuleRefs) (ref : Reference) : ModuleRefs := let refInfo := self.findD ref.ident RefInfo.empty self.insert ref.ident (refInfo.addRef ref) instance : Coe ModuleRefs Lsp.ModuleRefs where coe self := HashMap.ofList <| List.map (fun (k, v) => (k, v)) <| self.toList end ModuleRefs end Lean.Server namespace Lean.Lsp.RefInfo open Server def empty : RefInfo := ⟨ none, #[] ⟩ def merge (a : RefInfo) (b : RefInfo) : RefInfo := { definition := b.definition.orElse fun _ => a.definition usages := a.usages.append b.usages } def contains (self : RefInfo) (pos : Lsp.Position) : Bool := Id.run do if let some range := self.definition then if contains range pos then return true for range in self.usages do if contains range pos then return true false where contains (range : Lsp.Range) (pos : Lsp.Position) : Bool := range.start <= pos && pos < range.end end Lean.Lsp.RefInfo namespace Lean.Lsp.ModuleRefs open Server def findAt (self : ModuleRefs) (pos : Lsp.Position) : Array RefIdent := Id.run do let mut result := #[] for (ident, info) in self.toList do if info.contains pos then result := result.push ident result end Lean.Lsp.ModuleRefs namespace Lean.Server open IO open Std open Lsp open Elab /-- Content of individual `.ilean` files -/ structure Ilean where version : Nat := 1 module : Name references : Lsp.ModuleRefs deriving FromJson, ToJson namespace Ilean def load (path : System.FilePath) : IO Ilean := do let content ← FS.readFile path match Json.parse content >>= fromJson? with | Except.ok ilean => pure ilean | Except.error msg => throwServerError s!"Failed to load ilean at {path}: {msg}" end Ilean /-! # Collecting and deduplicating definitions and usages -/ def identOf : Info → Option (RefIdent × Bool) | Info.ofTermInfo ti => match ti.expr with | Expr.const n .. => some (RefIdent.const n, ti.isBinder) | Expr.fvar id .. => some (RefIdent.fvar id, ti.isBinder) | _ => none | Info.ofFieldInfo fi => some (RefIdent.const fi.projName, false) | _ => none def findReferences (text : FileMap) (trees : Array InfoTree) : Array Reference := Id.run <| StateT.run' (s := #[]) do for tree in trees do tree.visitM' (postNode := fun ci info _ => do if let some (ident, isBinder) := identOf info then if let some range := info.range? then modify (·.push { ident, range := range.toLspRange text, stx := info.stx, ci, info, isBinder })) get /-- The `FVarId`s of a function parameter in the function's signature and body differ. However, they have `TermInfo` nodes with `binder := true` in the exact same position. Moreover, macros such as do-reassignment `x := e` may create chains of variable definitions where a helper definition overlaps with a use of a variable. This function changes every such group to use a single `FVarId` (the head of the chain/DAG) and gets rid of duplicate definitions. -/ partial def combineFvars (trees : Array InfoTree) (refs : Array Reference) : Array Reference := Id.run do -- Deduplicate definitions based on their exact range let mut posMap : HashMap Lsp.Range FVarId := HashMap.empty for ref in refs do if let { ident := RefIdent.fvar id, range, isBinder := true, .. } := ref then posMap := posMap.insert range id let idMap := buildIdMap posMap let mut refs' := #[] for ref in refs do match ref with | { ident := ident@(RefIdent.fvar id), .. } => if idMap.contains id then refs' := refs'.push { ref with ident := applyIdMap idMap ident, aliases := #[ident] } else if !idMap.contains id then refs' := refs'.push ref | _ => refs' := refs'.push ref refs' where findCanonicalBinder (idMap : HashMap FVarId FVarId) (id : FVarId) : FVarId := match idMap.find? id with | some id' => findCanonicalBinder idMap id' -- recursion depth is expected to be very low | none => id applyIdMap : HashMap FVarId FVarId → RefIdent → RefIdent | m, RefIdent.fvar id => RefIdent.fvar <| findCanonicalBinder m id | _, ident => ident buildIdMap posMap := Id.run <| StateT.run' (s := HashMap.empty) do -- map fvar defs to overlapping fvar defs/uses for ref in refs do if let { ident := RefIdent.fvar baseId, range, .. } := ref then if let some id := posMap.find? range then insertIdMap id baseId -- apply `FVarAliasInfo` trees.forM (·.visitM' (postNode := fun _ info _ => do if let .ofFVarAliasInfo ai := info then insertIdMap ai.id ai.baseId)) get -- NOTE: poor man's union-find; see also `findCanonicalBinder` insertIdMap id baseId := do let idMap ← get let id := findCanonicalBinder idMap id let baseId := findCanonicalBinder idMap baseId if baseId != id then modify (·.insert id baseId) def dedupReferences (refs : Array Reference) (allowSimultaneousBinderUse := false) : Array Reference := Id.run do let mut refsByIdAndRange : HashMap (RefIdent × Option Bool × Lsp.Range) Reference := HashMap.empty for ref in refs do let isBinder := if allowSimultaneousBinderUse then some ref.isBinder else none let key := (ref.ident, isBinder, ref.range) refsByIdAndRange := match refsByIdAndRange[key] with | some ref' => refsByIdAndRange.insert key { ref' with aliases := ref'.aliases ++ ref.aliases } | none => refsByIdAndRange.insert key ref let dedupedRefs := refsByIdAndRange.fold (init := #[]) fun refs _ ref => refs.push ref return dedupedRefs.qsort (·.range < ·.range) def findModuleRefs (text : FileMap) (trees : Array InfoTree) (localVars : Bool := true) (allowSimultaneousBinderUse := false) : ModuleRefs := Id.run do let mut refs := dedupReferences (allowSimultaneousBinderUse := allowSimultaneousBinderUse) <| combineFvars trees <| findReferences text trees if !localVars then refs := refs.filter fun | { ident := RefIdent.fvar _, .. } => false | _ => true refs.foldl (init := HashMap.empty) fun m ref => m.addRef ref /-! # Collecting and maintaining reference info from different sources -/ structure References where /-- References loaded from ilean files -/ ileans : HashMap Name (System.FilePath × Lsp.ModuleRefs) /-- References from workers, overriding the corresponding ilean files -/ workers : HashMap Name (Nat × Lsp.ModuleRefs) namespace References def empty : References := { ileans := HashMap.empty, workers := HashMap.empty } def addIlean (self : References) (path : System.FilePath) (ilean : Ilean) : References := { self with ileans := self.ileans.insert ilean.module (path, ilean.references) } def removeIlean (self : References) (path : System.FilePath) : References := let namesToRemove := self.ileans.toList.filter (fun (_, p, _) => p == path) |>.map (fun (n, _, _) => n) namesToRemove.foldl (init := self) fun self name => { self with ileans := self.ileans.erase name } def updateWorkerRefs (self : References) (name : Name) (version : Nat) (refs : Lsp.ModuleRefs) : References := Id.run do if let some (currVersion, _) := self.workers.find? name then if version > currVersion then return { self with workers := self.workers.insert name (version, refs) } if version == currVersion then let current := self.workers.findD name (version, HashMap.empty) let merged := refs.fold (init := current.snd) fun m ident info => m.findD ident Lsp.RefInfo.empty |>.merge info |> m.insert ident return { self with workers := self.workers.insert name (version, merged) } return self def finalizeWorkerRefs (self : References) (name : Name) (version : Nat) (refs : Lsp.ModuleRefs) : References := Id.run do if let some (currVersion, _) := self.workers.find? name then if version < currVersion then return self return { self with workers := self.workers.insert name (version, refs) } def removeWorkerRefs (self : References) (name : Name) : References := { self with workers := self.workers.erase name } def allRefs (self : References) : HashMap Name Lsp.ModuleRefs := let ileanRefs := self.ileans.toList.foldl (init := HashMap.empty) fun m (name, _, refs) => m.insert name refs self.workers.toList.foldl (init := ileanRefs) fun m (name, _, refs) => m.insert name refs def findAt (self : References) (module : Name) (pos : Lsp.Position) : Array RefIdent := Id.run do if let some refs := self.allRefs.find? module then return refs.findAt pos #[] def referringTo (self : References) (identModule : Name) (ident : RefIdent) (srcSearchPath : SearchPath) (includeDefinition : Bool := true) : IO (Array Location) := do let refsToCheck := match ident with | RefIdent.const _ => self.allRefs.toList | RefIdent.fvar _ => match self.allRefs.find? identModule with | none => [] | some refs => [(identModule, refs)] let mut result := #[] for (module, refs) in refsToCheck do if let some info := refs.find? ident then if let some path ← srcSearchPath.findModuleWithExt "lean" module then -- Resolve symlinks (such as `src` in the build dir) so that files are -- opened in the right folder let uri := System.Uri.pathToUri <| ← IO.FS.realPath path if includeDefinition then if let some range := info.definition then result := result.push ⟨uri, range⟩ for range in info.usages do result := result.push ⟨uri, range⟩ return result def definitionOf? (self : References) (ident : RefIdent) (srcSearchPath : SearchPath) : IO (Option Location) := do for (module, refs) in self.allRefs.toList do if let some info := refs.find? ident then if let some definition := info.definition then if let some path ← srcSearchPath.findModuleWithExt "lean" module then -- Resolve symlinks (such as `src` in the build dir) so that files are -- opened in the right folder let uri := System.Uri.pathToUri <| ← IO.FS.realPath path return some ⟨uri, definition⟩ return none def definitionsMatching (self : References) (srcSearchPath : SearchPath) (filter : Name → Option α) (maxAmount? : Option Nat := none) : IO $ Array (α × Location) := do let mut result := #[] for (module, refs) in self.allRefs.toList do if let some path ← srcSearchPath.findModuleWithExt "lean" module then let uri := System.Uri.pathToUri <| ← IO.FS.realPath path for (ident, info) in refs.toList do if let (RefIdent.const name, some definition) := (ident, info.definition) then if let some a := filter name then result := result.push (a, ⟨uri, definition⟩) if let some maxAmount := maxAmount? then if result.size >= maxAmount then return result return result end References end Lean.Server
f87b36b851e30ba68fe10fb37948594eb1a572b8
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_geometry/projective_spectrum/scheme.lean
82bb7e9c258a6907adaaf927a92b90aef7d1450f
[ "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,431
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebraic_geometry.projective_spectrum.structure_sheaf import algebraic_geometry.Spec /-! # Proj as a scheme This file is to prove that `Proj` is a scheme. ## Notation * `Proj` : `Proj` as a locally ringed space * `Proj.T` : the underlying topological space of `Proj` * `Proj| U` : `Proj` restricted to some open set `U` * `Proj.T| U` : the underlying topological space of `Proj` restricted to open set `U` * `pbo f` : basic open set at `f` in `Proj` * `Spec` : `Spec` as a locally ringed space * `Spec.T` : the underlying topological space of `Spec` * `sbo g` : basic open set at `g` in `Spec` * `A⁰_x` : the degree zero part of localized ring `Aₓ` ## Implementation In `src/algebraic_geometry/projective_spectrum/structure_sheaf.lean`, we have given `Proj` a structure sheaf so that `Proj` is a locally ringed space. In this file we will prove that `Proj` equipped with this structure sheaf is a scheme. We achieve this by using an affine cover by basic open sets in `Proj`, more specifically: 1. We prove that `Proj` can be covered by basic open sets at homogeneous element of positive degree. 2. We prove that for any `f : A`, `Proj.T | (pbo f)` is homeomorphic to `Spec.T A⁰_f`: - forward direction : for any `x : pbo f`, i.e. a relevant homogeneous prime ideal `x`, send it to `x ∩ span {g / 1 | g ∈ A}` (see `Top_component.forward.carrier`). This ideal is prime, the proof is in `Top_component.forward.to_fun`. The fact that this function is continuous is found in `Top_component.forward` - backward direction : TBC ## Main Definitions and Statements * `degree_zero_part`: the degree zero part of the localized ring `Aₓ` where `x` is a homogeneous element of degree `n` is the subring of elements of the form `a/f^m` where `a` has degree `mn`. For a homogeneous element `f` of degree `n` * `Top_component.forward`: `forward f` is the continuous map between `Proj.T| pbo f` and `Spec.T A⁰_f` * `Top_component.forward.preimage_eq`: for any `a: A`, if `a/f^m` has degree zero, then the preimage of `sbo a/f^m` under `forward f` is `pbo f ∩ pbo a`. * [Robin Hartshorne, *Algebraic Geometry*][Har77]: Chapter II.2 Proposition 2.5 -/ noncomputable theory namespace algebraic_geometry open_locale direct_sum big_operators pointwise big_operators open direct_sum set_like.graded_monoid localization finset (hiding mk_zero) variables {R A : Type*} variables [comm_ring R] [comm_ring A] [algebra R A] variables (𝒜 : ℕ → submodule R A) variables [graded_algebra 𝒜] open Top topological_space open category_theory opposite open projective_spectrum.structure_sheaf local notation `Proj` := Proj.to_LocallyRingedSpace 𝒜 -- `Proj` as a locally ringed space local notation `Proj.T` := Proj .1.1.1 -- the underlying topological space of `Proj` local notation `Proj| ` U := Proj .restrict (opens.open_embedding (U : opens Proj.T)) -- `Proj` restrict to some open set local notation `Proj.T| ` U := (Proj .restrict (opens.open_embedding (U : opens Proj.T))).to_SheafedSpace.to_PresheafedSpace.1 -- the underlying topological space of `Proj` restricted to some open set local notation `pbo` x := projective_spectrum.basic_open 𝒜 x -- basic open sets in `Proj` local notation `sbo` f := prime_spectrum.basic_open f -- basic open sets in `Spec` local notation `Spec` ring := Spec.LocallyRingedSpace_obj (CommRing.of ring) -- `Spec` as a locally ringed space local notation `Spec.T` ring := (Spec.LocallyRingedSpace_obj (CommRing.of ring)).to_SheafedSpace.to_PresheafedSpace.1 -- the underlying topological space of `Spec` section variable {𝒜} /-- The degree zero part of the localized ring `Aₓ` is the subring of elements of the form `a/x^n` such that `a` and `x^n` have the same degree. -/ def degree_zero_part {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) : subring (away f) := { carrier := { y | ∃ (n : ℕ) (a : 𝒜 (m * n)), y = mk a.1 ⟨f^n, ⟨n, rfl⟩⟩ }, mul_mem' := λ _ _ ⟨n, ⟨a, h⟩⟩ ⟨n', ⟨b, h'⟩⟩, h.symm ▸ h'.symm ▸ ⟨n+n', ⟨⟨a.1 * b.1, (mul_add m n n').symm ▸ mul_mem a.2 b.2⟩, by {rw mk_mul, congr' 1, simp only [pow_add], refl }⟩⟩, one_mem' := ⟨0, ⟨1, (mul_zero m).symm ▸ one_mem⟩, by { symmetry, convert ← mk_self 1, simp only [pow_zero], refl, }⟩, add_mem' := λ _ _ ⟨n, ⟨a, h⟩⟩ ⟨n', ⟨b, h'⟩⟩, h.symm ▸ h'.symm ▸ ⟨n+n', ⟨⟨f ^ n * b.1 + f ^ n' * a.1, (mul_add m n n').symm ▸ add_mem (mul_mem (by { rw mul_comm, exact set_like.graded_monoid.pow_mem n f_deg }) b.2) begin rw add_comm, refine mul_mem _ a.2, rw mul_comm, exact set_like.graded_monoid.pow_mem _ f_deg end⟩, begin rw add_mk, congr' 1, simp only [pow_add], refl, end⟩⟩, zero_mem' := ⟨0, ⟨0, (mk_zero _).symm⟩⟩, neg_mem' := λ x ⟨n, ⟨a, h⟩⟩, h.symm ▸ ⟨n, ⟨-a, neg_mk _ _⟩⟩ } local notation `A⁰_` f_deg := degree_zero_part f_deg instance (f : A) {m : ℕ} (f_deg : f ∈ 𝒜 m) : comm_ring (degree_zero_part f_deg) := (degree_zero_part f_deg).to_comm_ring /-- Every element in the degree zero part of `Aₓ` can be written as `a/x^n` for some `a` and `n : ℕ`, `degree_zero_part.deg` picks this natural number `n` -/ def degree_zero_part.deg {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x : A⁰_ f_deg) : ℕ := x.2.some /-- Every element in the degree zero part of `Aₓ` can be written as `a/x^n` for some `a` and `n : ℕ`, `degree_zero_part.deg` picks the numerator `a` -/ def degree_zero_part.num {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x : A⁰_ f_deg) : A := x.2.some_spec.some.1 lemma degree_zero_part.num_mem {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x : A⁰_ f_deg) : degree_zero_part.num f_deg x ∈ 𝒜 (m * degree_zero_part.deg f_deg x) := x.2.some_spec.some.2 lemma degree_zero_part.eq {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x : A⁰_ f_deg) : x.1 = mk (degree_zero_part.num f_deg x) ⟨f^(degree_zero_part.deg f_deg x), ⟨_, rfl⟩⟩ := x.2.some_spec.some_spec lemma degree_zero_part.mul_val {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x y : A⁰_ f_deg) : (x * y).1 = x.1 * y.1 := rfl end end algebraic_geometry
e0653f8eee37363a64988dff6293f1ba1c6f38ca
1890046a4987fbd27f3f50dbac83f3ce095556d5
/01_Equality/04_propositions_as_types.lean
319571d1fac55e6186865e269b5518e31d9238a9
[]
no_license
kbhuynh/cs-dm
9f335727d1779f7c3d9e8221a52b4c9c106659ba
4041bd73618a49ef6870a1a80764e8947e60e768
refs/heads/master
1,585,353,017,958
1,536,055,215,000
1,536,055,215,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,930
lean
/- Wait! Lean is telling us that: eq.refl 0 : 0 = 0. Putting parenthesis in can make it easier to read: (eq.refl 0) : (0 = 0). We've so far read this as saying that (eq.refl 0) is a proof of 0 = 0. But the observant reader will see that it looks just like a type judgment as well. It looks like it's saying that (eq.refl 0) is a value of type (0 = 0). And indeed that is exactly what it's saying. Here is the deep idea: in the "constructive logic" of Lean, propositions are formalized as types, and proofs are represented values of these types! A proof,then, is valid for a given proposition if it is a value of the corresponding type. And Lean's type checker can always determine whether that is the case! In lieu of human checking of the validity of proofs, we therefore now have a mechanical proof checker! Read the eq_refl inference rule again. We can now see it clearly as defining a computation. It can now be seen as saying, "if you give me any value, t, I will infer its type, T, and will return to you a value (a proof!) of type, t = t. Not only that but the type-checker will provide you with a very high degree of assurance that it's a valid proof! -/ /- We can also now understand what it means when we say that Lean is a proof checker. It means that Lean will not allow us to use proofs that are not valid (with respect to the propositions they are supposed to prove) because they won't type check. -/ /- Let's look at type checking a little more deeply. We can always assign to a variable a value of the type that the variable is declared to have. -/ def n : nat := 1 /- This Lean definition says that n is a variable for which a value of type nat must be provided (n : nat), and it goes on to assign to n ( := ) the value 1. ℤ The Lean type checker checks that 1 is a value of type nat, which it is. Lean therefore accepts the definition, and consequently n is defined, with the value, 1, for the remainder of this file. We note that we could have elided the explicit type declaration (n : nat), as Lean infers from the value, 1, on the right, that the intended type of n can only be nat. -/ def n' := 1 #check n' /- The type checker also absolutely prevents the assignment to a variable of a value that is not of the right type. Read the following code and identify the type error, then uncomment it and see how Lean detects and reports the error. Be sure you understand the error message. This one is self-explanatory. -/ -- def n'' : nat := "Hello Lean!" /- Now let's replace the "nat" type with the type "0 = 0." Remember, every proposition is now viewed as a type. We could thus similarly declare a variable, p, to have this type, just as we declared n to have type nat. Finally we would need to assign to p a value of this type, which is to say a proof of 0 = 0. Compare this code carefully with that for n, above. Note the deep parallels. Here, however, rather than assigning a value such as 1, we're assigning a value that is a proof, and it, in turn, is produced by applying the eq.refl inference rule to the value 0. -/ def p : 0 = 0 := (eq.refl 0) /- variable type bind value/proof -/ #check p -- what is the type of p? #reduce p -- what is the value of p? /- EXERCISE: To the variable s, bind a proof of the proposition that "Hello Lean!" is equal to itself. EXERCISE: Do the same for the Boolean value, tt. -/ /- And just as the type checker prevents the assignment of a value that is not of the right type to a variable such as n, so it also prevents the assignment to p of a proof that is not of the right type. -/ /- EXERCISE. Explain precisely why Lean reports an error for this code and what it means. (Uncomment the code to see the error, then replace the comments so that the error isn't a problem in the rest of this file.) -/ -- def p' : 0 = 0 := (eq.refl 1) /- In Lean and related proof assistants, propositions are types, proofs are values of proposition types, and proof checking *is* type checking. Put a start next to this paragraph and be sure that you understand it. It takes time and study to fully grasp these concepts. -/ /- Now for a brief aside on lexicon. When we assign a computational data value, such as 1, to a variable, we generally use the keyword, def. When we assign a proof as a value to a parameter, we instead generally use the mathematical term, "theorem" or "lemma" instead. In Lean, these terms are interchangeable. They mean the same thing. But to make your Lean code easier for people to interpret, it's always a good idea to use the term that aligns with mathematical practice. Use theorem for proofs of major results. Use lemma for proofs of results that in turn are incorporated into theorems. Use def to define data and function values (computational as opposed to logical values). -/ /- EXERCISE: Use "theorem" instead of def to bind a proof of 0 = 0 to a variable, s'. Note that theorem, lemma, and def all mean the same thing in Lean. In practice, you should use one or the other to communicate your intent. Def is usually used to define function and data values, while theorem and lemma are used to define proof values. -/ /- EXERCISE: Prove theorems for the following propositions: oeqo : 1 = 1 heqh : "Hello Lean! = Hello Lean!" teqt : 2 = 1 + 1 -/ /- That last proposition, 2 = 1 + 1, is a bit different because it has different terms on each side of the equals sign. In Lean, these terms are reduced (evaluated) before they are compared, and so eq.refl can be used to prove this proposition. -/ /- We've already seen that types are values, too, and that a type thus has a type. The type of nat is Type, for example. So, in Lean, what is the type of a proposition, such as 0 = 0? Let's find out using #check. -/ #check (0 = 0) /- EXERCISE: What is the type of (0 = 1)? Answer before you #check it, then #check it to confirm. EXERCISE: What is the type of "Hello Lean" = "Hello Lean"? -/ /- Lean tells us that the type of each proposition is Prop. In Lean, every logical proposition is of type Prop, just as every ordinary computational type, such as nat, bool, or string, is of type, Type. So how do Prop and Type relate? -/ /- To prepare to answer this question, let's first claim and then prove that "Type" is a shorthand for Type 0. -/ theorem type0 : Type = Type 0 := eq.refl Type /- So now we know that Type is a shorthand for Type 0. And we already know that the type of Type (and thus of Type 0) is Type 1; it's type is Type 2; its type is Type 3; etc ad infinitum. -/ /- Ok, then, so where does Prop fit in? What is its type? To find out, we need to know the answer to the question, what is the type of Prop? We can of course just #check it. -/ #check Prop /- Ah ha. Prop is of type Type, which is to say that that Prop is of type, Type 0. We thus now have a complete picture of the type hierarchy of Lean. Prop : Type : Type 1 : Type 2 : Type 3 : ... | | 0 = 0 nat | | eq.refl 0 1 Prop is the first type in the hierarchy. Every propositional type is of type Prop. We illustrate here that the type (0=0) is of type Prop, but so is 0 = 1, 1 = 1, tt = tt, and so are all of the other propositions we'll ever see in Lean. All propositions, which again are themselves types, are of type Prop in the logic of Lean. By contrast, computational types, such as nat, but also string, bool, and function types (we will see them soon enough) are of type, Type. The lowest layer in the diagram illustrates where values fit in. The proof, eq.refl 0, is a value of type (0 = 0), just as 1 is a value of type nat. We will never need types above Type in this class. Mathematicians, logicians, and program verification experts who use Lean and other tools like it do sometimes need to be careful about how values fall into the various "type universes," as these various levels are called. -/
811d0c80721749f19da188d195f327e5cb1ea489
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/algebra/field.hlean
e0f71e61b3e66e4ca9f83075ec1d2fc44290c218
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,013
hlean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis Structures with multiplicative and additive components, including division rings and fields. The development is modeled after Isabelle's library. Ported from the standard library -/ import algebra.ring open core namespace algebra variable {A : Type} -- in division rings, 1 / 0 = 0 structure division_ring [class] (A : Type) extends ring A, has_inv A, zero_ne_one_class A := (mul_inv_cancel : Π{a}, a ≠ zero → mul a (inv a) = one) (inv_mul_cancel : Π{a}, a ≠ zero → mul (inv a) a = one) --(inv_zero : inv zero = zero) section division_ring variables [s : division_ring A] {a b c : A} include s definition divide (a b : A) : A := a * b⁻¹ infix / := divide -- only in this file local attribute divide [reducible] definition mul_inv_cancel (H : a ≠ 0) : a * a⁻¹ = 1 := division_ring.mul_inv_cancel H definition inv_mul_cancel (H : a ≠ 0) : a⁻¹ * a = 1 := division_ring.inv_mul_cancel H definition inv_eq_one_div : a⁻¹ = 1 / a := !one_mul⁻¹ -- the following are only theorems if we assume inv_zero here /- definition inv_zero : 0⁻¹ = 0 := !division_ring.inv_zero definition one_div_zero : 1 / 0 = 0 := calc 1 / 0 = 1 * 0⁻¹ : refl ... = 1 * 0 : division_ring.inv_zero A ... = 0 : mul_zero -/ definition div_eq_mul_one_div : a / b = a * (1 / b) := by rewrite [↑divide, one_mul] -- definition div_zero : a / 0 = 0 := by rewrite [div_eq_mul_one_div, one_div_zero, mul_zero] definition mul_one_div_cancel (H : a ≠ 0) : a * (1 / a) = 1 := by rewrite [-inv_eq_one_div, (mul_inv_cancel H)] definition one_div_mul_cancel (H : a ≠ 0) : (1 / a) * a = 1 := by rewrite [-inv_eq_one_div, (inv_mul_cancel H)] definition div_self (H : a ≠ 0) : a / a = 1 := mul_inv_cancel H definition one_div_one : 1 / 1 = (1:A) := div_self (ne.symm zero_ne_one) definition mul_div_assoc : (a * b) / c = a * (b / c) := !mul.assoc definition one_div_ne_zero (H : a ≠ 0) : 1 / a ≠ 0 := assume H2 : 1 / a = 0, have C1 : 0 = (1:A), from inverse (by rewrite [-(mul_one_div_cancel H), H2, mul_zero]), absurd C1 zero_ne_one -- definition ne_zero_of_one_div_ne_zero (H : 1 / a ≠ 0) : a ≠ 0 := -- assume Ha : a = 0, absurd (Ha⁻¹ ▸ one_div_zero) H definition inv_one_eq : 1⁻¹ = (1:A) := by rewrite [-mul_one, (inv_mul_cancel (ne.symm (@zero_ne_one A _)))] definition div_one : a / 1 = a := by rewrite [↑divide, inv_one_eq, mul_one] definition zero_div : 0 / a = 0 := !zero_mul -- note: integral domain has a "mul_ne_zero". Discrete fields are int domains. definition mul_ne_zero' (Ha : a ≠ 0) (Hb : b ≠ 0) : a * b ≠ 0 := assume H : a * b = 0, have C1 : a = 0, by rewrite [-mul_one, -(mul_one_div_cancel Hb), -mul.assoc, H, zero_mul], absurd C1 Ha definition mul_ne_zero_comm (H : a * b ≠ 0) : b * a ≠ 0 := have H2 : a ≠ 0 × b ≠ 0, from ne_zero_and_ne_zero_of_mul_ne_zero H, mul_ne_zero' (prod.pr2 H2) (prod.pr1 H2) -- make "left" and "right" versions? definition eq_one_div_of_mul_eq_one (H : a * b = 1) : b = 1 / a := have H2 : a ≠ 0, from (assume aeq0 : a = 0, have B : 0 = (1:A), by rewrite [-(zero_mul b), -aeq0, H], absurd B zero_ne_one), show b = 1 / a, from inverse (calc 1 / a = (1 / a) * 1 : mul_one ... = (1 / a) * (a * b) : H ... = (1 / a) * a * b : mul.assoc ... = 1 * b : one_div_mul_cancel H2 ... = b : one_mul) -- which one is left and which is right? definition eq_one_div_of_mul_eq_one_left (H : b * a = 1) : b = 1 / a := have H2 : a ≠ 0, from (assume A : a = 0, have B : 0 = 1, from inverse (calc 1 = b * a : inverse H ... = b * 0 : A ... = 0 : mul_zero), absurd B zero_ne_one), show b = 1 / a, from inverse (calc 1 / a = 1 * (1 / a) : one_mul ... = b * a * (1 / a) : H ... = b * (a * (1 / a)) : mul.assoc ... = b * 1 : mul_one_div_cancel H2 ... = b : mul_one) definition one_div_mul_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (b * a) := have H : (b * a) * ((1 / a) * (1 / b)) = 1, by rewrite [mul.assoc, -(mul.assoc a), (mul_one_div_cancel Ha), one_mul, (mul_one_div_cancel Hb)], eq_one_div_of_mul_eq_one H definition one_div_neg_one_eq_neg_one : (1:A) / (-1) = -1 := have H : (-1) * (-1) = 1, by rewrite [-neg_eq_neg_one_mul, neg_neg], inverse (eq_one_div_of_mul_eq_one H) definition one_div_neg_eq_neg_one_div (H : a ≠ 0) : 1 / (- a) = - (1 / a) := have H1 : -1 ≠ 0, from (assume H2 : -1 = 0, absurd (inverse (calc 1 = -(-1) : neg_neg ... = -0 : H2 ... = (0:A) : neg_zero)) zero_ne_one), calc 1 / (- a) = 1 / ((-1) * a) : neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : one_div_mul_one_div H H1 ... = (1 / a) * (-1) : one_div_neg_one_eq_neg_one ... = - (1 / a) : mul_neg_one_eq_neg definition div_neg_eq_neg_div (Ha : a ≠ 0) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : inv_eq_one_div ... = b * -(1 / a) : one_div_neg_eq_neg_one_div Ha ... = -(b * (1 / a)) : neg_mul_eq_mul_neg ... = - (b * a⁻¹) : inv_eq_one_div definition neg_div (Ha : a ≠ 0) : (-b) / a = - (b / a) := by rewrite [neg_eq_neg_one_mul, mul_div_assoc, -neg_eq_neg_one_mul] definition neg_div_neg_eq_div (Hb : b ≠ 0) : (-a) / (-b) = a / b := by rewrite [(div_neg_eq_neg_div Hb), (neg_div Hb), neg_neg] definition div_div (H : a ≠ 0) : 1 / (1 / a) = a := inverse (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel H)) definition eq_of_invs_eq (Ha : a ≠ 0) (Hb : b ≠ 0) (H : 1 / a = 1 / b) : a = b := by rewrite [-(div_div Ha), H, (div_div Hb)] -- oops, the analogous definition in group is called inv_mul, but it *should* be called -- mul_inv, in which case, we will have to rename this one definition mul_inv_eq (Ha : a ≠ 0) (Hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := have H1 : b * a ≠ 0, from mul_ne_zero' Hb Ha, inverse (calc a⁻¹ * b⁻¹ = (1 / a) * b⁻¹ : inv_eq_one_div ... = (1 / a) * (1 / b) : inv_eq_one_div ... = (1 / (b * a)) : one_div_mul_one_div Ha Hb ... = (b * a)⁻¹ : inv_eq_one_div) definition mul_div_cancel (Hb : b ≠ 0) : a * b / b = a := by rewrite [↑divide, mul.assoc, (mul_inv_cancel Hb), mul_one] definition div_mul_cancel (Hb : b ≠ 0) : a / b * b = a := by rewrite [↑divide, mul.assoc, (inv_mul_cancel Hb), mul_one] definition div_add_div_same : a / c + b / c = (a + b) / c := !right_distrib⁻¹ definition inv_mul_add_mul_inv_eq_inv_add_inv (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rewrite [(left_distrib (1 / a)), (one_div_mul_cancel Ha), right_distrib, one_mul, mul.assoc, (mul_one_div_cancel Hb), mul_one, add.comm] definition inv_mul_sub_mul_inv_eq_inv_add_inv (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rewrite [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel Ha), mul_sub_right_distrib, one_mul, mul.assoc, (mul_one_div_cancel Hb), mul_one, one_mul] definition div_eq_one_iff_eq (Hb : b ≠ 0) : a / b = 1 ↔ a = b := iff.intro (assume H1 : a / b = 1, inverse (calc b = 1 * b : one_mul ... = a / b * b : H1 ... = a : div_mul_cancel Hb)) (assume H2 : a = b, calc a / b = b / b : H2 ... = 1 : div_self Hb) definition eq_div_iff_mul_eq (Hc : c ≠ 0) : a = b / c ↔ a * c = b := iff.intro (assume H : a = b / c, by rewrite [H, (div_mul_cancel Hc)]) (assume H : a * c = b, by rewrite [-(mul_div_cancel Hc), H]) definition add_div_eq_mul_add_div (Hc : c ≠ 0) : a + b / c = (a * c + b) / c := have H : (a + b / c) * c = a * c + b, by rewrite [right_distrib, (div_mul_cancel Hc)], (iff.elim_right (eq_div_iff_mul_eq Hc)) H definition mul_mul_div (Hc : c ≠ 0) : a = a * c * (1 / c) := calc a = a * 1 : mul_one ... = a * (c * (1 / c)) : mul_one_div_cancel Hc ... = a * c * (1 / c) : mul.assoc -- There are many similar rules to these last two in the Isabelle library -- that haven't been ported yet. Do as necessary. end division_ring structure field [class] (A : Type) extends division_ring A, comm_ring A section field variables [s : field A] {a b c d: A} include s local attribute divide [reducible] definition one_div_mul_one_div' (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (a * b) := by rewrite [(one_div_mul_one_div Ha Hb), mul.comm b] definition div_mul_right (Hb : b ≠ 0) (H : a * b ≠ 0) : a / (a * b) = 1 / b := let Ha : a ≠ 0 := prod.pr1 (ne_zero_and_ne_zero_of_mul_ne_zero H) in inverse (calc 1 / b = 1 * (1 / b) : one_mul ... = (a * a⁻¹) * (1 / b) : mul_inv_cancel Ha ... = a * (a⁻¹ * (1 / b)) : mul.assoc ... = a * ((1 / a) * (1 / b)) :inv_eq_one_div ... = a * (1 / (b * a)) : one_div_mul_one_div Ha Hb ... = a * (1 / (a * b)) : mul.comm ... = a * (a * b)⁻¹ : inv_eq_one_div) definition div_mul_left (Ha : a ≠ 0) (H : a * b ≠ 0) : b / (a * b) = 1 / a := let H1 : b * a ≠ 0 := mul_ne_zero_comm H in by rewrite [mul.comm a, (div_mul_right Ha H1)] definition mul_div_cancel_left (Ha : a ≠ 0) : a * b / a = b := by rewrite [mul.comm a, (mul_div_cancel Ha)] definition mul_div_cancel' (Hb : b ≠ 0) : b * (a / b) = a := by rewrite [mul.comm, (div_mul_cancel Hb)] definition one_div_add_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := have H [visible] : a * b ≠ 0, from (mul_ne_zero' Ha Hb), by rewrite [add.comm, -(div_mul_left Ha H), -(div_mul_right Hb H), ↑divide, -right_distrib] definition div_mul_div (Hb : b ≠ 0) (Hd : d ≠ 0) : (a / b) * (c / d) = (a * c) / (b * d) := by rewrite [↑divide, 2 mul.assoc, (mul.comm b⁻¹), mul.assoc, (mul_inv_eq Hd Hb)] definition mul_div_mul_left (Hb : b ≠ 0) (Hc : c ≠ 0) : (c * a) / (c * b) = a / b := have H [visible] : c * b ≠ 0, from mul_ne_zero' Hc Hb, by rewrite [-(div_mul_div Hc Hb), (div_self Hc), one_mul] definition mul_div_mul_right (Hb : b ≠ 0) (Hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rewrite [(mul.comm a), (mul.comm b), (mul_div_mul_left Hb Hc)] definition div_mul_eq_mul_div : (b / c) * a = (b * a) / c := by rewrite [↑divide, mul.assoc, (mul.comm c⁻¹), -mul.assoc] -- this one is odd -- I am not sure what to call it, but again, the prefix is right definition div_mul_eq_mul_div_comm (Hc : c ≠ 0) : (b / c) * a = b * (a / c) := by rewrite [(div_mul_eq_mul_div), -(one_mul c), -(div_mul_div (ne.symm zero_ne_one) Hc), div_one, one_mul] definition div_add_div (Hb : b ≠ 0) (Hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := have H [visible] : b * d ≠ 0, from mul_ne_zero' Hb Hd, by rewrite [-(mul_div_mul_right Hb Hd), -(mul_div_mul_left Hd Hb), div_add_div_same] definition div_sub_div (Hb : b ≠ 0) (Hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := by rewrite [↑sub, neg_eq_neg_one_mul, -mul_div_assoc, (div_add_div Hb Hd), -mul.assoc, (mul.comm b), mul.assoc, -neg_eq_neg_one_mul] definition mul_eq_mul_of_div_eq_div (Hb : b ≠ 0) (Hd : d ≠ 0) (H : a / b = c / d) : a * d = c * b := by rewrite [-mul_one, mul.assoc, (mul.comm d), -mul.assoc, -(div_self Hb), -(div_mul_eq_mul_div_comm Hb), H, (div_mul_eq_mul_div), (div_mul_cancel Hd)] definition one_div_div (Ha : a ≠ 0) (Hb : b ≠ 0) : 1 / (a / b) = b / a := have H : (a / b) * (b / a) = 1, from calc (a / b) * (b / a) = (a * b) / (b * a) : div_mul_div Hb Ha ... = (a * b) / (a * b) : mul.comm ... = 1 : div_self (mul_ne_zero' Ha Hb), inverse (eq_one_div_of_mul_eq_one H) definition div_div_eq_mul_div (Hb : b ≠ 0) (Hc : c ≠ 0) : a / (b / c) = (a * c) / b := by rewrite [div_eq_mul_one_div, (one_div_div Hb Hc), -mul_div_assoc] definition div_div_eq_div_mul (Hb : b ≠ 0) (Hc : c ≠ 0) : (a / b) / c = a / (b * c) := by rewrite [div_eq_mul_one_div, (div_mul_div Hb Hc), mul_one] definition div_div_div_div (Hb : b ≠ 0) (Hc : c ≠ 0) (Hd : d ≠ 0) : (a / b) / (c / d) = (a * d) / (b * c) := by rewrite [(div_div_eq_mul_div Hc Hd), (div_mul_eq_mul_div), (div_div_eq_div_mul Hb Hc)] -- remaining to transfer from Isabelle fields: ordered fields end field structure discrete_field [class] (A : Type) extends field A := (has_decidable_eq : decidable_eq A) (inv_zero : inv zero = zero) attribute discrete_field.has_decidable_eq [instance] section discrete_field variable [s : discrete_field A] include s variables {a b c d : A} -- many of the theorems in discrete_field are the same as theorems in field or division ring, -- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable. -- they are named with '. Is there a better convention? definition discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero (x y : A) (H : x * y = 0) : x = 0 ⊎ y = 0 := decidable.by_cases (assume H : x = 0, sum.inl H) (assume H1 : x ≠ 0, sum.inr (by rewrite [-one_mul, -(inv_mul_cancel H1), mul.assoc, H, mul_zero])) definition discrete_field.to_integral_domain [instance] [reducible] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero⦄ definition inv_zero : 0⁻¹ = (0 : A) := !discrete_field.inv_zero definition one_div_zero : 1 / 0 = (0:A) := calc 1 / 0 = 1 * 0⁻¹ : refl ... = 1 * 0 : discrete_field.inv_zero A ... = 0 : mul_zero definition div_zero : a / 0 = 0 := by rewrite [div_eq_mul_one_div, one_div_zero, mul_zero] definition ne_zero_of_one_div_ne_zero (H : 1 / a ≠ 0) : a ≠ 0 := assume Ha : a = 0, absurd (Ha⁻¹ ▸ one_div_zero) H definition inv_zero_imp_zero (H : 1 / a = 0) : a = 0 := decidable.by_cases (assume Ha, Ha) (assume Ha, empty.elim ((one_div_ne_zero Ha) H)) -- the following could all go in "discrete_division_ring" definition one_div_mul_one_div'' : (1 / a) * (1 / b) = 1 / (b * a) := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, div_zero, zero_mul, -(@div_zero A s 1), mul_zero b]) (assume Ha : a ≠ 0, decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, div_zero, mul_zero, -(@div_zero A s 1), zero_mul a]) (assume Hb : b ≠ 0, one_div_mul_one_div Ha Hb)) definition one_div_neg_eq_neg_one_div' : 1 / (- a) = - (1 / a) := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, neg_zero, 2 div_zero, neg_zero]) (assume Ha : a ≠ 0, one_div_neg_eq_neg_one_div Ha) definition neg_div' : (-b) / a = - (b / a) := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, 2 div_zero, neg_zero]) (assume Ha : a ≠ 0, neg_div Ha) definition neg_div_neg_eq_div' : (-a) / (-b) = a / b := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, neg_zero, 2 div_zero]) (assume Hb : b ≠ 0, neg_div_neg_eq_div Hb) definition div_div' : 1 / (1 / a) = a := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, 2 div_zero]) (assume Ha : a ≠ 0, div_div Ha) definition eq_of_invs_eq' (H : 1 / a = 1 / b) : a = b := decidable.by_cases (assume Ha : a = 0, have Hb : b = 0, from inv_zero_imp_zero (by rewrite [-H, Ha, div_zero]), Hb⁻¹ ▸ Ha) (assume Ha : a ≠ 0, have Hb : b ≠ 0, from ne_zero_of_one_div_ne_zero (H ▸ (one_div_ne_zero Ha)), eq_of_invs_eq Ha Hb H) definition mul_inv' : (b * a)⁻¹ = a⁻¹ * b⁻¹ := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, mul_zero, 2 inv_zero, zero_mul]) (assume Ha : a ≠ 0, decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, zero_mul, 2 inv_zero, mul_zero]) (assume Hb : b ≠ 0, mul_inv_eq Ha Hb)) -- the following are specifically for fields definition one_div_mul_one_div''' : (1 / a) * (1 / b) = 1 / (a * b) := by rewrite [(one_div_mul_one_div''), mul.comm b] definition div_mul_right' (Ha : a ≠ 0) : a / (a * b) = 1 / b := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, mul_zero, 2 div_zero]) (assume Hb : b ≠ 0, div_mul_right Hb (mul_ne_zero Ha Hb)) definition div_mul_left' (Hb : b ≠ 0) : b / (a * b) = 1 / a := by rewrite [mul.comm a, div_mul_right' Hb] definition div_mul_div' : (a / b) * (c / d) = (a * c) / (b * d) := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, div_zero, zero_mul, -(@div_zero A s (a * c)), zero_mul]) (assume Hb : b ≠ 0, decidable.by_cases (assume Hd : d = 0, by rewrite [Hd, div_zero, mul_zero, -(@div_zero A s (a * c)), mul_zero]) (assume Hd : d ≠ 0, div_mul_div Hb Hd)) definition mul_div_mul_left' (Hc : c ≠ 0) : (c * a) / (c * b) = a / b := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, mul_zero, 2 div_zero]) (assume Hb : b ≠ 0, mul_div_mul_left Hb Hc) definition mul_div_mul_right' (Hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rewrite [(mul.comm a), (mul.comm b), (mul_div_mul_left' Hc)] -- this one is odd -- I am not sure what to call it, but again, the prefix is right definition div_mul_eq_mul_div_comm' : (b / c) * a = b * (a / c) := decidable.by_cases (assume Hc : c = 0, by rewrite [Hc, div_zero, zero_mul, -(mul_zero b), -(@div_zero A s a)]) (assume Hc : c ≠ 0, div_mul_eq_mul_div_comm Hc) definition one_div_div' : 1 / (a / b) = b / a := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, zero_div, 2 div_zero]) (assume Ha : a ≠ 0, decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, 2 div_zero, zero_div]) (assume Hb : b ≠ 0, one_div_div Ha Hb)) definition div_div_eq_mul_div' : a / (b / c) = (a * c) / b := by rewrite [div_eq_mul_one_div, one_div_div', -mul_div_assoc] definition div_div_eq_div_mul' : (a / b) / c = a / (b * c) := by rewrite [div_eq_mul_one_div, div_mul_div', mul_one] definition div_div_div_div' : (a / b) / (c / d) = (a * d) / (b * c) := by rewrite [div_div_eq_mul_div', div_mul_eq_mul_div, div_div_eq_div_mul'] end discrete_field end algebra /- decidable.by_cases (assume Ha : a = 0, sorry) (assume Ha : a ≠ 0, sorry) -/
e95c407841163aad9e98bb89849e659f304166f8
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.22.lean
1634657322c7af1b7302eb008980cf611720b486
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
776
lean
import standard example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := iff.intro (assume H : p ∧ (q ∨ r), show (p ∧ q) ∨ (p ∧ r), from proof have Hp : p, from and.elim_left H, or.elim (and.elim_right H) (assume Hq : q, show (p ∧ q) ∨ (p ∧ r), from or.inl (and.intro Hp Hq)) (assume Hr : r, show (p ∧ q) ∨ (p ∧ r), from or.inr (and.intro Hp Hr)) qed) (assume H : (p ∧ q) ∨ (p ∧ r), show p ∧ (q ∨ r), from proof or.elim H (assume Hpq : p ∧ q, have Hp : p, from and.elim_left Hpq, have Hq : q, from and.elim_right Hpq, show p ∧ (q ∨ r), from and.intro Hp (or.inl Hq)) (assume Hpr : p ∧ r, have Hp : p, from and.elim_left Hpr, have Hr : r, from and.elim_right Hpr, show p ∧ (q ∨ r), from and.intro Hp (or.inr Hr)) qed)
24f7dd4ad154fa2744258b78d382b24efdd2b1f1
9c2e8d73b5c5932ceb1333265f17febc6a2f0a39
/src/K/jump.lean
7e7ca12e65d4cdae038f3a850f839fcb7a671ac6
[ "MIT" ]
permissive
minchaowu/ModalTab
2150392108dfdcaffc620ff280a8b55fe13c187f
9bb0bf17faf0554d907ef7bdd639648742889178
refs/heads/master
1,626,266,863,244
1,592,056,874,000
1,592,056,874,000
153,314,364
12
1
null
null
null
null
UTF-8
Lean
false
false
3,640
lean
import .rules open psum nnf node set_option eqn_compiler.zeta true def tableau : Π Γ : list nnf, node Γ | Γ := match get_contra Γ with | inl w := contra_rule w.2 | inr no_contra := match get_and Γ with | inl p := let Δ := p.1.1 :: p.1.2 :: Γ.erase (nnf.and p.val.1 p.val.2) in let inst := and_instance.cons p.2 in have node_size ((p.val).fst :: (p.val).snd :: list.erase Γ (and ((p.val).fst) ((p.val).snd))) < node_size Γ, by apply split_lt_and; exact p.2, let d_delta : node Δ := tableau Δ in and_rule inst d_delta | inr no_and := match get_or Γ with | inl p := let Γ₁ := p.1.1 :: Γ.erase (nnf.or p.val.1 p.val.2) in let Γ₂ := p.1.2 :: Γ.erase (nnf.or p.val.1 p.val.2) in let inst := or_instance.cons p.2 in have node_size ((p.val).fst :: list.erase Γ (or ((p.val).fst) ((p.val).snd))) < node_size Γ, by apply split_lt_or_left; exact p.2, have node_size ((p.val).snd :: list.erase Γ (or ((p.val).fst) ((p.val).snd))) < node_size Γ, by apply split_lt_or_right; exact p.2, let d_Γ₁ : node (p.1.1 :: Γ.erase (or p.val.1 p.val.2)) := tableau Γ₁ in match d_Γ₁ with | closed m hsat pm := if hprcp : left_prcp inst ∈ m then or_rule inst (closed m hsat pm) (tableau Γ₂) else jump_rule inst m hsat pm hprcp | open_ w := open_rule inst w.2 end | inr no_or := match get_dia Γ with | inl p := let ma : modal_applicable Γ := {no_contra := no_contra, no_and := no_and, no_or := no_or, v := get_var Γ, hv := λ n, get_var_iff, φ := p.1, ex := p.2} in let l := @tmap (λ Δ, node_size Δ < node_size Γ) (λ x h, tableau x) (unmodal Γ) (unmodal_size Γ) in match l with | inl w := begin left, {exact unsat_of_unsat_unmodal ma w.1.1 ⟨w.2.1, w.2.2.1⟩}, swap, {exact mark_modal Γ w.1.1 w.1.2}, { exact modal_pmark ma w.1.1 w.1.2 ⟨w.2.1, w.2.2.1⟩ w.2.2.2 } end | inr w := begin right, split, apply sat_of_batch_sat, exact ma, exact w.2 end end | inr no_dia := let mc : model_constructible Γ := {no_contra := no_contra, no_and := no_and, no_or := no_or, v := get_var Γ, hv := λ n, get_var_iff, no_dia := no_dia} in by right; split; apply build_model; exact mc end end end end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf node_size⟩]} def is_sat (Γ : list nnf) : bool := match tableau Γ with | closed _ _ _:= ff | open_ _ := tt end theorem correctness (Γ : list nnf) : is_sat Γ = tt ↔ ∃ (st : Type) (k : kripke st) s, sat k s Γ := begin cases h : is_sat Γ, constructor, {intro, contradiction}, {intro hsat, cases eq : tableau Γ, rcases hsat with ⟨w, k, s, hsat⟩, apply false.elim, apply a, exact hsat, {dsimp [is_sat] at h, rw eq at h, contradiction} }, {split, intro, dsimp [is_sat] at h, cases eq : tableau Γ, { rw eq at h, contradiction }, { split, split, split, exact a_1.2}, { simp } } end /- The negation of the defining formula of K is unsatisfiable -/ def φ : nnf := and (box $ or (neg 1) (var 2)) (and (box $ var 1) (dia $ neg 2)) #eval is_sat [φ] def ψ : nnf := and (box (var 1)) (dia (dia (neg 1))) #eval is_sat [ψ]
c41e58e9b9dc2bba6093bfdb04b74e228375f743
bb31430994044506fa42fd667e2d556327e18dfe
/src/category_theory/idempotents/functor_extension.lean
2178e4be73b4c2c013dda820272123e5c4e9c5ee
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
10,990
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi /-! # Extension of functors to the idempotent completion In this file, we construct an extension `functor_extension₁` of functors `C ⥤ karoubi D` to functors `karoubi C ⥤ karoubi D`. This results in an equivalence `karoubi_universal₁ C D : (C ⥤ karoubi D) ≌ (karoubi C ⥤ karoubi D)`. We also construct an extension `functor_extension₂` of functors `(C ⥤ D) ⥤ (karoubi C ⥤ karoubi D)`. Moreover, when `D` is idempotent complete, we get equivalences `karoubi_universal₂ C D : C ⥤ D ≌ karoubi C ⥤ karoubi D` and `karoubi_universal C D : C ⥤ D ≌ karoubi C ⥤ D`. We occasionally state and use equalities of functors because it is sometimes convenient to use rewrites when proving properties of functors obtained using the constructions in this file. Users are encouraged to use the corresponding natural isomorphism whenever possible. -/ open category_theory.category open category_theory.idempotents.karoubi namespace category_theory namespace idempotents variables {C D E : Type*} [category C] [category D] [category E] /-- A natural transformation between functors `karoubi C ⥤ D` is determined by its value on objects coming from `C`. -/ lemma nat_trans_eq {F G : karoubi C ⥤ D} (φ : F ⟶ G) (P : karoubi C) : φ.app P = F.map (decomp_id_i P) ≫ φ.app P.X ≫ G.map (decomp_id_p P) := begin rw [← φ.naturality, ← assoc, ← F.map_comp], conv { to_lhs, rw [← id_comp (φ.app P), ← F.map_id], }, congr, apply decomp_id, end namespace functor_extension₁ /-- The canonical extension of a functor `C ⥤ karoubi D` to a functor `karoubi C ⥤ karoubi D` -/ @[simps] def obj (F : C ⥤ karoubi D) : karoubi C ⥤ karoubi D := { obj := λ P, ⟨(F.obj P.X).X, (F.map P.p).f, by simpa only [F.map_comp, hom_ext] using F.congr_map P.idem⟩, map := λ P Q f, ⟨(F.map f.f).f, by simpa only [F.map_comp, hom_ext] using F.congr_map f.comm⟩, } /-- Extension of a natural transformation `φ` between functors `C ⥤ karoubi D` to a natural transformation between the extension of these functors to `karoubi C ⥤ karoubi D` -/ @[simps] def map {F G : C ⥤ karoubi D} (φ : F ⟶ G) : obj F ⟶ obj G := { app := λ P, { f := (F.map P.p).f ≫ (φ.app P.X).f, comm := begin have h := φ.naturality P.p, have h' := F.congr_map P.idem, simp only [hom_ext, karoubi.comp_f, F.map_comp] at h h', simp only [obj_obj_p, assoc, ← h], slice_rhs 1 3 { rw [h', h'], }, end, }, naturality' := λ P Q f, begin ext, dsimp [obj], have h := φ.naturality f.f, have h' := F.congr_map (comp_p f), have h'' := F.congr_map (p_comp f), simp only [hom_ext, functor.map_comp, comp_f] at ⊢ h h' h'', slice_rhs 2 3 { rw ← h, }, slice_lhs 1 2 { rw h', }, slice_rhs 1 2 { rw h'', }, end } end functor_extension₁ variables (C D E) /-- The canonical functor `(C ⥤ karoubi D) ⥤ (karoubi C ⥤ karoubi D)` -/ @[simps] def functor_extension₁ : (C ⥤ karoubi D) ⥤ (karoubi C ⥤ karoubi D) := { obj := functor_extension₁.obj, map := λ F G, functor_extension₁.map, map_id' := λ F, by { ext P, exact comp_p (F.map P.p), }, map_comp' := λ F G H φ φ', begin ext P, simp only [comp_f, functor_extension₁.map_app_f, nat_trans.comp_app, assoc], have h := φ.naturality P.p, have h' := F.congr_map P.idem, simp only [hom_ext, comp_f, F.map_comp] at h h', slice_rhs 2 3 { rw ← h, }, slice_rhs 1 2 { rw h', }, simp only [assoc], end, } lemma functor_extension₁_comp_whiskering_left_to_karoubi : functor_extension₁ C D ⋙ (whiskering_left C (karoubi C) (karoubi D)).obj (to_karoubi C) = 𝟭 _ := begin refine functor.ext _ _, { intro F, refine functor.ext _ _, { intro X, ext, { dsimp, rw [id_comp, comp_id, F.map_id, id_eq], }, { refl, }, }, { intros X Y f, ext, dsimp, simp only [comp_id, eq_to_hom_f, eq_to_hom_refl, comp_p, functor_extension₁.obj_obj_p, to_karoubi_obj_p, comp_f], dsimp, simp only [functor.map_id, id_eq, p_comp], }, }, { intros F G φ, ext X, dsimp, simp only [eq_to_hom_app, F.map_id, comp_f, eq_to_hom_f, id_eq, p_comp, eq_to_hom_refl, comp_id, comp_p, functor_extension₁.obj_obj_p, to_karoubi_obj_p, F.map_id X], }, end /-- The natural isomorphism expressing that functors `karoubi C ⥤ karoubi D` obtained using `functor_extension₁` actually extends the original functors `C ⥤ karoubi D`. -/ @[simps] def functor_extension₁_comp_whiskering_left_to_karoubi_iso : functor_extension₁ C D ⋙ (whiskering_left C (karoubi C) (karoubi D)).obj (to_karoubi C) ≅ 𝟭 _ := eq_to_iso (functor_extension₁_comp_whiskering_left_to_karoubi C D) /-- The counit isomorphism of the equivalence `(C ⥤ karoubi D) ≌ (karoubi C ⥤ karoubi D)`. -/ @[simps] def karoubi_universal₁.counit_iso : (whiskering_left C (karoubi C) (karoubi D)).obj (to_karoubi C) ⋙ functor_extension₁ C D ≅ 𝟭 _ := nat_iso.of_components (λ G, { hom := { app := λ P, { f := (G.map (decomp_id_p P)).f, comm := by simpa only [hom_ext, G.map_comp, G.map_id] using G.congr_map (show P.decomp_id_p = (to_karoubi C).map P.p ≫ P.decomp_id_p ≫ 𝟙 _, by simp), }, naturality' := λ P Q f, by simpa only [hom_ext, G.map_comp] using (G.congr_map (decomp_id_p_naturality f)).symm, }, inv := { app := λ P, { f := (G.map (decomp_id_i P)).f, comm := by simpa only [hom_ext, G.map_comp, G.map_id] using G.congr_map (show P.decomp_id_i = 𝟙 _ ≫ P.decomp_id_i ≫ (to_karoubi C).map P.p, by simp), }, naturality' := λ P Q f, by simpa only [hom_ext, G.map_comp] using G.congr_map (decomp_id_i_naturality f), }, hom_inv_id' := begin ext P, simpa only [hom_ext, G.map_comp, G.map_id] using G.congr_map P.decomp_p.symm, end, inv_hom_id' := begin ext P, simpa only [hom_ext, G.map_comp, G.map_id] using G.congr_map P.decomp_id.symm, end, }) (λ G₁ G₂ φ, begin ext P, dsimp, simpa only [nat_trans_eq φ P, comp_f, functor_extension₁.map_app_f, functor.comp_map, whisker_left_app, assoc, P.decomp_p, G₁.map_comp], end) /-- The equivalence of categories `(C ⥤ karoubi D) ≌ (karoubi C ⥤ karoubi D)`. -/ @[simps] def karoubi_universal₁ : (C ⥤ karoubi D) ≌ (karoubi C ⥤ karoubi D) := { functor := functor_extension₁ C D, inverse := (whiskering_left C (karoubi C) (karoubi D)).obj (to_karoubi C), unit_iso := (functor_extension₁_comp_whiskering_left_to_karoubi_iso C D).symm, counit_iso := karoubi_universal₁.counit_iso C D, functor_unit_iso_comp' := λ F, begin ext P, dsimp [functor_extension₁.map, karoubi_universal₁.counit_iso], simpa only [comp_f, eq_to_hom_app, eq_to_hom_f, eq_to_hom_refl, comp_id, hom_ext, F.map_comp, comp_p] using F.congr_map P.idem, end, } lemma functor_extension₁_comp (F : C ⥤ karoubi D) (G : D ⥤ karoubi E) : (functor_extension₁ C E).obj (F ⋙ (functor_extension₁ D E).obj G) = (functor_extension₁ C D).obj F ⋙ (functor_extension₁ D E).obj G := functor.ext (by tidy) (λ X Y f, by { dsimp, simpa only [id_comp, comp_id], }) /-- The canonical functor `(C ⥤ D) ⥤ (karoubi C ⥤ karoubi D)` -/ @[simps] def functor_extension₂ : (C ⥤ D) ⥤ (karoubi C ⥤ karoubi D) := (whiskering_right C D (karoubi D)).obj (to_karoubi D) ⋙ functor_extension₁ C D lemma functor_extension₂_comp_whiskering_left_to_karoubi : functor_extension₂ C D ⋙ (whiskering_left C (karoubi C) (karoubi D)).obj (to_karoubi C) = (whiskering_right C D (karoubi D)).obj (to_karoubi D) := by simp only [functor_extension₂, functor.assoc, functor_extension₁_comp_whiskering_left_to_karoubi, functor.comp_id] /-- The natural isomorphism expressing that functors `karoubi C ⥤ karoubi D` obtained using `functor_extension₂` actually extends the original functors `C ⥤ D`. -/ @[simps] def functor_extension₂_comp_whiskering_left_to_karoubi_iso : functor_extension₂ C D ⋙ (whiskering_left C (karoubi C) (karoubi D)).obj (to_karoubi C) ≅ (whiskering_right C D (karoubi D)).obj (to_karoubi D) := eq_to_iso (functor_extension₂_comp_whiskering_left_to_karoubi C D) section is_idempotent_complete variable [is_idempotent_complete D] noncomputable instance : is_equivalence (to_karoubi D) := to_karoubi_is_equivalence D /-- The equivalence of categories `(C ⥤ D) ≌ (karoubi C ⥤ karoubi D)` when `D` is idempotent complete. -/ @[simps] noncomputable def karoubi_universal₂ : (C ⥤ D) ≌ (karoubi C ⥤ karoubi D) := (equivalence.congr_right (to_karoubi D).as_equivalence).trans (karoubi_universal₁ C D) lemma karoubi_universal₂_functor_eq : (karoubi_universal₂ C D).functor = functor_extension₂ C D := rfl noncomputable instance : is_equivalence (functor_extension₂ C D) := by { rw ← karoubi_universal₂_functor_eq, apply_instance, } /-- The extension of functors functor `(C ⥤ D) ⥤ (karoubi C ⥤ D)` when `D` is idempotent compltete. -/ @[simps] noncomputable def functor_extension : (C ⥤ D) ⥤ (karoubi C ⥤ D) := functor_extension₂ C D ⋙ (whiskering_right (karoubi C) (karoubi D) D).obj (to_karoubi_is_equivalence D).inverse /-- The equivalence `(C ⥤ D) ≌ (karoubi C ⥤ D)` when `D` is idempotent complete. -/ @[simps] noncomputable def karoubi_universal : (C ⥤ D) ≌ (karoubi C ⥤ D) := (karoubi_universal₂ C D).trans (equivalence.congr_right (to_karoubi D).as_equivalence.symm) lemma karoubi_universal_functor_eq : (karoubi_universal C D).functor = functor_extension C D := rfl noncomputable instance : is_equivalence (functor_extension C D) := by { rw ← karoubi_universal_functor_eq, apply_instance, } noncomputable instance : is_equivalence ((whiskering_left C (karoubi C) D).obj (to_karoubi C)) := is_equivalence.cancel_comp_right _ ((whiskering_right C _ _).obj (to_karoubi D) ⋙ (whiskering_right C _ _).obj (to_karoubi D).inv) (is_equivalence.of_equivalence (@equivalence.congr_right _ _ _ _ C _ ((to_karoubi D).as_equivalence.trans (to_karoubi D).as_equivalence.symm))) (by { change is_equivalence (karoubi_universal C D).inverse, apply_instance, }) variables {C D} lemma whiskering_left_obj_preimage_app {F G : karoubi C ⥤ D} (τ : to_karoubi _ ⋙ F ⟶ to_karoubi _ ⋙ G) (P : karoubi C) : (((whiskering_left _ _ _).obj (to_karoubi _)).preimage τ).app P = F.map P.decomp_id_i ≫ τ.app P.X ≫ G.map P.decomp_id_p := begin rw nat_trans_eq, congr' 2, exact congr_app (((whiskering_left _ _ _).obj (to_karoubi _)).image_preimage τ) P.X, end end is_idempotent_complete end idempotents end category_theory
e626842792f8bec6070030abf4d11454eb0e84e8
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/linear_algebra/finsupp_vector_space.lean
65184852f79a7d81672e8d17dc40de1242f814f7
[ "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
6,858
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `α →₀ β`. -/ import data.finsupp data.mv_polynomial linear_algebra.dimension noncomputable theory open lattice set linear_map submodule namespace finsupp section module variables {α : Type*} {β : Type*} {γ : Type*} variables [decidable_eq α] [decidable_eq β] [ring γ] [add_comm_group β] [module γ β] lemma linear_independent_single [decidable_eq γ] {φ : α → Type*} [∀ a, decidable_eq (φ a)] {f : Π α, φ α → β} (hf : ∀a, linear_independent γ (f a)) : linear_independent γ (λ ax : Σ a, φ a, single ax.1 (f ax.1 ax.2)) := begin apply @linear_independent_Union_finite γ _ _ _ _ _ _ α φ _ _ (λ a x, single a (f a x)), { assume a, have h_disjoint : disjoint (span γ (range (f a))) (ker (lsingle a)), { rw ker_lsingle, exact disjoint_bot_right }, apply linear_independent.image (hf a) h_disjoint }, { intros i t ht hit, apply disjoint_mono _ _ (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)), { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end end module section vector_space variables {α : Type*} {β : Type*} {γ : Type*} variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β] open linear_map submodule lemma is_basis_single {φ : α → Type*} [∀ a, decidable_eq (φ a)] (f : Π α, φ α → β) (hf : ∀a, is_basis γ (f a)) : is_basis γ (λ ax : Σ a, φ a, single ax.1 (f ax.1 ax.2)) := begin split, { apply linear_independent_single, exact λ a, (hf a).1 }, { rw [range_sigma_eq_Union_range, span_Union], simp only [image_univ.symm, λ i, image_comp (single i) (f i), span_single_image], simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] } end end vector_space section dim universes u v variables {α : Type u} {β : Type u} {γ : Type v} variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β] lemma dim_eq : vector_space.dim γ (α →₀ β) = cardinal.mk α * vector_space.dim γ β := begin rcases exists_is_basis γ β with ⟨bs, hbs⟩, rw [← cardinal.lift_inj, cardinal.lift_mul, ← hbs.mk_eq_dim, ← (is_basis_single _ (λa:α, hbs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (injective_single.{u u} _), cardinal.sum_const] } end end dim end finsupp section vector_space /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ universe variables u v w variables {α : Type u} {β γ : Type v} {β' : Type v} {γ' : Type w} variables [discrete_field α] variables [add_comm_group β] [vector_space α β] variables [add_comm_group γ] [vector_space α γ] variables [add_comm_group β'] [vector_space α β'] variables [add_comm_group γ'] [vector_space α γ'] open vector_space set_option class.instance_max_depth 70 lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{v w} (dim α β') = cardinal.lift.{w v} (dim α γ')) : nonempty (β' ≃ₗ[α] γ') := begin haveI := classical.dec_eq β', haveI := classical.dec_eq γ', rcases exists_is_basis α β' with ⟨b, hb⟩, rcases exists_is_basis α γ' with ⟨c, hc⟩, rw [←cardinal.lift_inj.1 hb.mk_eq_dim, ←cardinal.lift_inj.1 hc.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨((module_equiv_finsupp hb).trans (finsupp.dom_lcongr e)).trans (module_equiv_finsupp hc).symm⟩, end def equiv_of_dim_eq_dim (h : dim α β = dim α γ) : β ≃ₗ[α] γ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end lemma fin_dim_vectorspace_equiv (n : ℕ) (hn : (dim α β) = n) : β ≃ₗ[α] (fin n → α) := begin have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun α _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end lemma eq_bot_iff_dim_eq_zero (p : submodule α β) (h : dim α p = 0) : p = ⊥ := begin have : dim α p = dim α (⊥ : submodule α β) := by rwa [dim_bot], let e := equiv_of_dim_eq_dim this, exact e.eq_bot_of_equiv _ end lemma injective_of_surjective (f : β →ₗ[α] γ) (hβ : dim α β < cardinal.omega) (heq : dim α γ = dim α β) (hf : f.range = ⊤) : f.ker = ⊥ := have hk : dim α f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hβ, begin rcases cardinal.lt_omega.1 hβ with ⟨d₁, eq₁⟩, rcases cardinal.lt_omega.1 hk with ⟨d₂, eq₂⟩, have : 0 = d₂, { have := dim_eq_surjective f (linear_map.range_eq_top.1 hf), rw [heq, eq₁, eq₂, ← nat.cast_add, cardinal.nat_cast_inj] at this, exact nat.add_left_cancel this }, refine eq_bot_iff_dim_eq_zero _ _, rw [eq₂, ← this, nat.cast_zero] end end vector_space section vector_space universes u open vector_space set_option class.instance_max_depth 50 local attribute [instance] submodule.module set_option pp.universes false lemma cardinal_mk_eq_cardinal_mk_field_pow_dim {α β : Type u} [decidable_eq β] [discrete_field α] [add_comm_group β] [vector_space α β] (h : dim α β < cardinal.omega) : cardinal.mk β = cardinal.mk α ^ dim α β := begin rcases exists_is_basis α β with ⟨s, hs⟩, have : nonempty (fintype s), { rwa [← cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim] }, cases this with hsf, letI := hsf, calc cardinal.mk β = cardinal.mk (s →₀ α) : quotient.sound ⟨(module_equiv_finsupp hs).to_equiv⟩ ... = cardinal.mk (s → α) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_dim_lt_omega {α β : Type u} [decidable_eq β] [discrete_field α] [add_comm_group β] [vector_space α β] [fintype α] (h : dim α β < cardinal.omega) : cardinal.mk β < cardinal.omega := begin rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h], exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) h end end vector_space
21e40b6bda2ab12541260cc30e0e147062f071ea
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_geometry/locally_ringed_space.lean
10096613620f6b305153be7d31658bde1e8b7acf
[ "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
10,268
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebraic_geometry.ringed_space import algebraic_geometry.stalks import logic.equiv.transfer_instance /-! # The category of locally ringed spaces We define (bundled) locally ringed spaces (as `SheafedSpace CommRing` along with the fact that the stalks are local rings), and morphisms between these (morphisms in `SheafedSpace` with `is_local_ring_hom` on the stalk maps). -/ universes v u open category_theory open Top open topological_space open opposite open category_theory.category category_theory.functor namespace algebraic_geometry /-- A `LocallyRingedSpace` is a topological space equipped with a sheaf of commutative rings such that all the stalks are local rings. A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphisms induced on stalks are local ring homomorphisms. -/ @[nolint has_inhabited_instance] structure LocallyRingedSpace extends SheafedSpace CommRing := (local_ring : ∀ x, local_ring (presheaf.stalk x)) attribute [instance] LocallyRingedSpace.local_ring namespace LocallyRingedSpace variables (X : LocallyRingedSpace) /-- An alias for `to_SheafedSpace`, where the result type is a `RingedSpace`. This allows us to use dot-notation for the `RingedSpace` namespace. -/ def to_RingedSpace : RingedSpace := X.to_SheafedSpace /-- The underlying topological space of a locally ringed space. -/ def to_Top : Top := X.1.carrier instance : has_coe_to_sort LocallyRingedSpace (Type u) := ⟨λ X : LocallyRingedSpace, (X.to_Top : Type u)⟩ instance (x : X) : _root_.local_ring (X.to_PresheafedSpace.stalk x) := X.local_ring x -- PROJECT: how about a typeclass "has_structure_sheaf" to mediate the 𝒪 notation, rather -- than defining it over and over for PresheafedSpace, LRS, Scheme, etc. /-- The structure sheaf of a locally ringed space. -/ def 𝒪 : sheaf CommRing X.to_Top := X.to_SheafedSpace.sheaf /-- A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphims induced on stalks are local ring homomorphisms. -/ def hom (X Y : LocallyRingedSpace) : Type* := { f : X.to_SheafedSpace ⟶ Y.to_SheafedSpace // ∀ x, is_local_ring_hom (PresheafedSpace.stalk_map f x) } instance : quiver LocallyRingedSpace := ⟨hom⟩ @[ext] lemma hom_ext {X Y : LocallyRingedSpace} (f g : hom X Y) (w : f.1 = g.1) : f = g := subtype.eq w /-- The stalk of a locally ringed space, just as a `CommRing`. -/ -- TODO perhaps we should make a bundled `LocalRing` and return one here? -- TODO define `sheaf.stalk` so we can write `X.𝒪.stalk` here? noncomputable def stalk (X : LocallyRingedSpace) (x : X) : CommRing := X.presheaf.stalk x /-- A morphism of locally ringed spaces `f : X ⟶ Y` induces a local ring homomorphism from `Y.stalk (f x)` to `X.stalk x` for any `x : X`. -/ noncomputable def stalk_map {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : Y.stalk (f.1.1 x) ⟶ X.stalk x := PresheafedSpace.stalk_map f.1 x instance {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : is_local_ring_hom (stalk_map f x) := f.2 x instance {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : is_local_ring_hom (PresheafedSpace.stalk_map f.1 x) := f.2 x /-- The identity morphism on a locally ringed space. -/ @[simps] def id (X : LocallyRingedSpace) : hom X X := ⟨𝟙 _, λ x, by { erw PresheafedSpace.stalk_map.id, apply is_local_ring_hom_id, }⟩ instance (X : LocallyRingedSpace) : inhabited (hom X X) := ⟨id X⟩ /-- Composition of morphisms of locally ringed spaces. -/ @[simps] def comp {X Y Z : LocallyRingedSpace} (f : hom X Y) (g : hom Y Z) : hom X Z := ⟨f.val ≫ g.val, λ x, begin erw PresheafedSpace.stalk_map.comp, exact @is_local_ring_hom_comp _ _ _ _ _ _ _ _ (f.2 _) (g.2 _), end⟩ /-- The category of locally ringed spaces. -/ instance : category LocallyRingedSpace := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, comp_id' := by { intros, ext1, simp, }, id_comp' := by { intros, ext1, simp, }, assoc' := by { intros, ext1, simp, }, }. /-- The forgetful functor from `LocallyRingedSpace` to `SheafedSpace CommRing`. -/ @[simps] def forget_to_SheafedSpace : LocallyRingedSpace ⥤ SheafedSpace CommRing := { obj := λ X, X.to_SheafedSpace, map := λ X Y f, f.1, } instance : faithful forget_to_SheafedSpace := {} /-- The forgetful functor from `LocallyRingedSpace` to `Top`. -/ @[simps] def forget_to_Top : LocallyRingedSpace ⥤ Top := forget_to_SheafedSpace ⋙ SheafedSpace.forget _ @[simp] lemma comp_val {X Y Z : LocallyRingedSpace} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val = f.val ≫ g.val := rfl @[simp] lemma comp_val_c {X Y Z : LocallyRingedSpace} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val.c = g.val.c ≫ (presheaf.pushforward _ g.val.base).map f.val.c := rfl lemma comp_val_c_app {X Y Z : LocallyRingedSpace} (f : X ⟶ Y) (g : Y ⟶ Z) (U : (opens Z)ᵒᵖ) : (f ≫ g).val.c.app U = g.val.c.app U ≫ f.val.c.app (op $ (opens.map g.val.base).obj U.unop) := rfl /-- Given two locally ringed spaces `X` and `Y`, an isomorphism between `X` and `Y` as _sheafed_ spaces can be lifted to a morphism `X ⟶ Y` as locally ringed spaces. See also `iso_of_SheafedSpace_iso`. -/ @[simps] def hom_of_SheafedSpace_hom_of_is_iso {X Y : LocallyRingedSpace} (f : X.to_SheafedSpace ⟶ Y.to_SheafedSpace) [is_iso f] : X ⟶ Y := subtype.mk f $ λ x, -- Here we need to see that the stalk maps are really local ring homomorphisms. -- This can be solved by type class inference, because stalk maps of isomorphisms are isomorphisms -- and isomorphisms are local ring homomorphisms. show is_local_ring_hom (PresheafedSpace.stalk_map (SheafedSpace.forget_to_PresheafedSpace.map f) x), by apply_instance /-- Given two locally ringed spaces `X` and `Y`, an isomorphism between `X` and `Y` as _sheafed_ spaces can be lifted to an isomorphism `X ⟶ Y` as locally ringed spaces. This is related to the property that the functor `forget_to_SheafedSpace` reflects isomorphisms. In fact, it is slightly stronger as we do not require `f` to come from a morphism between _locally_ ringed spaces. -/ def iso_of_SheafedSpace_iso {X Y : LocallyRingedSpace} (f : X.to_SheafedSpace ≅ Y.to_SheafedSpace) : X ≅ Y := { hom := hom_of_SheafedSpace_hom_of_is_iso f.hom, inv := hom_of_SheafedSpace_hom_of_is_iso f.inv, hom_inv_id' := hom_ext _ _ f.hom_inv_id, inv_hom_id' := hom_ext _ _ f.inv_hom_id } instance : reflects_isomorphisms forget_to_SheafedSpace := { reflects := λ X Y f i, { out := by exactI ⟨hom_of_SheafedSpace_hom_of_is_iso (category_theory.inv (forget_to_SheafedSpace.map f)), hom_ext _ _ (is_iso.hom_inv_id _), hom_ext _ _ (is_iso.inv_hom_id _)⟩ } } instance is_SheafedSpace_iso {X Y : LocallyRingedSpace} (f : X ⟶ Y) [is_iso f] : is_iso f.1 := LocallyRingedSpace.forget_to_SheafedSpace.map_is_iso f /-- The restriction of a locally ringed space along an open embedding. -/ @[simps] def restrict {U : Top} (X : LocallyRingedSpace) {f : U ⟶ X.to_Top} (h : open_embedding f) : LocallyRingedSpace := { local_ring := begin intro x, dsimp at *, -- We show that the stalk of the restriction is isomorphic to the original stalk, apply @ring_equiv.local_ring _ _ _ (X.local_ring (f x)), exact (X.to_PresheafedSpace.restrict_stalk_iso h x).symm.CommRing_iso_to_ring_equiv, end, to_SheafedSpace := X.to_SheafedSpace.restrict h } /-- The canonical map from the restriction to the supspace. -/ def of_restrict {U : Top} (X : LocallyRingedSpace) {f : U ⟶ X.to_Top} (h : open_embedding f) : X.restrict h ⟶ X := ⟨X.to_PresheafedSpace.of_restrict h, λ x, infer_instance⟩ /-- The restriction of a locally ringed space `X` to the top subspace is isomorphic to `X` itself. -/ def restrict_top_iso (X : LocallyRingedSpace) : X.restrict (opens.open_embedding ⊤) ≅ X := @iso_of_SheafedSpace_iso (X.restrict (opens.open_embedding ⊤)) X X.to_SheafedSpace.restrict_top_iso /-- The global sections, notated Gamma. -/ def Γ : LocallyRingedSpaceᵒᵖ ⥤ CommRing := forget_to_SheafedSpace.op ⋙ SheafedSpace.Γ lemma Γ_def : Γ = forget_to_SheafedSpace.op ⋙ SheafedSpace.Γ := rfl @[simp] lemma Γ_obj (X : LocallyRingedSpaceᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl lemma Γ_obj_op (X : LocallyRingedSpace) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl @[simp] lemma Γ_map {X Y : LocallyRingedSpaceᵒᵖ} (f : X ⟶ Y) : Γ.map f = f.unop.1.c.app (op ⊤) := rfl lemma Γ_map_op {X Y : LocallyRingedSpace} (f : X ⟶ Y) : Γ.map f.op = f.1.c.app (op ⊤) := rfl lemma preimage_basic_open {X Y : LocallyRingedSpace} (f : X ⟶ Y) {U : opens Y} (s : Y.presheaf.obj (op U)) : (opens.map f.1.base).obj (Y.to_RingedSpace.basic_open s) = @RingedSpace.basic_open X.to_RingedSpace ((opens.map f.1.base).obj U) (f.1.c.app _ s) := begin ext, split, { rintros ⟨⟨y, hyU⟩, (hy : is_unit _), (rfl : y = _)⟩, erw RingedSpace.mem_basic_open _ _ ⟨x, show x ∈ (opens.map f.1.base).obj U, from hyU⟩, rw ← PresheafedSpace.stalk_map_germ_apply, exact (PresheafedSpace.stalk_map f.1 _).is_unit_map hy }, { rintros ⟨y, (hy : is_unit _), rfl⟩, erw RingedSpace.mem_basic_open _ _ ⟨f.1.base y.1, y.2⟩, rw ← PresheafedSpace.stalk_map_germ_apply at hy, exact (is_unit_map_iff (PresheafedSpace.stalk_map f.1 _) _).mp hy } end -- This actually holds for all ringed spaces with nontrivial stalks. @[simp] lemma basic_open_zero (X : LocallyRingedSpace) (U : opens X.carrier) : X.to_RingedSpace.basic_open (0 : X.presheaf.obj $ op U) = ∅ := begin ext, simp only [set.mem_empty_eq, topological_space.opens.empty_eq, topological_space.opens.mem_coe, opens.coe_bot, iff_false, RingedSpace.basic_open, is_unit_zero_iff, set.mem_set_of_eq, map_zero], rintro ⟨⟨y, _⟩, h, e⟩, exact @zero_ne_one (X.presheaf.stalk y) _ _ h, end instance component_nontrivial (X : LocallyRingedSpace) (U : opens X.carrier) [hU : nonempty U] : nontrivial (X.presheaf.obj $ op U) := (X.to_PresheafedSpace.presheaf.germ hU.some).domain_nontrivial end LocallyRingedSpace end algebraic_geometry
9701775616180b85ad432cc137a1d32561f0ff11
5b0c53e5aaa0e60538d10f6b619a464aaf463815
/ch7.hlean
163f925b3908755647af95b05fb63cbc6ba2cb7f
[ "Apache-2.0" ]
permissive
bbentzen/hott-book-in-lean
f845a19ef09d48d2fb813624b4650d5832a47e10
9e262e633e653280b9cde5d287631fcec8501f64
refs/heads/master
1,586,430,679,994
1,519,975,089,000
1,519,975,089,000
50,330,220
1
0
null
null
null
null
UTF-8
Lean
false
false
3,482
hlean
/- Copyright (c) 2017 Bruno Bentzen. All rights reserved. Released under the Apache License 2.0 (see "License"); Theorems and exercises of the HoTT book (Chapter 7) -/ import .ch2 .ch3 .ch4 open eq prod unit bool sum sigma ua funext nat lift decidable /- ************************************** -/ /- Ch.7 Homotopy n-Types -/ /- ************************************** -/ variables {A B C : Type} universe variables i j /- §7.1 (Definition of n-Types) -/ inductive neg_two_int : Type := | neg_two : neg_two_int | succ : neg_two_int → neg_two_int open neg_two_int notation `ℤ₋₂` := neg_two_int notation `-2` := neg_two notation `-1` := succ neg_two notation `-0` := succ (succ neg_two) definition is_type : Π (n : ℤ₋₂) (X : Type), Type | is_type -2 X := isContr X | is_type (succ k) X := Π (x y : X), is_type k (x = y) -- Example 7.1.3 definition is_neg_1_type_eq_isProp (X : Type) : is_type -1 X = isProp X := ua (prop_eqv (pi_preserves_prop (λ x, pi_preserves_prop (λ y, isContr_is_prop (x = y)))) (isProp_is_prop X) (pr2 (prop_iff_contr_path X)) (pr1 (prop_iff_contr_path X))) definition is_0_type_eq_isSet (X : Type) : is_type -0 X = isSet X := ua (pi_preserves_equiv (λ (x : X), pi_preserves_equiv (λ (y : X), (idtoeqv (is_neg_1_type_eq_isProp (x = y) ))))) -- /- §7.2 (Uniqueness of identity proofs and Hedberg's theorem) -/ -- Theorem 7.2.5 (Hedberg Theorem) -- This proof is based on Alan Schmitt's coq proof (https://sympa.inria.fr/sympa/arc/coq-club/2016-09/msg00064.html) -- If a type has decidable equality, one can define a "collapsing" function (x = y) → (x = y) ... definition collapse {x y : A} (H : decidable_eq A) : (x = y) → (x = y) := λ p, sum.rec_on (H x y) (λ Heq, Heq) (λ Hne, empty.rec_on _ (Hne p)) -- ...such that `collapse p = colapse q` holds for any p q : x = y definition collapses_eq {x y : A} (H : decidable_eq A) (p q : x = y) : collapse H p = collapse H q := begin unfold collapse, cases (H x y) with Heq Hne, reflexivity, induction (Hne p) end -- Moreover, any p : x = y can be rewritten in terms of collapse definition rewrite_collapse {x y : A} (H : decidable_eq A) (p : x = y) : (collapse H (refl x))⁻¹ ⬝ (collapse H p) = p := eq.rec_on p (left_inv _) -- now we just need to rewrite p and q in terms of collapse and left-whisker `collapses_eq` to show that p = q definition UIP {x y : A} (H : decidable_eq A) (p q : x = y) : p = q := (rewrite_collapse H p)⁻¹ ⬝ l_whisker _ (collapses_eq H p q) ⬝ (rewrite_collapse H q) -- Theorem 7.2.6 definition neq_succ {n : ℕ} : ¬ (n = succ n) := by intro H; induction n with n IH; exact (empty.rec _ (down (nat.no_confusion H))); exact (IH (ap pred H)) definition nat_deceq (n m: ℕ) : (n = m) + ¬(n = m) := begin revert m, induction n with n IHn, { intro m, induction m with m IHm, exact (inl (refl 0)), cases IHm with H₁ H₂, exact (inr (λ H, empty.rec _ (down (nat.no_confusion (H ⬝ (ap succ H₁)⁻¹))) )), exact (inr (λ H, H₂ (ap pred H))) }, { intro m, induction m with m IHm, cases (IHn 0) with H₁, exact (inr (λ H, empty.rec _ (neq_succ (H⁻¹ ⬝ (ap succ H₁))) )), exact (inr (λ H, empty.rec _ (down (nat.no_confusion H )))), cases (IHn m) with H₁ H₂, exact (inl (ap succ H₁)), exact (inr (λ H, H₂ (ap pred H) )) } end
640962fceca4703f0c0507456a610aec959c010c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/letArrowOutsideDo.lean
71ce43654c806ab99df19fbd2bad14faa1831f1c
[ "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
63
lean
def myFun (n : Nat) : IO Nat := let q ← (10 : Nat) n + q
1188ee7b01a7b45476cbb59074cba222de19b9fd
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Compiler.lean
80de3ba550bfc080618b30b14e740a19cc083a4c
[ "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
489
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.InlineAttrs import Lean.Compiler.Specialize import Lean.Compiler.ConstFolding import Lean.Compiler.ClosedTermCache import Lean.Compiler.ExternAttr import Lean.Compiler.ImplementedByAttr import Lean.Compiler.NeverExtractAttr import Lean.Compiler.IR import Lean.Compiler.CSimpAttr import Lean.Compiler.FFI
0d4c45e0a43aaf3032972354aa8ee65bf812db4f
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/nat/factorial.lean
83445004a8c0b9a220f1d400b2d2628214d59135
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,141
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn -/ import data.nat.basic /-! # The factorial function -/ namespace nat variables {m n : ℕ} /-- `nat.factorial n` is the factorial of `n`. -/ @[simp] def factorial : nat → nat | 0 := 1 | (succ n) := succ n * factorial n localized "notation n `!`:10000 := nat.factorial n" in nat @[simp] theorem factorial_zero : 0! = 1! := rfl @[simp] theorem factorial_succ (n : ℕ) : n.succ! = succ n * n! := rfl @[simp] theorem factorial_one : 1! = 1 := rfl theorem factorial_pos : ∀ n, 0 < n! | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (factorial_pos n) theorem factorial_ne_zero (n : ℕ) : n! ≠ 0 := ne_of_gt (factorial_pos _) theorem factorial_dvd_factorial {m n} (h : m ≤ n) : m! ∣ n! := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_factorial : ∀ {m n}, 0 < m → m ≤ n → m ∣ n! | (succ m) n _ h := dvd_of_mul_right_dvd (factorial_dvd_factorial h) theorem factorial_le {m n} (h : m ≤ n) : m! ≤ n! := le_of_dvd (factorial_pos _) (factorial_dvd_factorial h) lemma factorial_mul_pow_le_factorial : ∀ {m n : ℕ}, m! * m.succ ^ n ≤ (m + n)! | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.factorial_succ, mul_comm (nat.succ _), pow_succ', ← mul_assoc]; exact mul_le_mul factorial_mul_pow_le_factorial (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_factorial : monotone factorial := λ n m, factorial_le lemma factorial_lt (h0 : 0 < n) : n! < m! ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (factorial_le hmn) }, { have : ∀(n : ℕ), 0 < n → n! < n.succ!, { intros k hk, rw [factorial_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (factorial_pos k) }, induction h generalizing h0, { exact this _ h0, }, { refine lt_trans (h_ih h0) (this _ _), exact lt_trans h0 (lt_of_succ_le h_a) }} end lemma one_lt_factorial : 1 < n! ↔ 1 < n := by { convert factorial_lt _, refl, exact one_pos } lemma factorial_eq_one : n! = 1 ↔ n ≤ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_factorial, h], apply lt_irrefl }, { cases h with h h, refl, cases h, refl } end lemma factorial_inj (h0 : 1 < n!) : n! = m! ↔ n = m := begin split; intro h, { rcases lt_trichotomy n m with hnm|hnm|hnm, { exfalso, rw [← factorial_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_factorial] at h0, exact lt_trans one_pos h0 }, { exact hnm }, { exfalso, rw [← factorial_lt, h] at hnm, exact lt_irrefl _ hnm, rw [h, one_lt_factorial] at h0, exact lt_trans one_pos h0 }}, { rw h } end lemma self_le_factorial : ∀ n : ℕ, n ≤ n! | 0 := zero_le_one | (k+1) := le_mul_of_one_le_right k.zero_lt_succ.le (nat.one_le_of_lt $ nat.factorial_pos _) end nat
e1e9d1770a94331aca089d055c947c6d32679f1b
5bf112cf7101c6c6303dc3fd0b3179c860e61e56
/lean/problems/default.lean
945b79881f786cf14e6bdeda633ce75a4fe44d34
[ "Apache-2.0" ]
permissive
fredfeng/formal-encoding
7ab645f49a553dfad2af03fcb4289e40fc679759
024efcf58672ac6b817caa10dfe8cd9708b07f1b
refs/heads/master
1,597,236,551,123
1,568,832,149,000
1,568,832,149,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36
lean
import problems.algebra.imo_2018_sl
80cd59754e7576d7b04f59a8c124fd3216600505
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/cpi/concretion/pseudo_apply.lean
848dd479e561c73bc6670550e5590301e96a4063
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
26,630
lean
import data.cpi.concretion.congruence namespace cpi namespace concretion variables {ℍ : Type} {ω : context} /-- An alternative measure, simply computes the depth of a term, and thus is preserved over renames. -/ private def depth : ∀ {Γ} {b y}, concretion ℍ ω Γ b y → ℕ | _ _ _ (#(_; _) _) := 1 | _ _ _ (F |₁ _) := depth F + 1 | _ _ _ (_ |₂ F) := depth F + 1 | _ _ _ (ν'(M) F) := depth F + 1 private theorem depth.over_rename : ∀ {Γ Δ} {b y} (ρ : name Γ → name Δ) (F : concretion ℍ ω Γ b y) , depth F = depth (rename ρ F) | Γ Δ b y ρ (#(_; _) _) := by unfold rename depth | Γ Δ b y ρ (F |₁ A) := by { unfold rename depth, rw depth.over_rename ρ F } | Γ Δ b y ρ (A |₂ F) := by { unfold rename depth, rw depth.over_rename ρ F } | Γ Δ b y ρ (ν'(M) F) := by { unfold rename depth, rw depth.over_rename (name.ext ρ) F } /-- Helper function for doign the actual application. This is split up to make the totality of pseudo_apply/pseudo_apply_app easier to determine. -/ private def pseudo_apply_app {a b} : ∀ {Γ}, vector (name Γ) a → species ℍ ω (context.extend b Γ) → concretion ℍ ω Γ b a → species ℍ ω Γ | Γ as A (#(bs; y) B) := species.rename (name.mk_apply bs) A |ₛ species.rename (name.mk_apply as) B | Γ as A (F |₁ B) := pseudo_apply_app as A F |ₛ B | Γ as A (B |₂ F) := B |ₛ pseudo_apply_app as A F | Γ as A (ν'(M) F) := ν(M) (pseudo_apply_app (vector.map name.extend as) (species.rename (name.ext name.extend) A) F) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, concretion.sizeof ℍ ω x.fst b a x.snd.snd.snd ) ⟩ ], dec_tac := tactic.fst_dec_tac, } /-- Apply two concretions together. -/ def pseudo_apply {a b} : ∀ {Γ}, concretion ℍ ω Γ a b → concretion ℍ ω Γ b a → species ℍ ω Γ | Γ (#(bs; y) A) F' := pseudo_apply_app bs A F' | Γ (F |₁ A) F' := pseudo_apply F F' |ₛ A | Γ (A |₂ F) F' := A |ₛ pseudo_apply F F' | Γ (ν'(M) F) F' := ν(M) (pseudo_apply F (rename name.extend F')) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, concretion.sizeof ℍ ω x.fst a b x.snd.fst ) ⟩ ], dec_tac := tactic.fst_dec_tac, } open species.equiv (hiding trans symm refl) open_locale congruence protected lemma pseudo_apply.on_parallel₁ : ∀ {Γ} {a b} (F : concretion ℍ ω Γ a b) (G : concretion ℍ ω Γ b a) (A : species ℍ ω Γ) , pseudo_apply F (G |₁ A) ≈ (pseudo_apply F G |ₛ A) | Γ a b (#(bs; y) A) G B := by unfold pseudo_apply pseudo_apply_app | Γ a b (F |₁ B) G A := begin unfold pseudo_apply, calc (pseudo_apply F (G |₁ A) |ₛ B) ≈ ((pseudo_apply F G |ₛ A) |ₛ B) : ξ_parallel₁ (pseudo_apply.on_parallel₁ F G A) ... ≈ ((pseudo_apply F G |ₛ B) |ₛ A) : parallel_symm₂ end | Γ a b (B |₂ F) G A := begin unfold pseudo_apply, calc (B |ₛ pseudo_apply F (G |₁ A)) ≈ (B |ₛ pseudo_apply F G |ₛ A) : ξ_parallel₂ (pseudo_apply.on_parallel₁ F G A) ... ≈ ((B |ₛ pseudo_apply F G) |ₛ A) : parallel_assoc₂ end | Γ a b (ν'(M) F) G A := begin unfold pseudo_apply rename, calc (ν(M) pseudo_apply F (rename name.extend G |₁ species.rename name.extend A)) ≈ (ν(M) pseudo_apply F (rename name.extend G) |ₛ species.rename name.extend A) : ξ_restriction M (pseudo_apply.on_parallel₁ F _ _) ... ≈ ((ν(M) pseudo_apply F (rename name.extend G)) |ₛ A) : ν_parallel' M end protected lemma pseudo_apply.on_parallel₂ : ∀ {Γ} {a b} (F : concretion ℍ ω Γ a b) (A : species ℍ ω Γ) (G : concretion ℍ ω Γ b a) , pseudo_apply F (A |₂ G) ≈ (A |ₛ pseudo_apply F G) | Γ a b (#(bs; y) A) B F := by unfold pseudo_apply pseudo_apply_app | Γ a b (F |₁ B) A G := begin unfold pseudo_apply, calc (pseudo_apply F (A |₂ G) |ₛ B) ≈ ((A |ₛ pseudo_apply F G) |ₛ B) : ξ_parallel₁ (pseudo_apply.on_parallel₂ F A G) ... ≈ (A |ₛ pseudo_apply F G |ₛ B) : parallel_assoc₁ end | Γ a b (B |₂ F) A G := begin unfold pseudo_apply, calc (B |ₛ pseudo_apply F (A |₂ G)) ≈ (B |ₛ A |ₛ pseudo_apply F G) : ξ_parallel₂ (pseudo_apply.on_parallel₂ F A G) ... ≈ (A |ₛ B |ₛ pseudo_apply F G) : parallel_symm₁ end | Γ a b (ν'(M) F) A G := begin unfold pseudo_apply rename, calc (ν(M) pseudo_apply F (species.rename name.extend A |₂ rename name.extend G)) ≈ (ν(M) species.rename name.extend A |ₛ pseudo_apply F (rename name.extend G)) : ξ_restriction M (pseudo_apply.on_parallel₂ F _ _) ... ≈ (A |ₛ ν(M) pseudo_apply F (rename name.extend G)) : ν_parallel₁ M end -- TODO: Clean up to use calc -- TODO: Use induction - does this allow us to drop the explicit termination -- checks? private lemma pseudo_apply_app.rename {a b} : ∀ {Γ Δ} (ρ : name Γ → name Δ) (as : vector (name Γ) a) (A : species ℍ ω (context.extend b Γ)) (F : concretion ℍ ω Γ b a) , species.rename ρ (pseudo_apply_app as A F) = pseudo_apply_app (vector.map ρ as) (species.rename (name.ext ρ) A) (rename ρ F) | Γ Δ ρ as A (#(bs; y) B) := begin unfold pseudo_apply_app rename, simp [species.rename_compose, name.mk_apply_rename] end | Γ Δ ρ bs A (F |₁ B) := begin unfold pseudo_apply_app rename, simp [pseudo_apply_app.rename ρ bs A F] end | Γ Δ ρ bs A (B |₂ F) := begin unfold pseudo_apply_app rename, simp [pseudo_apply_app.rename ρ bs A F] end | Γ Δ ρ ⟨ bs, n ⟩ A (ν'(M) G) := begin unfold pseudo_apply_app rename, simp, have map : vector.map (@name.extend _ M.arity) (vector.map ρ ⟨bs, n⟩) = vector.map (name.ext ρ) (vector.map name.extend ⟨bs, n⟩), unfold vector.map, simp, rw ← name.ext_extend ρ, rw map, have spc : species.rename (name.ext (@name.extend _ M.arity)) (species.rename (name.ext ρ) A) = species.rename (name.ext (name.ext ρ)) (species.rename (name.ext name.extend) A), rw [species.rename_compose, species.rename_compose], rw [name.ext_comp, name.ext_comp], rw name.ext_extend ρ, rw spc, from pseudo_apply_app.rename (name.ext ρ) _ _ G, end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, concretion.sizeof ℍ ω x.fst b a x.snd.snd.snd.snd.snd ) ⟩ ], dec_tac := tactic.fst_dec_tac, } protected lemma pseudo_apply.rename {a b} : ∀ {Γ Δ} (ρ : name Γ → name Δ) (F : concretion ℍ ω Γ a b) (G : concretion ℍ ω Γ b a) , species.rename ρ (pseudo_apply F G) = pseudo_apply (rename ρ F) (rename ρ G) | Γ Δ ρ (#(bs; y) A) G := begin unfold pseudo_apply rename, from pseudo_apply_app.rename ρ bs A G end | Γ Δ ρ (F |₁ A) G := begin unfold pseudo_apply rename, simp [pseudo_apply.rename ρ F G] end | Γ Δ ρ (A |₂ F) G := begin unfold pseudo_apply rename, simp [pseudo_apply.rename ρ F G] end | Γ Δ ρ (ν'(M) F) G := begin unfold pseudo_apply rename, simp, -- -- TODO: Clean up to use calc rw rename_compose, rw ← name.ext_extend, rw ← rename_compose name.extend, rw pseudo_apply.rename (name.ext ρ) F _, end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, concretion.sizeof ℍ ω x.fst a b x.snd.snd.snd.fst ) ⟩ ], dec_tac := tactic.fst_dec_tac, } private lemma pseudo_apply.restriction_swap {a b}: ∀ {Γ} (M N : affinity ℍ) (F : concretion ℍ ω (context.extend N.arity Γ) a b) (G : concretion ℍ ω (context.extend M.arity Γ) b a) , (ν(N) ν(M) pseudo_apply (rename name.extend F) (rename (name.ext name.extend) G)) ≈ ν(M) ν(N) pseudo_apply (rename (name.ext name.extend) F) (rename name.extend G) | Γ M N F G := calc (ν(N) ν(M) pseudo_apply (rename name.extend F) (rename (name.ext name.extend) G)) ≈ (ν(M) ν(N) species.rename name.swap (pseudo_apply (rename name.extend F) (rename (name.ext name.extend) G))) : ν_swap₁ N M ... ≈ (ν(M) ν(N) (pseudo_apply (rename name.swap (rename name.extend F)) (rename name.swap (rename (name.ext name.extend) G)))) : by rw pseudo_apply.rename ... ≈ (ν(M) ν(N) (pseudo_apply (rename (name.swap ∘ name.extend) F) (rename (name.swap ∘ name.ext name.extend) G))) : by rw [rename_compose, rename_compose] ... ≈ ν(M) ν(N) pseudo_apply (rename (name.ext name.extend) F) (rename name.extend G) : by rw [name.swap_comp_extend, name.swap_comp_ext_extend] lemma pseudo_apply.on_restriction : ∀ {Γ} {a b} (F : concretion ℍ ω Γ a b) (M : affinity ℍ) (G : concretion ℍ ω (context.extend M.arity Γ) b a) , pseudo_apply F (ν'(M) G) ≈ ν(M) (pseudo_apply (rename name.extend F) G) | Γ a b (#(bs; y) A) M G := by unfold pseudo_apply pseudo_apply_app rename | Γ a b (F |₁ A) M G := begin unfold pseudo_apply rename, calc (pseudo_apply F (ν'(M) G) |ₛ A) ≈ ((ν(M) pseudo_apply (rename name.extend F) G) |ₛ A) : ξ_parallel₁ (pseudo_apply.on_restriction F M G) ... ≈ ν(M) pseudo_apply (rename name.extend F) G |ₛ species.rename name.extend A : symm (ν_parallel' M), end | Γ a b (A |₂ F) M G := begin unfold pseudo_apply rename, calc (A |ₛ pseudo_apply F (ν'(M) G)) ≈ (A |ₛ ν(M) pseudo_apply (rename name.extend F) G) : ξ_parallel₂ (pseudo_apply.on_restriction F M G) ... ≈ ν(M) species.rename name.extend A |ₛ pseudo_apply (rename name.extend F) G : ν_parallel₂ M, end | Γ a b (ν'(N) F) M G := begin unfold pseudo_apply rename, calc (ν(N) pseudo_apply F (ν'(M) rename (name.ext name.extend) G)) ≈ (ν(N) ν(M) pseudo_apply (rename name.extend F) (rename (name.ext name.extend) G)) : ξ_restriction N (pseudo_apply.on_restriction F M _) ... ≈ ν(M) ν(N) pseudo_apply (rename (name.ext name.extend) F) (rename name.extend G) : pseudo_apply.restriction_swap M N F G end private theorem pseudo_apply_app.symm {a b} : ∀ {Γ} (bs : vector (name Γ) a) (A : species ℍ ω (context.extend b Γ)) (G : concretion ℍ ω Γ b a) , pseudo_apply_app bs A G ≈ pseudo_apply G (#(bs; b) A) := begin intros Γ as A G, induction G, case apply : Γ' b' bs y A { unfold pseudo_apply pseudo_apply_app, from parallel_symm }, case parallel₁ : Γ' b' y F A ih { unfold pseudo_apply pseudo_apply_app, from ξ_parallel₁ (ih _ _) }, case parallel₂ : Γ' b' y A F ih { unfold pseudo_apply pseudo_apply_app, from ξ_parallel₂ (ih _ _) }, case restriction : Γ' b' y M F ih { unfold pseudo_apply pseudo_apply_app, from ξ_restriction M (ih _ _) } end theorem pseudo_apply.symm {a b} : ∀ {Γ} (F : concretion ℍ ω Γ a b) (G : concretion ℍ ω Γ b a) , pseudo_apply F G ≈ pseudo_apply G F | Γ (#(as; x) A) G := begin unfold pseudo_apply, from pseudo_apply_app.symm as A G end | Γ (F |₁ A) (#(bs; y) B) := begin unfold pseudo_apply pseudo_apply_app, from ξ_parallel₁ (symm (pseudo_apply_app.symm bs B F)), end | Γ (F |₁ A) (G |₁ B) := begin unfold pseudo_apply, calc (pseudo_apply F (G |₁ B) |ₛ A) ≈ ((pseudo_apply F G |ₛ B) |ₛ A) : ξ_parallel₁ (pseudo_apply.on_parallel₁ F G B) ... ≈ ((pseudo_apply G F |ₛ B) |ₛ A) : ξ_parallel₁ (ξ_parallel₁ (pseudo_apply.symm F G)) ... ≈ ((pseudo_apply G F |ₛ A) |ₛ B) : parallel_symm₂ ... ≈ (pseudo_apply G (F |₁ A) |ₛ B) : ξ_parallel₁ (symm (pseudo_apply.on_parallel₁ G F A)) end | Γ (F |₁ A) (B |₂ G) := begin unfold pseudo_apply, calc (pseudo_apply F (B |₂ G) |ₛ A) ≈ ((B |ₛ pseudo_apply F G) |ₛ A) : ξ_parallel₁ (pseudo_apply.on_parallel₂ F B G) ... ≈ (B |ₛ pseudo_apply F G |ₛ A) : parallel_assoc₁ ... ≈ (B |ₛ pseudo_apply G F |ₛ A) : ξ_parallel₂ (ξ_parallel₁ (pseudo_apply.symm F G)) ... ≈ (B |ₛ pseudo_apply G (F |₁ A)) : ξ_parallel₂ (symm (pseudo_apply.on_parallel₁ G F A)) end | Γ (F |₁ A) (ν'(M) G) := begin unfold pseudo_apply rename, calc (pseudo_apply F (ν'(M) G) |ₛ A) ≈ ((ν(M) pseudo_apply (rename name.extend F) G) |ₛ A) : ξ_parallel₁ (pseudo_apply.on_restriction F M G) ... ≈ ((ν(M) pseudo_apply G (rename name.extend F)) |ₛ A) : ξ_parallel₁ (ξ_restriction M (pseudo_apply.symm _ G)) ... ≈ (ν(M) (pseudo_apply G (rename name.extend F)) |ₛ species.rename name.extend A) : symm (ν_parallel' M) ... ≈ ν(M) pseudo_apply G (rename name.extend F |₁ species.rename name.extend A) : ξ_restriction M (symm (pseudo_apply.on_parallel₁ G _ _)) end | Γ (A |₂ F) (#(bs; y) B) := begin unfold pseudo_apply pseudo_apply_app, from ξ_parallel₂ (symm (pseudo_apply_app.symm bs B F)), end | Γ (A |₂ F) (G |₁ B) := begin unfold pseudo_apply, calc (A |ₛ pseudo_apply F (G |₁ B)) ≈ (A |ₛ pseudo_apply F G |ₛ B) : ξ_parallel₂ (pseudo_apply.on_parallel₁ F G B) ... ≈ (A |ₛ pseudo_apply G F |ₛ B) : ξ_parallel₂ (ξ_parallel₁ (pseudo_apply.symm F G)) ... ≈ ((A |ₛ pseudo_apply G F) |ₛ B) : parallel_assoc₂ ... ≈ (pseudo_apply G (A |₂ F) |ₛ B) : ξ_parallel₁ (symm (pseudo_apply.on_parallel₂ G A F)) end | Γ (A |₂ F) (B |₂ G) := begin unfold pseudo_apply, calc (A |ₛ pseudo_apply F (B |₂ G)) ≈ (A |ₛ B |ₛ pseudo_apply F G) : ξ_parallel₂ (pseudo_apply.on_parallel₂ F B G) ... ≈ (B |ₛ A |ₛ pseudo_apply F G) : parallel_symm₁ ... ≈ (B |ₛ A |ₛ pseudo_apply G F) : ξ_parallel₂ (ξ_parallel₂ (pseudo_apply.symm F G)) ... ≈ (B |ₛ pseudo_apply G (A |₂ F)) : ξ_parallel₂ (symm (pseudo_apply.on_parallel₂ G A F)) end | Γ (A |₂ F) (ν'(M) G) := begin unfold pseudo_apply rename, calc (A |ₛ pseudo_apply F (ν'(M) G)) ≈ (A |ₛ ν(M) pseudo_apply (rename name.extend F) G) : ξ_parallel₂ (pseudo_apply.on_restriction F M G) ... ≈ ν(M) species.rename name.extend A |ₛ pseudo_apply (rename name.extend F) G : ν_parallel₂ M ... ≈ ν(M) species.rename name.extend A |ₛ pseudo_apply G (rename name.extend F) : ξ_restriction M (ξ_parallel₂ (pseudo_apply.symm _ G)) ... ≈ ν(M) pseudo_apply G (species.rename name.extend A |₂ rename name.extend F) : ξ_restriction M (symm (pseudo_apply.on_parallel₂ G _ _)) end | Γ (ν'(M) F) (#(bs; y) B) := begin unfold pseudo_apply pseudo_apply_app, from ξ_restriction M (symm (pseudo_apply_app.symm _ _ F)), end | Γ (ν'(M) F) (G |₁ B) := let h : depth (rename (@name.extend Γ M.arity) G) < depth G + 1 := begin rw ← depth.over_rename name.extend G, from nat.lt_add_of_pos_right nat.zero_lt_one end in begin unfold pseudo_apply rename, calc (ν(M) pseudo_apply F (rename name.extend G |₁ species.rename name.extend B)) ≈ (ν(M) pseudo_apply F (rename name.extend G) |ₛ species.rename name.extend B) : ξ_restriction M (pseudo_apply.on_parallel₁ F _ _) ... ≈ ((ν(M) pseudo_apply F (rename name.extend G)) |ₛ B) : ν_parallel' M ... ≈ ((ν(M) pseudo_apply (rename name.extend G) F) |ₛ B) : ξ_parallel₁ (ξ_restriction M (pseudo_apply.symm F (rename name.extend G))) ... ≈ (pseudo_apply G (ν'(M) F) |ₛ B) : ξ_parallel₁ (symm (pseudo_apply.on_restriction G M F)) end | Γ (ν'(M) F) (B |₂ G) := let h : depth (rename (@name.extend Γ M.arity) G) < depth G + 1 := begin rw ← depth.over_rename name.extend G, from nat.lt_add_of_pos_right nat.zero_lt_one end in begin unfold pseudo_apply rename, calc (ν(M) pseudo_apply F (species.rename name.extend B |₂ rename name.extend G)) ≈ (ν(M) species.rename name.extend B |ₛ pseudo_apply F (rename name.extend G)) : ξ_restriction M (pseudo_apply.on_parallel₂ F _ _) ... ≈ (B |ₛ ν(M) pseudo_apply F (rename name.extend G)) : ν_parallel₁ M ... ≈ (B |ₛ ν(M) pseudo_apply (rename name.extend G) F) : ξ_parallel₂ (ξ_restriction M (pseudo_apply.symm F _)) ... ≈ (B |ₛ pseudo_apply G (ν'(M) F)) : ξ_parallel₂ (symm (pseudo_apply.on_restriction G M F)) end | Γ (ν'(M) F) (ν'(N) G) := let h : depth (rename (name.ext (@name.extend Γ M.arity)) G) < depth G + 1 := begin rw ← depth.over_rename _ G, from nat.lt_add_of_pos_right nat.zero_lt_one end in begin unfold pseudo_apply rename, calc (ν(M) pseudo_apply F (ν'(N) rename (name.ext name.extend) G)) ≈ (ν(M) ν(N) pseudo_apply (rename name.extend F) (rename (name.ext name.extend) G)) : ξ_restriction M (pseudo_apply.on_restriction F N _) ... ≈ (ν(M) ν(N) pseudo_apply (rename (name.ext name.extend) G) (rename name.extend F)) : ξ_restriction M (ξ_restriction N (pseudo_apply.symm _ _)) ... ≈ ν(N) ν(M) pseudo_apply (rename name.extend G) (rename (name.ext name.extend) F) : symm (pseudo_apply.restriction_swap M N G F) ... ≈ ν(N) pseudo_apply G (ν'(M) rename (name.ext name.extend) F) : ξ_restriction N (symm (pseudo_apply.on_restriction G M _)) end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, depth x.snd.snd ) ⟩ ], dec_tac := do well_founded_tactics.unfold_wf_rel, well_founded_tactics.unfold_sizeof, tactic.dunfold_target [``depth, ``psigma.fst, ``psigma.snd], well_founded_tactics.cancel_nat_add_lt, tactic.try well_founded_tactics.trivial_nat_lt } private lemma pseudo_apply_app.equiv {a b} : ∀ {Γ} {bs : vector (name Γ) a} {A A' : species ℍ ω (context.extend b Γ)} {F : concretion ℍ ω Γ b a} , A ≈ A' → pseudo_apply_app bs A F ≈ pseudo_apply_app bs A' F := begin intros Γ as A A' G eq, induction G, case apply : Γ b bs y B { unfold pseudo_apply_app, from ξ_parallel₁ (species.equiv.rename _ eq), }, case parallel₁ : Γ b y F B ih { unfold pseudo_apply_app, from ξ_parallel₁ (ih eq) }, case parallel₂ : Γ b y B F ih { unfold pseudo_apply_app, from ξ_parallel₂ (ih eq) }, case restriction : Γ b y M F ih { unfold pseudo_apply_app, from ξ_restriction M (ih (species.equiv.rename _ eq)), } end private lemma pseudo_apply_app.par {a b} : ∀ {Γ} (bs : vector (name Γ) a) (A : species ℍ ω Γ) (B : species ℍ ω (context.extend b Γ)) (G : concretion ℍ ω Γ b a) , pseudo_apply_app bs (species.rename name.extend A |ₛ B) G ≈ (A |ₛ pseudo_apply_app bs B G) := begin intros Γ as A B G, induction G, case apply : _ b' bs y C { unfold pseudo_apply_app, simp, calc ((species.rename (name.mk_apply bs) (species.rename name.extend A) |ₛ species.rename (name.mk_apply bs) B) |ₛ species.rename (name.mk_apply as) C) ≈ ((species.rename (name.mk_apply bs ∘ name.extend) A |ₛ species.rename (name.mk_apply bs) B) |ₛ species.rename (name.mk_apply as) C) : by rw species.rename_compose _ _ A ... ≈ ((A |ₛ species.rename (name.mk_apply bs) B) |ₛ species.rename (name.mk_apply as) C) : by { rw [name.mk_apply_ext, species.rename_id], } ... ≈ (A |ₛ species.rename (name.mk_apply bs) B |ₛ species.rename (name.mk_apply as) C) : parallel_assoc₁ }, case parallel₁ : _ b' y G C ih { unfold pseudo_apply_app species.rename, calc (pseudo_apply_app as (species.rename name.extend A |ₛ B) G |ₛ C) ≈ ((A |ₛ pseudo_apply_app as B G) |ₛ C) : ξ_parallel₁ (ih as A B) ... ≈ (A |ₛ pseudo_apply_app as B G |ₛ C) : parallel_assoc₁ }, case parallel₂ : _ b' y C G ih { unfold pseudo_apply_app species.rename, calc (C |ₛ pseudo_apply_app as (species.rename name.extend A |ₛ B) G) ≈ (C |ₛ (A |ₛ pseudo_apply_app as B G)) : ξ_parallel₂ (ih as A B) ... ≈ (A |ₛ C |ₛ pseudo_apply_app as B G) : parallel_symm₁ }, case restriction : _ b' y' M G ih { unfold pseudo_apply_app, simp, calc (ν(M) pseudo_apply_app (vector.map name.extend as) (species.rename (name.ext name.extend) (species.rename name.extend A) |ₛ species.rename (name.ext name.extend) B) G) ≈ (ν(M) pseudo_apply_app (vector.map name.extend as) (species.rename name.extend (species.rename name.extend A) |ₛ species.rename (name.ext name.extend) B) G) : by rw ← species.rename_ext A ... ≈ (ν(M) species.rename name.extend A |ₛ pseudo_apply_app (vector.map name.extend as) (species.rename (name.ext name.extend) B) G) : ξ_restriction M (ih _ _ _) ... ≈ (A |ₛ ν(M) pseudo_apply_app (vector.map name.extend as) (species.rename (name.ext name.extend) B) G) : ν_parallel₁ M } end lemma pseudo_apply.equiv_l {a b} : ∀ {Γ} {F F' : concretion ℍ ω Γ a b} {G : concretion ℍ ω Γ b a} , F ≈ F' → pseudo_apply F G ≈ pseudo_apply F' G := begin intros Γ F F' G eq, induction eq, -- Modifiers are incredibly trivial case equiv.refl { from refl _ }, case equiv.trans : Γ b y F G H fg gh ih_fg ih_gh { from trans ih_fg ih_gh }, case equiv.symm : Γ b y F G eq ih_eq { from symm ih_eq }, -- Projections are trivial case equiv.ξ_parallel₁ : Γ b y F F' A eq ih { unfold pseudo_apply, from ξ_parallel₁ ih }, case equiv.ξ_parallel₂ : Γ b y A F F' eq ih { unfold pseudo_apply, from ξ_parallel₂ ih }, case equiv.ξ_restriction : Γ b y M F F' eq ih { unfold pseudo_apply, from ξ_restriction M ih }, -- Now for the interesting stuff. Well, relatively speaking. case equiv.parallel_nil : Γ b y F { unfold pseudo_apply, from parallel_nil₁ }, case equiv.parallel_symm : Γ b y F G { unfold pseudo_apply, from parallel_symm }, case equiv.parallel_assoc₁ : Γ b y F A B { unfold pseudo_apply, from parallel_assoc₁ }, case equiv.parallel_assoc₂ : Γ b y F A B { unfold pseudo_apply, from parallel_assoc₁ }, case equiv.ξ_apply : Γ b y bs A A' eq F { unfold pseudo_apply, from pseudo_apply_app.equiv eq }, case equiv.ξ_parallel : Γ b y F A A' eq { unfold pseudo_apply, from ξ_parallel₂ eq }, case equiv.ν_parallel₁ : Γ b y M A F { unfold pseudo_apply, from ν_parallel₁ M }, case equiv.ν_parallel₂ : Γ b y M F F { unfold pseudo_apply, rw ← pseudo_apply.rename name.extend F G, from ν_parallel₁ M }, case equiv.ν_drop : Γ b y M F { unfold pseudo_apply, rw ← pseudo_apply.rename name.extend F G, from ν_drop₁ M }, case equiv.ν_swap : Γ b y M N F { unfold pseudo_apply, calc (ν(M) ν(N) pseudo_apply F (rename name.extend (rename name.extend G))) ≈ (ν(M) ν(N) pseudo_apply F (rename (name.extend ∘ name.extend) G)) : by rw rename_compose ... ≈ (ν(N) ν(M) pseudo_apply (rename name.swap F) (rename name.swap (rename (name.extend ∘ name.extend) G))) : by { rw ← pseudo_apply.rename, from ν_swap₁ M N } ... ≈ (ν(N) ν(M) pseudo_apply (rename name.swap F) (rename (name.swap ∘ name.extend ∘ name.extend) G)) : by rw rename_compose ... ≈ (ν(N) ν(M) pseudo_apply (rename name.swap F) (rename (name.extend ∘ name.extend) G)) : by rw [← function.comp.assoc, name.swap_comp_extend, name.ext_extend] ... ≈ (ν(N) ν(M) pseudo_apply (rename name.swap F) (rename name.extend (rename name.extend G))) : by rw rename_compose }, case equiv.apply_parallel : Γ b y bs A B { unfold pseudo_apply, from pseudo_apply_app.par bs A B G } end theorem pseudo_apply.equiv {a b} : ∀ {Γ} {F F' : concretion ℍ ω Γ a b} {G G' : concretion ℍ ω Γ b a} , F ≈ F' → G ≈ G' → pseudo_apply F G ≈ pseudo_apply F' G' | Γ F F' G G' eq_1 eq_2 := calc pseudo_apply F G ≈ pseudo_apply F' G : pseudo_apply.equiv_l eq_1 ... ≈ pseudo_apply G F' : pseudo_apply.symm F' G ... ≈ pseudo_apply G' F' : pseudo_apply.equiv_l eq_2 ... ≈ pseudo_apply F' G' : pseudo_apply.symm G' F' protected lemma pseudo_apply.on_parallel₂' {Γ} {a b} (A : species ℍ ω Γ) (F : concretion ℍ ω Γ a b) (G : concretion ℍ ω Γ b a) : pseudo_apply (A |₂ F) G ≈ (A |ₛ pseudo_apply F G) := calc pseudo_apply (A |₂ F) G ≈ pseudo_apply G (A |₂ F) : pseudo_apply.symm _ G ... ≈ (A |ₛ pseudo_apply G F) : pseudo_apply.on_parallel₂ G A F ... ≈ (A |ₛ pseudo_apply F G) : ξ_parallel₂ (pseudo_apply.symm G F) protected lemma pseudo_apply.parallel_shift {Γ} {a b} (F : concretion ℍ ω Γ a b) (A : species ℍ ω Γ) (G : concretion ℍ ω Γ b a) : pseudo_apply (F |₁ A) G ≈ pseudo_apply F (A |₂ G) := calc pseudo_apply (F |₁ A) G ≈ pseudo_apply G (F |₁ A) : pseudo_apply.symm _ G ... ≈ (pseudo_apply G F |ₛ A) : pseudo_apply.on_parallel₁ G F A ... ≈ (A |ₛ pseudo_apply G F) : parallel_symm ... ≈ (A |ₛ pseudo_apply F G) : ξ_parallel₂ (pseudo_apply.symm G F) ... ≈ pseudo_apply F (A |₂ G) : symm (pseudo_apply.on_parallel₂ F A G) /-- Pseudo application lifted to the level of quotients. -/ def pseudo_apply.quotient {Γ a b} : concretion' ℍ ω Γ a b → concretion' ℍ ω Γ b a → species' ℍ ω Γ | F G := quotient.lift_on₂ F G (λ F G, ⟦ pseudo_apply F G ⟧) (λ F G F' G' eqF eqG, quot.sound (pseudo_apply.equiv eqF eqG)) lemma pseudo_apply.quotient.symm {Γ a b} : ∀ (F : concretion' ℍ ω Γ a b) (G : concretion' ℍ ω Γ b a) , pseudo_apply.quotient F G = pseudo_apply.quotient G F | F G := begin rcases quot.exists_rep F with ⟨ F, ⟨ _ ⟩ ⟩, rcases quot.exists_rep G with ⟨ G, ⟨ _ ⟩ ⟩, show ⟦pseudo_apply F G⟧ = ⟦pseudo_apply G F⟧, from quot.sound (pseudo_apply.symm F G), end end concretion end cpi #lint-
edd02dd67d5b77caf691b15ea2a9ed8e0020890a
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Elab/PreDefinition/WF/TerminationBy.lean
9aaa5d7f6cbe90fd316fc7c9643f8cd455a9dc3c
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
2,652
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command namespace Lean.Elab.WF inductive TerminationBy where | none | one (stx : Syntax) | many (map : NameMap Syntax) def expandTerminationBy (terminationBy? : Option Syntax) (cliques : Array (Array Name)) : MacroM TerminationBy := do if let some terminationBy := terminationBy? then let terminationBy := terminationBy[1] if terminationBy.getKind == ``Parser.Command.terminationBy1 then return TerminationBy.one terminationBy[0] else if terminationBy.getKind == ``Parser.Command.terminationByMany then let m ← terminationBy[0].getArgs.foldlM (init := {}) fun m arg => let declName? := cliques.findSome? fun clique => clique.findSome? fun declName => if arg[0].getId.isSuffixOf declName then some declName else none match declName? with | none => Macro.throwErrorAt arg[0] s!"function '{arg[0].getId}' not found in current declaration" | some declName => return m.insert declName arg[2] for clique in cliques do let mut found? := Option.none for declName in clique do if let some stx := m.find? declName then if let some found := found? then Macro.throwErrorAt stx s!"invalid 'termination_by' element, '{declName}' and '{found}' are in the same clique" found? := some declName return TerminationBy.many m else Macro.throwUnsupported else return TerminationBy.none def TerminatioBy.erase (t : TerminationBy) (clique : Array Name) : TerminationBy := match t with | TerminationBy.none => TerminationBy.none | TerminationBy.one .. => TerminationBy.none | TerminationBy.many m => do for declName in clique do if m.contains declName then let m := m.erase declName let m := m.erase declName if m.isEmpty then return TerminationBy.none else return TerminationBy.many m return t def TerminationBy.find? (t : TerminationBy) (clique : Array Name) : Option Syntax := do match t with | TerminationBy.none => Option.none | TerminationBy.one stx => some stx | TerminationBy.many m => clique.findSome? m.find? def TerminationBy.ensureIsEmpty (t : TerminationBy) : MacroM Unit := do match t with | TerminationBy.one stx => Macro.throwErrorAt stx "unused 'termination_by' element" | TerminationBy.many m => m.forM fun _ stx => Macro.throwErrorAt stx "unused 'termination_by' element" | _ => pure () end Lean.Elab.WF
19c697fdd65a3477effe6fe3d33734e1f60c1640
ed9ca7f44f366ca3a04272f939b2275961f36c59
/src/for_mathlib/uniform_space/separation.lean
44368851b5111681daf9848cac18988fc40ac8fb
[ "Apache-2.0" ]
permissive
wh941231/lean-perfectoid-spaces
e88fb5d76746009242349f276cd0920285d8beb9
43954f64ce4afdf4fa39e2aeef8ec43826b24f2a
refs/heads/master
1,653,641,928,775
1,588,499,720,000
1,588,499,720,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,178
lean
import topology.uniform_space.separation import topology.uniform_space.uniform_embedding import for_mathlib.quotient import for_mathlib.topology noncomputable theory local attribute [instance, priority 0] classical.prop_decidable open filter universes u v w local notation f `∘₂` g := function.bicompr f g section variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] local attribute [instance] uniform_space.separation_setoid def uniform_space.separated_map (f : α → β) : Prop := ∀ x y, x ≈ y → f x ≈ f y def uniform_space.separated_map₂ (f : α → β → γ) : Prop := uniform_space.separated_map (function.uncurry' f) --∀ x x' y y', x ≈ x' → y ≈ y' → f x y ≈ f x' y' end local attribute [instance] uniform_space.separation_setoid section open uniform_space variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type*} variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] lemma uniform_space.separated_map.comp {f : α → β} {g : β → γ} (hf : separated_map f) (hg : separated_map g) : separated_map (g ∘ f) := assume x y h, hg _ _ (hf x y h) lemma uniform_space.separated_map.comp₂ {f : α → β → γ} {g : γ → δ} (hf : separated_map₂ f) (hg : separated_map g) : separated_map₂ (g ∘₂ f) := begin unfold separated_map₂, rw function.uncurry'_bicompr, exact hf.comp hg end lemma uniform_space.separated_map.eqv_of_separated {f : α → β} {x y : α} (hf : uniform_space.separated_map f) (h : x ≈ y) : f x ≈ f y := hf x y h lemma uniform_space.separated_map.eq_of_separated [separated β] {f : α → β} {x y : α} (hf : uniform_space.separated_map f) (h : x ≈ y) : f x = f y := separated_def.1 ‹_› _ _ (hf x y h) lemma uniform_continuous.separated_map {f : α → β} (H : uniform_continuous f) : uniform_space.separated_map f := assume x y h s Hs, h _ (H Hs) lemma uniform_continuous.eqv_of_separated {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x ≈ f y := H.separated_map _ _ h lemma uniform_continuous.eq_of_separated [separated β] {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x = f y := H.separated_map.eq_of_separated h lemma separated.eq_iff [separated α] {x y : α} (h : x ≈ y) : x = y := separated_def.1 (by apply_instance) x y h end open uniform_space /-- separation space -/ @[reducible] def sep_quot (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace sep_quot variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] def mk {α : Type u} [uniform_space α] : α → sep_quot α := quotient.mk lemma uniform_embedding [separated α] : uniform_embedding (sep_quot.mk : α → sep_quot α) := { comap_uniformity := comap_quotient_eq_uniformity, inj := λ x y h, separated.eq_iff (quotient.exact h) } lemma uniform_continuous_mk : uniform_continuous (quotient.mk : α → sep_quot α) := le_refl _ def lift [separated β] (f : α → β) : sep_quot α → β := if h : separated_map f then quotient.lift f (λ x x' hxx', h.eq_of_separated hxx') else λ x, f $ habitant_of_quotient_habitant x lemma continuous_lift [separated β] {f : α → β} (h : continuous f) : continuous (lift f) := begin by_cases hf : separated_map f, { rw [lift, dif_pos hf], apply continuous_quotient_lift _ h, }, { rw [lift, dif_neg hf], exact continuous_of_const (λ a b, rfl)} end lemma uniform_continuous_lift [separated β] {f : α → β} (hf : uniform_continuous f) : uniform_continuous (lift f) := by simp [lift, hf.separated_map] ; exact hf section sep_quot_lift variables [separated β] {f : α → β} (h : separated_map f) include h lemma lift_mk (x : α) : lift f ⟦x⟧ = f x := by simp[lift, h] lemma unique_lift {g : sep_quot α → β} (hg : uniform_continuous g) (g_mk : ∀ x, g ⟦x⟧ = f x) : g = lift f := begin ext a, cases quotient.exists_rep a with x hx, rwa [←hx, lift_mk h x, g_mk x] end end sep_quot_lift def map (f : α → β) : sep_quot α → sep_quot β := lift (quotient.mk ∘ f) lemma continuous_map {f : α → β} (h : continuous f) : continuous (map f) := continuous_lift $ continuous_quotient_mk.comp h lemma uniform_continuous_map {f : α → β} (hf : uniform_continuous f): uniform_continuous (map f) := uniform_continuous_lift (uniform_continuous_mk.comp hf) lemma map_mk {f : α → β} (h : separated_map f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (h.comp uniform_continuous_mk.separated_map)] lemma map_unique {f : α → β} (hf : separated_map f) {g : sep_quot α → sep_quot β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a @[simp] lemma map_id : map (@id α) = id := map_unique uniform_continuous_id.separated_map rfl lemma map_comp {f : α → β} {g : β → γ} (hf : separated_map f) (hg : separated_map g) : map g ∘ map f = map (g ∘ f) := (map_unique (hf.comp hg) $ by simp only [(∘), map_mk, hf, hg]).symm protected def prod : sep_quot α → sep_quot β → sep_quot (α × β) := quotient.lift₂ (λ a b, ⟦(a, b)⟧) $ assume _ _ _ _ h h', quotient.eq.2 (separation_prod.2 ⟨h, h'⟩) lemma uniform_continuous_prod : uniform_continuous₂ (@sep_quot.prod α β _ _) := begin unfold uniform_continuous₂, unfold uniform_continuous, rw [uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff, uniformity_quotient, uniformity_prod_eq_prod], exact tendsto_map end @[simp] lemma prod_mk_mk (a : α) (b : β) : sep_quot.prod ⟦a⟧ ⟦b⟧ = ⟦(a, b)⟧ := rfl def lift₂ [separated γ] (f : α → β → γ) : sep_quot α → sep_quot β → γ := (lift $ function.uncurry' f) ∘₂ sep_quot.prod lemma uniform_continuous_lift₂ [separated γ] {f : α → β → γ} (hf : uniform_continuous₂ f) : uniform_continuous₂ (sep_quot.lift₂ f) := uniform_continuous_prod.comp $ uniform_continuous_lift hf @[simp] lemma lift₂_mk_mk [separated γ] {f : α → β → γ} (h : separated_map₂ f) (a : α) (b : β) : lift₂ f ⟦a⟧ ⟦b⟧ = f a b := lift_mk h _ def map₂ (f : α → β → γ) : sep_quot α → sep_quot β → sep_quot γ := lift₂ (quotient.mk ∘₂ f) lemma uniform_continuous_map₂ {f : α → β → γ} (hf : uniform_continuous₂ f) : uniform_continuous₂ (sep_quot.map₂ f) := uniform_continuous_lift₂ $ hf.comp uniform_continuous_mk @[simp] lemma map₂_mk_mk {f : α → β → γ} (h : separated_map₂ f) (a : α) (b : β) : map₂ f ⟦a⟧ ⟦b⟧ = ⟦f a b⟧ := lift₂_mk_mk (uniform_continuous_mk.separated_map.comp₂ h) _ _ lemma map₂_unique {f : α → β → γ} (hf : separated_map₂ f) {g : sep_quot α → sep_quot β → sep_quot γ} (comm : ∀ a b, ⟦f a b⟧ = g ⟦a⟧ ⟦b⟧) : map₂ f = g := by ext ⟨a⟩ ⟨b⟩ ; calc map₂ f ⟦a⟧ ⟦b⟧ = ⟦f a b⟧ : map₂_mk_mk hf a b ... = g ⟦a⟧ ⟦b⟧ : comm a b variables {δ : Type*} {δ' : Type*} {δ'' : Type*} {ε : Type*} [uniform_space δ] [uniform_space δ'] [uniform_space δ''] [uniform_space ε] lemma continuous_map₂ {f : α → β → γ} (h : continuous₂ f) : continuous₂ (map₂ f) := (continuous_lift $ by exact continuous_quotient_mk.comp h).comp uniform_continuous_prod.continuous -- Now begins a long series of lemmas for which we use an ad hoc killing tactic. meta def sep_quot_tac : tactic unit := `[repeat { rintros ⟨x⟩ }, repeat { rw quot_mk_quotient_mk }, repeat { rw map_mk <|> rw map₂_mk_mk }, repeat { rw H }, repeat { assumption } ] lemma map₂_const_left_eq_map {f : α → β → γ} (hf : separated_map₂ f) {g : β → γ} (hg : separated_map g) (a : α) (H : ∀ b, f a b = g b) : ∀ b, map₂ f ⟦a⟧ b = map g b := by sep_quot_tac lemma map₂_const_right_eq_map {f : α → β → γ} (hf : separated_map₂ f) {g : α → γ} (hg : separated_map g) (b : β) (H : ∀ a, f a b = g a) : ∀ a, map₂ f a ⟦b⟧ = map g a := by sep_quot_tac lemma map₂_map_left_self_const {f : α → β → γ} (hf : separated_map₂ f) {g : β → α} (hg : separated_map g) (c : γ) (H : ∀ b, f (g b) b = c) : ∀ b, map₂ f (map g b) b = ⟦c⟧ := by sep_quot_tac lemma map₂_map_right_self_const {f : α → β → γ} (hf : separated_map₂ f) {g : α → β} (hg : separated_map g) (c : γ) (H : ∀ a, f a (g a) = c) : ∀ a, map₂ f a (map g a) = ⟦c⟧ := by sep_quot_tac lemma map₂_comm {f : α → α → β} (hf : separated_map₂ f) (H : ∀ a b, f a b = f b a) : ∀ a b, map₂ f a b = map₂ f b a := by sep_quot_tac lemma map₂_assoc {f : α → β → δ} (hf : separated_map₂ f) {f' : β → γ → δ'} (hf' : separated_map₂ f') {g : δ → γ → ε} (hg : separated_map₂ g) {g' : α → δ' → ε} (hg' : separated_map₂ g') (H : ∀ a b c, g (f a b) c = g' a (f' b c)) : ∀ a b c, map₂ g (map₂ f a b) c = map₂ g' a (map₂ f' b c) := by sep_quot_tac lemma map₂_left_distrib {f : α → β → δ} (hf : separated_map₂ f) {f' : α → γ → δ'} (hf' : separated_map₂ f') {g : δ → δ' → ε} (hg : separated_map₂ g) {f'' : β → γ → δ''} (hg : separated_map₂ f'') {g' : α → δ'' → ε} (hg : separated_map₂ g') (H : ∀ a b c, g' a (f'' b c) = g (f a b) (f' a c)) : ∀ a b c, map₂ g' a (map₂ f'' b c) = map₂ g (map₂ f a b) (map₂ f' a c) := by sep_quot_tac lemma map₂_right_distrib {f : α → γ → δ} (hf : separated_map₂ f) {f' : β → γ → δ'} (hf' : separated_map₂ f') {g : δ → δ' → ε} (hg : separated_map₂ g) {f'' : α → β → δ''} (hg : separated_map₂ f'') {g' : δ'' → γ → ε} (hg : separated_map₂ g') (H : ∀ a b c, g' (f'' a b) c = g (f a c) (f' b c)) : ∀ a b c, map₂ g' (map₂ f'' a b) c = map₂ g (map₂ f a c) (map₂ f' b c) := by sep_quot_tac end sep_quot
feb550a2bec79c53a84e6276272deadda4de76dd
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/data/nat/prime.lean
e0c6db381197c4b9e5f60b015582eb5030109d63
[ "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
17,103
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro Prime numbers. -/ import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm open bool subtype namespace nat open decidable /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 := ne.symm $ (ne_of_lt hp.gt_one) theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (decidable.lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := assume hn : n = 0, have h2 : ¬ prime 0, from dec_trivial, h2 (hn ▸ h) theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 := lt_of_succ_lt pp.gt_one theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 := lt_pred_iff.2 pp.gt_one theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_ge_two h a1).1 (dvd_mul_right _ _) section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := rfl | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_ge_two pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, m ≥ 2 → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : min_fac n > 0 := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p := ⟨λ pp, ⟨pp.ge_two, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ /-- This instance is faster in the virtual machine than `decidable_prime_1`, but slower in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ theorem exists_infinite_primes (n : ℕ) : ∃ p, p ≥ n ∧ prime p := let p := min_fac (fact n + 1) in have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ fact n, from dvd_fact (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := (nat.mod_two_eq_zero_or_one p).elim (λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) or.inr theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).gt_one /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim IH id] lemma prime.dvd_fact : ∀ {n p : ℕ} (hp : prime p), p ∣ n.fact ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩ lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb], perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _) end lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) : p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n := have hpd : p^(k+l) * p ∣ m*n, from hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, show p^k*p ∣ m ∨ p^l*p ∣ n, from hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) end nat
17116306fea15bf183be74b35327a25ffc144594
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/group4.lean
f9c17c88dfa9a43dfa1a60797acb0b6475ce3c4a
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,073
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 -- algebra.group -- ============= -- Various structures with 1, *, inv, including groups. import logic.eq logic.connectives import data.unit data.sigma data.prod import algebra.function algebra.binary open eq namespace algebra structure has_mul [class] (A : Type) := mk :: (mul : A → A → A) structure has_one [class] (A : Type) := mk :: (one : A) structure has_inv [class] (A : Type) := mk :: (inv : A → A) infixl `*` := has_mul.mul postfix `⁻¹` := has_inv.inv notation 1 := has_one.one structure semigroup [class] (A : Type) extends has_mul A := mk :: (assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) set_option pp.notation false -- set_option pp.implicit true -- set_option pp.coercions true print instances has_mul section variables {A : Type} [s : semigroup A] include s variables a b : A example : a * b = semigroup.mul a b := rfl theorem mul_assoc (a b c : A) : a * b * c = a * (b * c) := semigroup.assoc a b c end structure comm_semigroup [class] (A : Type) extends semigroup A := mk :: (comm : ∀a b, mul a b = mul b a) namespace comm_semigroup variables {A : Type} [s : comm_semigroup A] include s variables a b c : A theorem mul_comm : a * b = b * a := !comm_semigroup.comm theorem mul_left_comm : a * (b * c) = b * (a * c) := binary.left_comm mul_comm mul_assoc a b c end comm_semigroup structure monoid [class] (A : Type) extends semigroup A, has_one A := mk :: (right_id : ∀a, mul a one = a) (left_id : ∀a, mul one a = a) section variables {A : Type} [s : monoid A] variable a : A include s theorem mul_right_id : a * 1 = a := !monoid.right_id theorem mul_left_id : 1 * a = a := !monoid.left_id end structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A print prefix algebra.comm_monoid structure Semigroup := mk :: (carrier : Type) (struct : semigroup carrier) coercion [persistent] Semigroup.carrier instance [persistent] Semigroup.struct structure CommSemigroup := mk :: (carrier : Type) (struct : comm_semigroup carrier) coercion [persistent] CommSemigroup.carrier instance [persistent] CommSemigroup.struct structure Monoid := mk :: (carrier : Type) (struct : monoid carrier) coercion [persistent] Monoid.carrier instance [persistent] Monoid.struct structure CommMonoid := mk :: (carrier : Type) (struct : comm_monoid carrier) coercion [persistent] CommMonoid.carrier instance [persistent] CommMonoid.struct end algebra open algebra section examples theorem test1 {S : Semigroup} (a b c d : S) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : mul_assoc ... = a * b * (c * d) : mul_assoc theorem test2 {M : CommSemigroup} (a b : M) : a * b = a * b := rfl theorem test3 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : mul_assoc ... = a * b * (c * d) : mul_assoc -- for test4b to work, we need instances at the level of the bundled structures as well definition Monoid_Semigroup [coercion] (M : Monoid) : Semigroup := Semigroup.mk (Monoid.carrier M) _ theorem test4 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := test1 a b c d theorem test5 {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : mul_right_id ... = a * (b * c) : mul_assoc theorem test5a {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : mul_right_id ... = a * (b * c) : mul_assoc theorem test5b {A : Type} {M : monoid A} (a b c : A) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : mul_right_id ... = a * (b * c) : mul_assoc theorem test6 {M : CommMonoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : mul_right_id ... = a * (b * c) : mul_assoc end examples
0f24a65190ccc8d63f41fde6b3812f872964b38e
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/module/multilinear.lean
de11e05b4035eaf53bc71a61c35a2cc71d463249
[ "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
20,024
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.algebra.module.basic import linear_algebra.multilinear.basic /-! # Continuous multilinear maps We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear and continuous, by extending the space of multilinear maps with a continuity assumption. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these spaces are also topological spaces. ## Main definitions * `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from `Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module. ## Implementation notes We mostly follow the API of multilinear maps. ## Notation We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from `M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent types as the arguments of our continuous multilinear maps), but arguably the most important one, especially when defining iterated derivatives. -/ open function fin set open_locale big_operators universes u v w w₁ w₁' w₂ w₃ w₄ variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁} {M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι] /-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R` with a topological structure. In applications, there will be compatibility conditions between the algebraic and the topological structures, but this is not needed for the definition. -/ structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] extends multilinear_map R M₁ M₂ := (cont : continuous to_fun) notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M' namespace continuous_multilinear_map section semiring variables [semiring R] [Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, module R (M i)] [Π i, module R (M₁ i)] [Π i, module R (M₁' i)] [module R M₂] [module R M₃] [module R M₄] [Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)] [topological_space M₂] [topological_space M₃] [topological_space M₄] (f f' : continuous_multilinear_map R M₁ M₂) instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) (λ _, (Π i, M₁ i) → M₂) := ⟨λ f, f.to_fun⟩ @[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont @[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl theorem to_multilinear_map_inj : function.injective (continuous_multilinear_map.to_multilinear_map : continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂) | ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl @[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := to_multilinear_map_inj $ multilinear_map.ext H @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero instance : has_zero (continuous_multilinear_map R M₁ M₂) := ⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩ instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl @[simp] lemma to_multilinear_map_zero : (0 : continuous_multilinear_map R M₁ M₂).to_multilinear_map = 0 := rfl section has_scalar variables {R' R'' A : Type*} [monoid R'] [monoid R''] [semiring A] [Π i, module A (M₁ i)] [module A M₂] [distrib_mul_action R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂] [distrib_mul_action R'' M₂] [has_continuous_const_smul R'' M₂] [smul_comm_class A R'' M₂] instance : has_scalar R' (continuous_multilinear_map A M₁ M₂) := ⟨λ c f, { cont := f.cont.const_smul c, .. c • f.to_multilinear_map }⟩ @[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl @[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) : (c • f).to_multilinear_map = c • f.to_multilinear_map := rfl instance [smul_comm_class R' R'' M₂] : smul_comm_class R' R'' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ c₂ f, ext $ λ x, smul_comm _ _ _⟩ instance [has_scalar R' R''] [is_scalar_tower R' R'' M₂] : is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩ instance [distrib_mul_action R'ᵐᵒᵖ M₂] [is_central_scalar R' M₂] : is_central_scalar R' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ f, ext $ λ x, op_smul_eq_smul _ _⟩ instance : mul_action R' (continuous_multilinear_map A M₁ M₂) := function.injective.mul_action to_multilinear_map to_multilinear_map_inj (λ _ _, rfl) end has_scalar section has_continuous_add variable [has_continuous_add M₂] instance : has_add (continuous_multilinear_map R M₁ M₂) := ⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl @[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) : (f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map := rfl instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) /-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/ def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ := ⟨λ f, f m, rfl, λ _ _, rfl⟩ @[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂) (m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m := (apply_add_hom m).map_sum f s end has_continuous_add /-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ := { cont := f.cont.comp (continuous_const.update i continuous_id), .. f.to_multilinear_map.to_linear_map m i } /-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/ def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) : continuous_multilinear_map R M₁ (M₂ × M₃) := { cont := f.cont.prod_mk g.cont, .. f.to_multilinear_map.prod g.to_multilinear_map } @[simp] lemma prod_apply (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) : (f.prod g) m = (f m, g m) := rfl /-- Combine a family of continuous multilinear maps with the same domain and codomains `M' i` into a continuous multilinear map taking values in the space of functions `Π i, M' i`. -/ def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : continuous_multilinear_map R M₁ (Π i, M' i) := { cont := continuous_pi $ λ i, (f i).coe_continuous, to_multilinear_map := multilinear_map.pi (λ i, (f i).to_multilinear_map) } @[simp] lemma coe_pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : ⇑(pi f) = λ m j, f j m := rfl lemma pi_apply {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) (m : Π i, M₁ i) (j : ι') : pi f m j = f j m := rfl /-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call `g.comp_continuous_linear_map f`. -/ def comp_continuous_linear_map (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) : continuous_multilinear_map R M₁ M₄ := { cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _, .. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) } @[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) : g.comp_continuous_linear_map f m = g (λ i, f i $ m i) := rfl /-- Composing a continuous multilinear map with a continuous linear map gives again a continuous multilinear map. -/ def _root_.continuous_linear_map.comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : continuous_multilinear_map R M₁ M₃ := { cont := g.cont.comp f.cont, .. g.to_linear_map.comp_multilinear_map f.to_multilinear_map } @[simp] lemma _root_.continuous_linear_map.comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : ((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) = (g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) := by { ext m, refl } /-- `continuous_multilinear_map.pi` as an `equiv`. -/ @[simps] def pi_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] : (Π i, continuous_multilinear_map R M₁ (M' i)) ≃ continuous_multilinear_map R M₁ (Π i, M' i) := { to_fun := continuous_multilinear_map.pi, inv_fun := λ f i, (continuous_linear_map.proj i : _ →L[R] M' i).comp_continuous_multilinear_map f, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := f.to_multilinear_map.cons_add m x y /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := f.to_multilinear_map.cons_smul m c x lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := f.to_multilinear_map.map_piecewise_add _ _ _ /-- Additivity of a continuous multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := f.to_multilinear_map.map_add_univ _ _ section apply_sum open fintype finset variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) /-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum_finset _ _ /-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum _ end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)] [module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : continuous_multilinear_map R M₁ M₂ := { to_multilinear_map := f.to_multilinear_map.restrict_scalars R, cont := f.cont } @[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar end semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f f' : continuous_multilinear_map R M₁ M₂) @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := f.to_multilinear_map.map_sub _ _ _ _ section topological_add_group variable [topological_add_group M₂] instance : has_neg (continuous_multilinear_map R M₁ M₂) := ⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (continuous_multilinear_map R M₁ M₂) := ⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl instance : add_comm_group (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end topological_add_group end ring section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f : continuous_multilinear_map R M₁ M₂) lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m := f.to_multilinear_map.map_piecewise_smul _ _ _ /-- Multiplicativity of a continuous multilinear map along all coordinates at the same time, writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λ i, c i • m i) = (∏ i, c i) • f m := f.to_multilinear_map.map_smul_univ _ _ end comm_semiring section distrib_mul_action variables {R' R'' A : Type*} [monoid R'] [monoid R''] [semiring A] [Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [Π i, topological_space (M₁ i)] [topological_space M₂] [Π i, module A (M₁ i)] [module A M₂] [distrib_mul_action R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂] [distrib_mul_action R'' M₂] [has_continuous_const_smul R'' M₂] [smul_comm_class A R'' M₂] instance [has_continuous_add M₂] : distrib_mul_action R' (continuous_multilinear_map A M₁ M₂) := function.injective.distrib_mul_action ⟨to_multilinear_map, to_multilinear_map_zero, to_multilinear_map_add⟩ to_multilinear_map_inj (λ _ _, rfl) end distrib_mul_action section module variables {R' A : Type*} [semiring R'] [semiring A] [Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [Π i, topological_space (M₁ i)] [topological_space M₂] [has_continuous_add M₂] [Π i, module A (M₁ i)] [module A M₂] [module R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂] /-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module R' (continuous_multilinear_map A M₁ M₂) := function.injective.module _ ⟨to_multilinear_map, to_multilinear_map_zero, to_multilinear_map_add⟩ to_multilinear_map_inj (λ _ _, rfl) /-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map the corresponding multilinear map. -/ @[simps] def to_multilinear_map_linear : continuous_multilinear_map A M₁ M₂ →ₗ[R'] multilinear_map A M₁ M₂ := { to_fun := to_multilinear_map, map_add' := to_multilinear_map_add, map_smul' := to_multilinear_map_smul } /-- `continuous_multilinear_map.pi` as a `linear_equiv`. -/ @[simps {simp_rhs := tt}] def pi_linear_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [∀ i, has_continuous_add (M' i)] [Π i, module R' (M' i)] [Π i, module A (M' i)] [∀ i, smul_comm_class A R' (M' i)] [Π i, has_continuous_const_smul R' (M' i)] : (Π i, continuous_multilinear_map A M₁ (M' i)) ≃ₗ[R'] continuous_multilinear_map A M₁ (Π i, M' i) := { map_add' := λ x y, rfl, map_smul' := λ c x, rfl, .. pi_equiv } end module section comm_algebra variables (R ι) (A : Type*) [fintype ι] [comm_semiring R] [comm_semiring A] [algebra R A] [topological_space A] [has_continuous_mul A] /-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra over `𝕜`, associating to `m` the product of all the `m i`. See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/ protected def mk_pi_algebra : continuous_multilinear_map R (λ i : ι, A) A := { cont := continuous_finset_prod _ $ λ i hi, continuous_apply _, to_multilinear_map := multilinear_map.mk_pi_algebra R ι A} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : continuous_multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i := rfl end comm_algebra section algebra variables (R n) (A : Type*) [comm_semiring R] [semiring A] [algebra R A] [topological_space A] [has_continuous_mul A] /-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to `m` the product of all the `m i`. See also: `continuous_multilinear_map.mk_pi_algebra`. -/ protected def mk_pi_algebra_fin : A [×n]→L[R] A := { cont := begin change continuous (λ m, (list.of_fn m).prod), simp_rw list.of_fn_eq_map, exact continuous_list_prod _ (λ i hi, continuous_apply _), end, to_multilinear_map := multilinear_map.mk_pi_algebra_fin R n A} variables {R n A} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : continuous_multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl end algebra end continuous_multilinear_map
3bc4e9d09c951c0838bd251824b8f1281bca67c1
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/ring_theory/fractional_ideal.lean
7dcf36f97245411d3c4eaec11f6919ed2623fb90
[ "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
45,791
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.localization import ring_theory.noetherian import ring_theory.principal_ideal_domain import tactic.field_simp /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal S P` is the type of fractional ideals in `P` * `has_coe (ideal R) (fractional_ideal S P)` instance * `comm_semiring (fractional_ideal S P)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal S P)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R⁰ = R \ {0}` (i.e. the field of fractions). * `fractional_ideal R⁰ K` is the type of fractional ideals in the field of fractions * `has_div (fractional_ideal R⁰ K)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `prod_one_self_div_eq` states that `1 / I` is the inverse of `I` if one exists * `is_noetherian` states that very fractional ideal of a noetherian integral domain is noetherian ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `↑I + ↑J = ↑(I + J)` and `↑⊥ = ↑0`. Many results in fact do not need that `P` is a localization, only that `P` is an `R`-algebra. We omit the `is_localization` parameter whenever this is practical. Similarly, we don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `R⁰`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open is_localization local notation R`⁰`:9000 := non_zero_divisors R section defs variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] variables [algebra R P] variables (S) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R P) := ∃ a ∈ S, ∀ b ∈ I, is_integer R (a • b) variables (S P) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R P // is_fractional S I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] variables [algebra R P] [loc : is_localization S P] /-- Map a fractional ideal `I` to a submodule by forgetting that `∃ a, a I ⊆ R`. This coercion is typically called `coe_to_submodule` in lemma names (or `coe` when the coercion is clear from the context), not to be confused with `is_localization.coe_submodule : ideal R → submodule R P` (which we use to define `coe : ideal R → fractional_ideal S P`, referred to as `coe_ideal` in theorem names). -/ instance : has_coe (fractional_ideal S P) (submodule R P) := ⟨λ I, I.val⟩ protected lemma is_fractional (I : fractional_ideal S P) : is_fractional S (I : submodule R P) := I.prop section set_like instance : set_like (fractional_ideal S P) P := { coe := λ I, ↑(I : submodule R P), coe_injective' := set_like.coe_injective.comp subtype.coe_injective } @[simp] lemma mem_coe {I : fractional_ideal S P} {x : P} : x ∈ (I : submodule R P) ↔ x ∈ I := iff.rfl @[ext] lemma ext {I J : fractional_ideal S P} : (∀ x, x ∈ I ↔ x ∈ J) → I = J := set_like.ext /-- Copy of a `fractional_ideal` with a new underlying set equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : fractional_ideal S P) (s : set P) (hs : s = ↑p) : fractional_ideal S P := ⟨submodule.copy p s hs, by { convert p.is_fractional, ext, simp only [hs], refl }⟩ end set_like @[simp] lemma val_eq_coe (I : fractional_ideal S P) : I.val = I := rfl @[simp, norm_cast] lemma coe_mk (I : submodule R P) (hI : is_fractional S I) : (subtype.mk I hI : submodule R P) = I := rfl lemma coe_to_submodule_injective : function.injective (coe : fractional_ideal S P → submodule R P) := subtype.coe_injective lemma is_fractional_of_le_one (I : submodule R P) (h : I ≤ 1) : is_fractional S I := begin use [1, S.one_mem], intros b hb, rw one_smul, obtain ⟨b', b'_mem, rfl⟩ := h hb, exact set.mem_range_self b', end lemma is_fractional_of_le {I : submodule R P} {J : fractional_ideal S P} (hIJ : I ≤ J) : is_fractional S I := begin obtain ⟨a, a_mem, ha⟩ := J.is_fractional, use [a, a_mem], intros b b_mem, exact ha b (hIJ b_mem) end /-- Map an ideal `I` to a fractional ideal by forgetting `I` is integral. This is a bundled version of `is_localization.coe_submodule : ideal R → submodule R P`, which is not to be confused with the `coe : fractional_ideal S P → submodule R P`, also called `coe_to_submodule` in theorem names. -/ instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal S P) := ⟨λ I, ⟨coe_submodule P I, is_fractional_of_le_one _ (by simpa using coe_submodule_mono P (le_top : I ≤ ⊤))⟩⟩ @[simp, norm_cast] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal S P) : submodule R P) = coe_submodule P I := rfl variables (S) @[simp] lemma mem_coe_ideal {x : P} {I : ideal R} : x ∈ (I : fractional_ideal S P) ↔ ∃ x', x' ∈ I ∧ algebra_map R P x' = x := mem_coe_submodule _ _ lemma mem_coe_ideal_of_mem {x : R} {I : ideal R} (hx : x ∈ I) : algebra_map R P x ∈ (I : fractional_ideal S P) := (mem_coe_ideal S).mpr ⟨x, hx, rfl⟩ lemma coe_ideal_le_coe_ideal' [is_localization S P] (h : S ≤ non_zero_divisors R) {I J : ideal R} : (I : fractional_ideal S P) ≤ J ↔ I ≤ J := coe_submodule_le_coe_submodule h @[simp] lemma coe_ideal_le_coe_ideal (K : Type*) [comm_ring K] [algebra R K] [is_fraction_ring R K] {I J : ideal R} : (I : fractional_ideal R⁰ K) ≤ J ↔ I ≤ J := is_fraction_ring.coe_submodule_le_coe_submodule instance : has_zero (fractional_ideal S P) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal S P) ↔ x = 0 := ⟨(λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩)⟩ variables {S} @[simp, norm_cast] lemma coe_zero : ↑(0 : fractional_ideal S P) = (⊥ : submodule R P) := submodule.ext $ λ _, mem_zero_iff S @[simp, norm_cast] lemma coe_to_fractional_ideal_bot : ((⊥ : ideal R) : fractional_ideal S P) = 0 := rfl variables (P) include loc @[simp] lemma exists_mem_to_map_eq {x : R} {I : ideal R} (h : S ≤ non_zero_divisors R) : (∃ x', x' ∈ I ∧ algebra_map R P x' = algebra_map R P x) ↔ x ∈ I := ⟨λ ⟨x', hx', eq⟩, is_localization.injective _ h eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩ variables {P} lemma coe_to_fractional_ideal_injective (h : S ≤ non_zero_divisors R) : function.injective (coe : ideal R → fractional_ideal S P) := λ I J heq, have ∀ (x : R), algebra_map R P x ∈ (I : fractional_ideal S P) ↔ algebra_map R P x ∈ (J : fractional_ideal S P) := λ x, heq ▸ iff.rfl, ideal.ext (by simpa only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq P h] using this) lemma coe_to_fractional_ideal_eq_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal S P) = 0 ↔ I = (⊥ : ideal R) := ⟨λ h, coe_to_fractional_ideal_injective hS h, λ h, by rw [h, coe_to_fractional_ideal_bot]⟩ lemma coe_to_fractional_ideal_ne_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal S P) ≠ 0 ↔ I ≠ (⊥ : ideal R) := not_iff_not.mpr (coe_to_fractional_ideal_eq_zero hS) omit loc lemma coe_to_submodule_eq_bot {I : fractional_ideal S P} : (I : submodule R P) = ⊥ ↔ I = 0 := ⟨λ h, coe_to_submodule_injective (by simp [h]), λ h, by simp [h]⟩ lemma coe_to_submodule_ne_bot {I : fractional_ideal S P} : ↑I ≠ (⊥ : submodule R P) ↔ I ≠ 0 := not_iff_not.mpr coe_to_submodule_eq_bot instance : inhabited (fractional_ideal S P) := ⟨0⟩ instance : has_one (fractional_ideal S P) := ⟨(⊤ : ideal R)⟩ variables (S) @[simp, norm_cast] lemma coe_ideal_top : ((⊤ : ideal R) : fractional_ideal S P) = 1 := rfl lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal S P) ↔ ∃ x' : R, algebra_map R P x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨⟩, h⟩) lemma coe_mem_one (x : R) : algebra_map R P x ∈ (1 : fractional_ideal S P) := (mem_one_iff S).mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal S P) := (mem_one_iff S).mpr ⟨1, ring_hom.map_one _⟩ variables {S} /-- `(1 : fractional_ideal S P)` is defined as the R-submodule `f(R) ≤ P`. However, this is not definitionally equal to `1 : submodule R P`, which is proved in the actual `simp` lemma `coe_one`. -/ lemma coe_one_eq_coe_submodule_top : ↑(1 : fractional_ideal S P) = coe_submodule P (⊤ : ideal R) := rfl @[simp, norm_cast] lemma coe_one : (↑(1 : fractional_ideal S P) : submodule R P) = 1 := by rw [coe_one_eq_coe_submodule_top, coe_submodule_top] section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ @[simp] lemma coe_le_coe {I J : fractional_ideal S P} : (I : submodule R P) ≤ (J : submodule R P) ↔ I ≤ J := iff.rfl lemma zero_le (I : fractional_ideal S P) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal S P) := { bot := 0, bot_le := zero_le, ..set_like.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal S P) = 0 := rfl @[simp] lemma le_zero_iff {I : fractional_ideal S P} : I ≤ 0 ↔ I = 0 := le_bot_iff lemma eq_zero_iff {I : fractional_ideal S P} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, (mem_zero_iff S).mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal S P) : is_fractional S (I ⊔ J : submodule R P) := begin rcases I.is_fractional with ⟨aI, haI, hI⟩, rcases J.is_fractional with ⟨aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, rfl⟩, rw smul_add, apply is_integer_add, { rw [mul_smul, smul_comm], exact is_integer_smul (hI bI hbI), }, { rw mul_smul, exact is_integer_smul (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal S P) : is_fractional S (I ⊓ J : submodule R P) := begin rcases I.is_fractional with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact hI b hbI end instance lattice : lattice (fractional_ideal S P) := { inf := λ I J, ⟨I ⊓ J, fractional_inf I J⟩, sup := λ I J, ⟨I ⊔ J, fractional_sup I J⟩, inf_le_left := λ I J, show (I ⊓ J : submodule R P) ≤ I, from inf_le_left, inf_le_right := λ I J, show (I ⊓ J : submodule R P) ≤ J, from inf_le_right, le_inf := λ I J K hIJ hIK, show (I : submodule R P) ≤ J ⊓ K, from le_inf hIJ hIK, le_sup_left := λ I J, show (I : submodule R P) ≤ I ⊔ J, from le_sup_left, le_sup_right := λ I J, show (J : submodule R P) ≤ I ⊔ J, from le_sup_right, sup_le := λ I J K hIK hJK, show (I ⊔ J : submodule R P) ≤ K, from sup_le hIK hJK, ..set_like.partial_order } instance : semilattice_sup_bot (fractional_ideal S P) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal S P) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal S P) : I ⊔ J = I + J := rfl @[simp, norm_cast] lemma coe_add (I J : fractional_ideal S P) : (↑(I + J) : submodule R P) = I + J := rfl lemma fractional_mul (I J : fractional_ideal S P) : is_fractional S (I * J : submodule R P) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [mul_smul, mul_comm m, ← smul_mul_assoc, ← hn', ← algebra.smul_def], apply hI, exact submodule.smul_mem _ _ hm }, { rw smul_zero, exact ⟨0, ring_hom.map_zero _⟩ }, { intros x y hx hy, rw smul_add, apply is_integer_add hx hy }, { intros r x hx, rw smul_comm, exact is_integer_smul hx }, end /-- `fractional_ideal.mul` is the product of two fractional ideals, used to define the `has_mul` instance. This is only an auxiliary definition: the preferred way of writing `I.mul J` is `I * J`. Elaborated terms involving `fractional_ideal` tend to grow quite large, so by making definitions irreducible, we hope to avoid deep unfolds. -/ @[irreducible] def mul (I J : fractional_ideal S P) : fractional_ideal S P := ⟨I * J, fractional_mul I J⟩ local attribute [semireducible] mul instance : has_mul (fractional_ideal S P) := ⟨λ I J, mul I J⟩ @[simp] lemma mul_eq_mul (I J : fractional_ideal S P) : mul I J = I * J := rfl @[simp, norm_cast] lemma coe_mul (I J : fractional_ideal S P) : (↑(I * J) : submodule R P) = I * J := rfl lemma mul_left_mono (I : fractional_ideal S P) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal S P) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) lemma mul_mem_mul {I J : fractional_ideal S P} {i j : P} (hi : i ∈ I) (hj : j ∈ J) : i * j ∈ I * J := submodule.mul_mem_mul hi hj lemma mul_le {I J K : fractional_ideal S P} : I * J ≤ K ↔ (∀ (i ∈ I) (j ∈ J), i * j ∈ K) := submodule.mul_le @[elab_as_eliminator] protected theorem mul_induction_on {I J : fractional_ideal S P} {C : P → Prop} {r : P} (hr : r ∈ I * J) (hm : ∀ (i ∈ I) (j ∈ J), C (i * j)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := submodule.mul_induction_on hr hm h0 ha hs instance comm_semiring : comm_semiring (fractional_ideal S P) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, mul_assoc := λ I J K, coe_to_submodule_injective (submodule.mul_assoc _ _ _), mul_comm := λ I J, coe_to_submodule_injective (submodule.mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, rfl⟩, convert submodule.smul_mem _ y' hx, rw [mul_comm, eq_comm], exact algebra.smul_def y' x }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h (one_mem_one _), rwa [mul_one] at this } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, rfl⟩ y hy, convert submodule.smul_mem _ x' hy, rw eq_comm, exact algebra.smul_def x' y }, { have : 1 * x ∈ (1 * I) := mul_mem_mul (one_mem_one _) h, rwa one_mul at this } end, mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [(mem_zero_iff S).mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [(mem_zero_iff S).mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, coe_to_submodule_injective (mul_add _ _ _), right_distrib := λ I J K, coe_to_submodule_injective (add_mul _ _ _), ..fractional_ideal.has_zero S, ..fractional_ideal.has_add, ..fractional_ideal.has_one, ..fractional_ideal.has_mul } section order lemma add_le_add_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) : J' + I ≤ J' + J := sup_le_sup_left hIJ J' lemma mul_le_mul_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) : J' * I ≤ J' * J := mul_le.mpr (λ k hk j hj, mul_mem_mul hk (hIJ hj)) lemma le_self_mul_self {I : fractional_ideal S P} (hI: 1 ≤ I) : I ≤ I * I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma mul_self_le_self {I : fractional_ideal S P} (hI: I ≤ 1) : I * I ≤ I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma coe_ideal_le_one {I : ideal R} : (I : fractional_ideal S P) ≤ 1 := λ x hx, let ⟨y, _, hy⟩ := (fractional_ideal.mem_coe_ideal S).mp hx in (fractional_ideal.mem_one_iff S).mpr ⟨y, hy⟩ lemma le_one_iff_exists_coe_ideal {J : fractional_ideal S P} : J ≤ (1 : fractional_ideal S P) ↔ ∃ (I : ideal R), ↑I = J := begin split, { intro hJ, refine ⟨⟨{x : R | algebra_map R P x ∈ J}, _, _, _⟩, _⟩, { rw [mem_set_of_eq, ring_hom.map_zero], exact J.val.zero_mem }, { intros a b ha hb, rw [mem_set_of_eq, ring_hom.map_add], exact J.val.add_mem ha hb }, { intros c x hx, rw [smul_eq_mul, mem_set_of_eq, ring_hom.map_mul, ← algebra.smul_def], exact J.val.smul_mem c hx }, { ext x, split, { rintros ⟨y, hy, eq_y⟩, rwa ← eq_y }, { intro hx, obtain ⟨y, eq_x⟩ := (fractional_ideal.mem_one_iff S).mp (hJ hx), rw ← eq_x at *, exact ⟨y, hx, rfl⟩ } } }, { rintro ⟨I, hI⟩, rw ← hI, apply coe_ideal_le_one }, end end order variables {P' : Type*} [comm_ring P'] [algebra R P'] [loc' : is_localization S P'] variables {P'' : Type*} [comm_ring P''] [algebra R P''] [loc'' : is_localization S P''] lemma fractional_map (g : P →ₐ[R] P') (I : fractional_ideal S P) : is_fractional S (submodule.map g.to_linear_map I) := begin rcases I with ⟨I, a, a_nonzero, hI⟩, use [a, a_nonzero], intros b hb, obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'] end /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : P →ₐ[R] P') : fractional_ideal S P → fractional_ideal S P' := λ I, ⟨submodule.map g.to_linear_map I, fractional_map g I⟩ @[simp, norm_cast] lemma coe_map (g : P →ₐ[R] P') (I : fractional_ideal S P) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma mem_map {I : fractional_ideal S P} {g : P →ₐ[R] P'} {y : P'} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y := submodule.mem_map variables (I J : fractional_ideal S P) (g : P →ₐ[R] P') @[simp] lemma map_id : I.map (alg_hom.id _ _) = I := coe_to_submodule_injective (submodule.map_id I) @[simp] lemma map_comp (g' : P' →ₐ[R] P'') : I.map (g'.comp g) = (I.map g).map g' := coe_to_submodule_injective (submodule.map_comp g.to_linear_map g'.to_linear_map I) @[simp, norm_cast] lemma map_coe_ideal (I : ideal R) : (I : fractional_ideal S P).map g = I := begin ext x, simp only [mem_coe_ideal], split, { rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩, exact ⟨y, hy, (g.commutes y).symm⟩ }, { rintro ⟨y, hy, rfl⟩, exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ }, end @[simp] lemma map_one : (1 : fractional_ideal S P).map g = 1 := map_coe_ideal g ⊤ @[simp] lemma map_zero : (0 : fractional_ideal S P).map g = 0 := map_coe_ideal g 0 @[simp] lemma map_add : (I + J).map g = I.map g + J.map g := coe_to_submodule_injective (submodule.map_sup _ _ _) @[simp] lemma map_mul : (I * J).map g = I.map g * J.map g := coe_to_submodule_injective (submodule.map_mul _ _ _) @[simp] lemma map_map_symm (g : P ≃ₐ[R] P') : (I.map (g : P →ₐ[R] P')).map (g.symm : P' →ₐ[R] P) = I := by rw [←map_comp, g.symm_comp, map_id] @[simp] lemma map_symm_map (I : fractional_ideal S P') (g : P ≃ₐ[R] P') : (I.map (g.symm : P' →ₐ[R] P)).map (g : P →ₐ[R] P') = I := by rw [←map_comp, g.comp_symm, map_id] /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : P ≃ₐ[R] P') : fractional_ideal S P ≃+* fractional_ideal S P' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma coe_fun_map_equiv (g : P ≃ₐ[R] P') : (map_equiv g : fractional_ideal S P → fractional_ideal S P') = map g := rfl @[simp] lemma map_equiv_apply (g : P ≃ₐ[R] P') (I : fractional_ideal S P) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_symm (g : P ≃ₐ[R] P') : ((map_equiv g).symm : fractional_ideal S P' ≃+* _) = map_equiv g.symm := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal S P) := ring_equiv.ext (λ x, by simp) lemma is_fractional_span_iff {s : set P} : is_fractional S (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → is_integer R (a • b) := ⟨λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (by { rw smul_zero, exact is_integer_zero }) (λ x y hx hy, by { rw smul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw smul_comm, exact is_integer_smul hx })⟩⟩ include loc lemma is_fractional_of_fg {I : submodule R P} (hI : I.fg) : is_fractional S I := begin rcases hI with ⟨I, rfl⟩, rcases exist_integer_multiples_of_finset S I with ⟨⟨s, hs1⟩, hs⟩, rw is_fractional_span_iff, exact ⟨s, hs1, hs⟩, end omit loc lemma mem_span_mul_finite_of_mem_mul {I J : fractional_ideal S P} {x : P} (hx : x ∈ I * J) : ∃ (T T' : finset P), (T : set P) ⊆ I ∧ (T' : set P) ⊆ J ∧ x ∈ span R (T * T' : set P) := submodule.mem_span_mul_finite_of_mem_mul (by simpa using mem_coe.mpr hx) variables (S) lemma coe_ideal_fg (inj : function.injective (algebra_map R P)) (I : ideal R) : fg ((I : fractional_ideal S P) : submodule R P) ↔ fg I := coe_submodule_fg _ inj _ variables {S} lemma fg_unit (I : units (fractional_ideal S P)) : fg (I : submodule R P) := begin have : (1 : P) ∈ (I * ↑I⁻¹ : fractional_ideal S P), { rw units.mul_inv, exact one_mem_one _ }, obtain ⟨T, T', hT, hT', one_mem⟩ := mem_span_mul_finite_of_mem_mul this, refine ⟨T, submodule.span_eq_of_le _ hT _⟩, rw [← one_mul ↑I, ← mul_one (span R ↑T)], conv_rhs { rw [← fractional_ideal.coe_one, ← units.mul_inv I, fractional_ideal.coe_mul, mul_comm ↑↑I, ← mul_assoc] }, refine submodule.mul_le_mul_left (le_trans _ (submodule.mul_le_mul_right (submodule.span_le.mpr hT'))), rwa [submodule.one_le, submodule.span_mul_span] end lemma fg_of_is_unit (I : fractional_ideal S P) (h : is_unit I) : fg (I : submodule R P) := by { rcases h with ⟨I, rfl⟩, exact fg_unit I } lemma _root_.ideal.fg_of_is_unit (inj : function.injective (algebra_map R P)) (I : ideal R) (h : is_unit (I : fractional_ideal S P)) : I.fg := by { rw ← coe_ideal_fg S inj I, exact fg_of_is_unit I h } variables (S P P') include loc loc' /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `P` and in `P'` -/ @[irreducible] noncomputable def canonical_equiv : fractional_ideal S P ≃+* fractional_ideal S P' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _, ..ring_equiv_of_ring_equiv P P' (ring_equiv.refl R) (show S.map _ = S, by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } @[simp] lemma mem_canonical_equiv_apply {I : fractional_ideal S P} {x : P'} : x ∈ canonical_equiv S P P' I ↔ ∃ y ∈ I, is_localization.map P' (ring_hom.id R) (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) (y : P) = x := begin rw [canonical_equiv, map_equiv_apply, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ end @[simp] lemma canonical_equiv_symm : (canonical_equiv S P P').symm = canonical_equiv S P' P := ring_equiv.ext $ λ I, set_like.ext_iff.mpr $ λ x, by { rw [mem_canonical_equiv_apply, canonical_equiv, map_equiv_symm, map_equiv, ring_equiv.coe_mk, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ } @[simp] lemma canonical_equiv_flip (I) : canonical_equiv S P P' (canonical_equiv S P' P I) = I := by rw [←canonical_equiv_symm, ring_equiv.symm_apply_apply] end semiring section is_fraction_ring /-! ### `is_fraction_ring` section This section concerns fractional ideals in the field of fractions, i.e. the type `fractional_ideal R⁰ K` where `is_fraction_ring R K`. -/ variables {K K' : Type*} [field K] [field K'] variables [algebra R K] [is_fraction_ring R K] [algebra R K'] [is_fraction_ring R K'] variables {I J : fractional_ideal R⁰ K} (h : K →ₐ[R] K') /-- Nonzero fractional ideals contain a nonzero integer. -/ lemma exists_ne_zero_mem_is_integer [nontrivial R] (hI : I ≠ 0) : ∃ x ≠ (0 : R), algebra_map R K x ∈ I := begin obtain ⟨y, y_mem, y_not_mem⟩ := set_like.exists_of_lt (bot_lt_iff_ne_bot.mpr hI), have y_ne_zero : y ≠ 0 := by simpa using y_not_mem, obtain ⟨z, ⟨x, hx⟩⟩ := exists_integer_multiple R⁰ y, refine ⟨x, _, _⟩, { rw [ne.def, ← @is_fraction_ring.to_map_eq_zero_iff R _ K, hx, algebra.smul_def], exact mul_ne_zero (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors z.2) y_ne_zero }, { rw hx, exact smul_mem _ _ y_mem } end lemma map_ne_zero [nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := begin obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI, contrapose! x_ne_zero with map_eq_zero, refine is_fraction_ring.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)), exact ⟨algebra_map R K x, hx, h.commutes x⟩, end @[simp] lemma map_eq_zero_iff [nontrivial R] : I.map h = 0 ↔ I = 0 := ⟨imp_of_not_imp_not _ _ (map_ne_zero _), λ hI, hI.symm ▸ map_zero h⟩ lemma coe_ideal_injective : function.injective (coe : ideal R → fractional_ideal R⁰ K) := injective_of_le_imp_le _ (λ _ _, (coe_ideal_le_coe_ideal _).mp) @[simp] lemma coe_ideal_eq_zero_iff {I : ideal R} : (I : fractional_ideal R⁰ K) = 0 ↔ I = ⊥ := by { rw ← coe_to_fractional_ideal_bot, exact coe_ideal_injective.eq_iff } lemma coe_ideal_ne_zero_iff {I : ideal R} : (I : fractional_ideal R⁰ K) ≠ 0 ↔ I ≠ ⊥ := not_iff_not.mpr coe_ideal_eq_zero_iff lemma coe_ideal_ne_zero {I : ideal R} (hI : I ≠ ⊥) : (I : fractional_ideal R⁰ K) ≠ 0 := coe_ideal_ne_zero_iff.mpr hI end is_fraction_ring section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] variables [algebra R₁ K] [frac : is_fraction_ring R₁ K] instance : nontrivial (fractional_ideal R₁⁰ K) := ⟨⟨0, 1, λ h, have this : (1 : K) ∈ (0 : fractional_ideal R₁⁰ K) := by { rw ← (algebra_map R₁ K).map_one, simpa only [h] using coe_mem_one R₁⁰ 1 }, one_ne_zero ((mem_zero_iff _).mp this)⟩⟩ include frac lemma fractional_div_of_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : is_fractional R₁⁰ (I / J : submodule R₁ K) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := set_like.exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R₁).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : algebra_map R₁ K aJ * y = 0, { rw [← algebra.smul_def, ←hy', y'_eq_zero, ring_hom.map_zero] }, have y_zero := (mul_eq_zero.mp this).resolve_left (mt ((algebra_map R₁ K).injective_iff.1 (is_fraction_ring.injective _ _) _) (mem_non_zero_divisors_iff_ne_zero.mp haJ)), exact not_mem_zero ((mem_zero_iff R₁⁰).mpr y_zero) }, intros b hb, convert hI _ (hb _ (submodule.smul_mem _ aJ mem_J)) using 1, rw [← hy', mul_comm b, ← algebra.smul_def, mul_smul] end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal R₁⁰ K) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I / J, fractional_div_of_nonzero h⟩ ⟩ variables {I J : fractional_ideal R₁⁰ K} [ J ≠ 0 ] @[simp] lemma div_zero {I : fractional_ideal R₁⁰ K} : I / 0 = 0 := dif_pos rfl lemma div_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (I / J) = ⟨I / J, fractional_div_of_nonzero h⟩ := dif_neg h @[simp] lemma coe_div {I J : fractional_ideal R₁⁰ K} (hJ : J ≠ 0) : (↑(I / J) : submodule R₁ K) = ↑I / (↑J : submodule R₁ K) := begin unfold has_div.div, simp only [dif_neg hJ, coe_mk, val_eq_coe], end lemma mem_div_iff_of_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) {x} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by { rw div_nonzero h, exact submodule.mem_div_iff_forall_mul_mem } lemma mul_one_div_le_one {I : fractional_ideal R₁⁰ K} : I * (1 / I) ≤ 1 := begin by_cases hI : I = 0, { rw [hI, div_zero, mul_zero], exact zero_le 1 }, { rw [← coe_le_coe, coe_mul, coe_div hI, coe_one], apply submodule.mul_one_div_le_one }, end lemma le_self_mul_one_div {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * (1 / I) := begin by_cases hI_nz : I = 0, { rw [hI_nz, div_zero, mul_zero], exact zero_le 0 }, { rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one], rw [← coe_le_coe, coe_one] at hI, exact submodule.le_self_mul_one_div hI }, end lemma le_div_iff_of_nonzero {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ ∀ (x ∈ I) (y ∈ J'), x * y ∈ J := ⟨ λ h x hx, (mem_div_iff_of_nonzero hJ').mp (h hx), λ h x hx, (mem_div_iff_of_nonzero hJ').mpr (h x hx) ⟩ lemma le_div_iff_mul_le {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J := begin rw div_nonzero hJ', convert submodule.le_div_iff_mul_le using 1, rw [← coe_mul, coe_le_coe] end @[simp] lemma div_one {I : fractional_ideal R₁⁰ K} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal R₁⁰ K) _ _)], ext, split; intro h, { simpa using mem_div_iff_forall_mul_mem.mp h 1 ((algebra_map R₁ K).map_one ▸ coe_mem_one R₁⁰ 1) }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, rfl⟩, rw mul_comm, convert submodule.smul_mem _ y' h, exact (algebra.smul_def _ _).symm } end omit frac lemma ne_zero_of_mul_eq_one (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal R₁⁰ K) _ _ (by { convert h, simp [hI], }) include frac theorem eq_one_div_of_mul_eq_one (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = 1 / I := begin have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply mul_left_mono I, apply (le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact mul_mem_mul hx hy, end theorem mul_div_self_cancel_iff {I : fractional_ideal R₁⁰ K} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨(1 / I), h⟩, λ ⟨J, hJ⟩, by rwa [← eq_one_div_of_mul_eq_one I J hJ]⟩ variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_div (I J : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I / J).map (h : K →ₐ[R₁] K') = I.map h / J.map h := begin by_cases H : J = 0, { rw [H, div_zero, map_zero, div_zero] }, { apply coe_to_submodule_injective, simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] } end @[simp] lemma map_one_div (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (1 / I).map (h : K →ₐ[R₁] K') = 1 / I.map h := by rw [map_div, map_one] end quotient section field variables {R₁ K L : Type*} [integral_domain R₁] [field K] [field L] variables [algebra R₁ K] [is_fraction_ring R₁ K] [algebra K L] [is_fraction_ring K L] lemma eq_zero_or_one (I : fractional_ideal K⁰ L) : I = 0 ∨ I = 1 := begin rw or_iff_not_imp_left, intro hI, simp_rw [@set_like.ext_iff _ _ _ I 1, fractional_ideal.mem_one_iff], intro x, split, { intro x_mem, obtain ⟨n, d, rfl⟩ := is_localization.mk'_surjective K⁰ x, refine ⟨n / d, _⟩, rw [ring_hom.map_div, is_fraction_ring.mk'_eq_div] }, { rintro ⟨x, rfl⟩, obtain ⟨y, y_ne, y_mem⟩ := fractional_ideal.exists_ne_zero_mem_is_integer hI, rw [← div_mul_cancel x y_ne, ring_hom.map_mul, ← algebra.smul_def], exact submodule.smul_mem I _ y_mem } end lemma eq_zero_or_one_of_is_field (hF : is_field R₁) (I : fractional_ideal R₁⁰ K) : I = 0 ∨ I = 1 := by { letI : field R₁ := hF.to_field R₁, exact eq_zero_or_one I } end field section principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] variables [algebra R₁ K] [is_fraction_ring R₁ K] open_locale classical open submodule submodule.is_principal include loc lemma is_fractional_span_singleton (x : P) : is_fractional S (span R {x} : submodule R P) := let ⟨a, ha⟩ := exists_integer_multiple S x in is_fractional_span_iff.mpr ⟨a, a.2, λ x' hx', (set.mem_singleton_iff.mp hx').symm ▸ ha⟩ variables (S) /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ @[irreducible] def span_singleton (x : P) : fractional_ideal S P := ⟨span R {x}, is_fractional_span_singleton x⟩ local attribute [semireducible] span_singleton @[simp] lemma coe_span_singleton (x : P) : (span_singleton S x : submodule R P) = span R {x} := rfl @[simp] lemma mem_span_singleton {x y : P} : x ∈ span_singleton S y ↔ ∃ (z : R), z • y = x := submodule.mem_span_singleton lemma mem_span_singleton_self (x : P) : x ∈ span_singleton S x := (mem_span_singleton S).mpr ⟨1, one_smul _ _⟩ variables {S} lemma eq_span_singleton_of_principal (I : fractional_ideal S P) [is_principal (I : submodule R P)] : I = span_singleton S (generator (I : submodule R P)) := coe_to_submodule_injective (span_singleton_generator ↑I).symm lemma is_principal_iff (I : fractional_ideal S P) : is_principal (I : submodule R P) ↔ ∃ x, I = span_singleton S x := ⟨λ h, ⟨@generator _ _ _ _ _ ↑I h, @eq_span_singleton_of_principal _ _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton _ x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton S (0 : P) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm] } lemma span_singleton_eq_zero_iff {y : P} : span_singleton S y = 0 ↔ y = 0 := ⟨λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y), λ h, by simp [h] ⟩ lemma span_singleton_ne_zero_iff {y : P} : span_singleton S y ≠ 0 ↔ y ≠ 0 := not_congr span_singleton_eq_zero_iff @[simp] lemma span_singleton_one : span_singleton S (1 : P) = 1 := begin ext, refine (mem_span_singleton S).trans ((exists_congr _).trans (mem_one_iff S).symm), intro x', rw [algebra.smul_def, mul_one] end @[simp] lemma span_singleton_mul_span_singleton (x y : P) : span_singleton S x * span_singleton S y = span_singleton S (x * y) := begin apply coe_to_submodule_injective, simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul] end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(span R {x} : ideal R) : fractional_ideal S P) = span_singleton S (algebra_map R P x) := begin ext y, refine (mem_coe_ideal S).trans (iff.trans _ (mem_span_singleton S).symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hy', use x', rw [smul_eq_mul, ring_hom.map_mul, algebra.smul_def] }, { rintros ⟨y', rfl⟩, refine ⟨y' * x, submodule.mem_span_singleton.mpr ⟨y', rfl⟩, _⟩, rw [ring_hom.map_mul, algebra.smul_def] } end @[simp] lemma canonical_equiv_span_singleton {P'} [comm_ring P'] [algebra R P'] [is_localization S P'] (x : P) : canonical_equiv S P P' (span_singleton S x) = span_singleton S (is_localization.map P' (ring_hom.id R) (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) x) := begin apply set_like.ext_iff.mpr, intro y, split; intro h, { rw mem_span_singleton, obtain ⟨x', hx', rfl⟩ := (mem_canonical_equiv_apply _ _ _).mp h, obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp hx', use z, rw is_localization.map_smul, refl }, { rw mem_canonical_equiv_apply, obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp h, use z • x, use (mem_span_singleton _).mpr ⟨z, rfl⟩, simp [is_localization.map_smul] } end lemma mem_singleton_mul {x y : P} {I : fractional_ideal S P} : y ∈ span_singleton S x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply fractional_ideal.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := (mem_span_singleton S).mp hx', use [a • y', submodule.smul_mem I a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { exact ⟨0, submodule.zero_mem I, (mul_zero x).symm⟩ }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', submodule.add_mem I hy hy', (mul_add _ _ _).symm⟩ }, { rintros r _ ⟨y', hy', rfl⟩, exact ⟨r • y', submodule.smul_mem I r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul ((mem_span_singleton S).mpr ⟨1, one_smul _ _⟩) hy' } end omit loc lemma one_div_span_singleton (x : K) : 1 / span_singleton R₁⁰ x = span_singleton R₁⁰ (x⁻¹) := if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one _ _ (by simp [h])).symm @[simp] lemma div_span_singleton (J : fractional_ideal R₁⁰ K) (d : K) : J / span_singleton R₁⁰ d = span_singleton R₁⁰ (d⁻¹) * J := begin rw ← one_div_span_singleton, by_cases hd : d = 0, { simp only [hd, span_singleton_zero, div_zero, zero_mul] }, have h_spand : span_singleton R₁⁰ d ≠ 0 := mt span_singleton_eq_zero_iff.mp hd, apply le_antisymm, { intros x hx, rw [← mem_coe, coe_div h_spand, submodule.mem_div_iff_forall_mul_mem] at hx, specialize hx d (mem_span_singleton_self R₁⁰ d), have h_xd : x = d⁻¹ * (x * d), { field_simp }, rw [← mem_coe, coe_mul, one_div_span_singleton, h_xd], exact submodule.mul_mem_mul (mem_span_singleton_self R₁⁰ _) hx }, { rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_span_singleton, span_singleton_mul_span_singleton, inv_mul_cancel hd, span_singleton_one, mul_one], exact le_refl J }, end lemma exists_eq_span_singleton_mul (I : fractional_ideal R₁⁰ K) : ∃ (a : R₁) (aI : ideal R₁), a ≠ 0 ∧ I = span_singleton R₁⁰ (algebra_map R₁ K a)⁻¹ * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.is_fractional, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero : algebra_map R₁ K a_inv ≠ 0 := mt is_fraction_ring.to_map_eq_zero_iff.mp nonzero, refine ⟨a_inv, submodule.comap (algebra.linear_map R₁ K) ↑(span_singleton R₁⁰ (algebra_map R₁ K a_inv) * I), nonzero, ext (λ x, iff.trans ⟨_, _⟩ mem_singleton_mul.symm)⟩, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, rw algebra.smul_def at hx', refine ⟨algebra_map R₁ K x', (mem_coe_ideal _).mpr ⟨x', mem_singleton_mul.mpr _, rfl⟩, _⟩, { exact ⟨x, hx, hx'⟩ }, { rw [hx', ← mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] } }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := (mem_coe_ideal _).mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw algebra.linear_map_apply at hx', rwa [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] } end instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] [algebra R K] [is_fraction_ring R K] (I : fractional_ideal R⁰ K) : (I : submodule R K).is_principal := begin obtain ⟨a, aI, -, ha⟩ := exists_eq_span_singleton_mul I, use (algebra_map R K a)⁻¹ * algebra_map R K (generator aI), suffices : I = span_singleton R⁰ ((algebra_map R K a)⁻¹ * algebra_map R K (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end end principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] variables {K : Type*} [field K] [algebra R₁ K] [frac : is_fraction_ring R₁ K] local attribute [instance] classical.prop_decidable lemma is_noetherian_zero : is_noetherian R₁ (0 : fractional_ideal R₁⁰ K) := is_noetherian_submodule.mpr (λ I (hI : I ≤ (0 : fractional_ideal R₁⁰ K)), by { rw coe_zero at hI, rw le_bot_iff.mp hI, exact fg_bot }) lemma is_noetherian_iff {I : fractional_ideal R₁⁰ K} : is_noetherian R₁ I ↔ ∀ J ≤ I, (J : submodule R₁ K).fg := is_noetherian_submodule.trans ⟨λ h J hJ, h _ hJ, λ h J hJ, h ⟨J, is_fractional_of_le hJ⟩ hJ⟩ lemma is_noetherian_coe_to_fractional_ideal [_root_.is_noetherian_ring R₁] (I : ideal R₁) : is_noetherian R₁ (I : fractional_ideal R₁⁰ K) := begin rw is_noetherian_iff, intros J hJ, obtain ⟨J, rfl⟩ := le_one_iff_exists_coe_ideal.mp (le_trans hJ coe_ideal_le_one), exact fg_map (is_noetherian.noetherian J), end include frac lemma is_noetherian_span_singleton_inv_to_map_mul (x : R₁) {I : fractional_ideal R₁⁰ K} (hI : is_noetherian R₁ I) : is_noetherian R₁ (span_singleton R₁⁰ (algebra_map R₁ K x)⁻¹ * I : fractional_ideal R₁⁰ K) := begin by_cases hx : x = 0, { rw [hx, ring_hom.map_zero, _root_.inv_zero, span_singleton_zero, zero_mul], exact is_noetherian_zero }, have h_gx : algebra_map R₁ K x ≠ 0, from mt ((algebra_map R₁ K).injective_iff.mp (is_fraction_ring.injective _ _) x) hx, have h_spanx : span_singleton R₁⁰ (algebra_map R₁ K x) ≠ 0, from span_singleton_ne_zero_iff.mpr h_gx, rw is_noetherian_iff at ⊢ hI, intros J hJ, rw [← div_span_singleton, le_div_iff_mul_le h_spanx] at hJ, obtain ⟨s, hs⟩ := hI _ hJ, use s * {(algebra_map R₁ K x)⁻¹}, rw [finset.coe_mul, finset.coe_singleton, ← span_mul_span, hs, ← coe_span_singleton R₁⁰, ← coe_mul, mul_assoc, span_singleton_mul_span_singleton, mul_inv_cancel h_gx, span_singleton_one, mul_one], end /-- Every fractional ideal of a noetherian integral domain is noetherian. -/ theorem is_noetherian [_root_.is_noetherian_ring R₁] (I : fractional_ideal R₁⁰ K) : is_noetherian R₁ I := begin obtain ⟨d, J, h_nzd, rfl⟩ := exists_eq_span_singleton_mul I, apply is_noetherian_span_singleton_inv_to_map_mul, apply is_noetherian_coe_to_fractional_ideal, end section adjoin include loc omit frac variables {R P} (S) (x : P) (hx : is_integral R x) /-- `A[x]` is a fractional ideal for every integral `x`. -/ lemma is_fractional_adjoin_integral : is_fractional S (algebra.adjoin R ({x} : set P)).to_submodule := is_fractional_of_fg (fg_adjoin_singleton_of_integral x hx) /-- `fractional_ideal.adjoin_integral (S : submonoid R) x hx` is `R[x]` as a fractional ideal, where `hx` is a proof that `x : P` is integral over `R`. -/ @[simps] def adjoin_integral : fractional_ideal S P := ⟨_, is_fractional_adjoin_integral S x hx⟩ lemma mem_adjoin_integral_self : x ∈ adjoin_integral S x hx := algebra.subset_adjoin (set.mem_singleton x) end adjoin end fractional_ideal
628fa139086e8b810184bc9e16def404cd554733
022547453607c6244552158ff25ab3bf17361760
/src/algebra/big_operators/basic.lean
2b7b5ed774c4d06d823aa0562f585f6f3ecb0930
[ "Apache-2.0" ]
permissive
1293045656/mathlib
5f81741a7c1ff1873440ec680b3680bfb6b7b048
4709e61525a60189733e72a50e564c58d534bed8
refs/heads/master
1,687,010,200,553
1,626,245,646,000
1,626,245,646,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,207
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finset.fold import data.equiv.mul_add import tactic.abel /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) ## Implementation Notes The first arguments in all definitions and lemmas is the codomain of the function of the big operator. This is necessary for the heuristic in `@[to_additive]`. See the documentation of `to_additive.attr` for more information. -/ universes u v w variables {β : Type u} {α : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs : s.nodup) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl end finset /-- There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ library_note "operator precedence of big operators" localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = s.fold (*) 1 f := rfl @[simp] lemma sum_multiset_singleton (s : finset α) : s.sum (λ x, x ::ₘ 0) = s.val := by simp [sum_eq_multiset_sum] end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [non_assoc_semiring β] [non_assoc_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s @[to_additive] lemma monoid_hom.coe_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) : ⇑(∏ x in s, f x) = ∏ x in s, f x := (monoid_hom.coe_fn β γ).map_prod _ _ -- See also `finset.prod_apply`, with the same conclusion -- but with the weaker hypothesis `f : α → β → γ`. @[simp, to_additive] lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b := (monoid_hom.eval b).map_prod _ _ variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} namespace finset section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100, to_additive] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm end comm_monoid end finset section open finset variables [fintype α] [decidable_eq α] [comm_monoid β] @[to_additive] lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) : (∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i := (finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl end namespace finset section comm_monoid variables [comm_monoid β] @[to_additive] lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i := is_compl_compl.prod_mul_prod f @[to_additive] lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i := is_compl_compl.symm.prod_mul_prod f @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_map, prod_map], { simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply, sum.elim_inr] }, { simp only [disjoint_left, finset.mem_map, finset.mem_map], rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩, cases H } end @[to_additive] lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bUnion_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bUnion s t), from (disjoint_bUnion_right _ _ _).mpr this, by simp only [bUnion_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bUnion, prod_bUnion], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end /-- An uncurried version of `finset.prod_product`. -/ @[to_additive "An uncurried version of `finset.sum_product`"] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product /-- Product over a sigma type equals the product of fiberwise products. For rewriting in the reverse direction, use `finset.prod_sigma'`. -/ @[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `finset.sum_sigma'`"] lemma prod_sigma {σ : α → Type*} (s : finset α) (t : Πa, finset (σ a)) (f : sigma σ → β) : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bUnion (λa, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_sigma' {σ : α → Type*} (s : finset α) (t : Πa, finset (σ a)) (f : Πa, σ a → β) : (∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 := eq.symm $ prod_sigma s t (λ x, f x.1 x.2) @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bUnion $ λ x' hx y' hy hne, _).symm, rw [disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = ∏ x in s.filter (λc', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : (∏ x in s, g (f x)) = g (∏ x in s, f x) := ((monoid_hom.of g).map_prod f s).symm @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1, from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _ _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λx, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset _ s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a := begin haveI := classical.dec_eq α, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, prod_eq_single_of_mem a this h₀) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; let s' := ({a, b} : finset α), have hu : s' ⊆ s, { refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb }, have hf : ∀ c ∈ s, c ∉ s' → f c = 1, { intros c hc hcs, apply h₀ c hc, apply not_or_distrib.mp, intro hab, apply hcs, apply mem_insert.mpr, rw mem_singleton, exact hab }, rw ←prod_subset hu hf, exact finset.prod_pair hn end @[to_additive] lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s, { exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ }, { rw [hb h₂, mul_one], apply prod_eq_single_of_mem a h₁, exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ }, { rw [ha h₁, one_mul], apply prod_eq_single_of_mem b h₂, exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ }, { rw [ha h₁, hb h₂, mul_one], exact trans (prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩)) prod_const_one } end @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_finset_coe (f : α → β) (s : finset α) : ∏ (i : (s : set α)), f i = ∏ i in s, f i := prod_attach @[to_additive] lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α) (h : ∀ x, x ∈ s ↔ p x) (f : α → β) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, by { substI p, rw [←prod_finset_coe], congr } @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := by letI := classical.dec_eq α; exact calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) : by rw [filter_union_filter_neg_eq] ... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) := by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] } @[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) := by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa } @[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) := by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h } @[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) := by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h } @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) @[to_additive] lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) : (∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x := apply_ite (λ s, ∏ x in s, f x) _ _ _ @[simp, to_additive] lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β): (∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x := by { split_ifs with h; refl } @[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M] (i : ι) (x : M) (s : finset ι) : ∑ j in s, pi.single i x j = if i ∈ s then x else 0 := sum_dite_eq' _ _ _ @[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*} [decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) : ∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 := sum_dite_eq _ _ _ /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive " Reorder a sum. The difference with `sum_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. "] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive " Reorder a sum. The difference with `sum_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. "] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (j : Πa∈t, α) (hj : ∀a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (i_inj : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (i_surj : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λx, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λx, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end @[to_additive] lemma prod_range_succ_comm (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = f n * ∏ x in range n, f x := by rw [range_succ, prod_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n := by simp only [mul_comm, prod_range_succ_comm] @[to_additive] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := prod_range_succ _ _ | (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ] @[to_additive] lemma eventually_constant_prod {u : ℕ → β} {N : ℕ} (hu : ∀ n ≥ N, u n = 1) {n : ℕ} (hn : N ≤ n) : ∏ k in range (n + 1), u k = ∏ k in range (N + 1), u k := begin obtain ⟨m, rfl : n = N + m⟩ := le_iff_exists_add.mp hn, clear hn, induction m with m hm, { simp }, erw [prod_range_succ, hm], simp [hu] end @[to_additive] lemma prod_range_add (f : ℕ → β) (n m : ℕ) : ∏ x in range (n + m), f x = (∏ x in range n, f x) * (∏ x in range m, f (n + x)) := begin induction m with m hm, { simp }, { rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], }, end @[to_additive] lemma prod_range_zero (f : ℕ → β) : ∏ k in range 0, f k = 1 := by rw [range_zero, prod_empty] @[to_additive sum_range_one] lemma prod_range_one (f : ℕ → β) : ∏ k in range 1, f k = f 0 := by { rw [range_one], apply @prod_singleton β ℕ 0 f } open multiset lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := begin apply s.induction_on, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, intros a s ih, simp only [prod_cons, map_cons, to_finset_cons, ih], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx end lemma sum_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [add_comm_monoid M] (f : α → M) : (s.map f).sum = ∑ m in s.to_finset, s.count m • f m := @prod_multiset_map_count _ _ _ (multiplicative M) _ f attribute [to_additive] prod_multiset_map_count @[to_additive] lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw map_id } /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty]) (multiset.forall_mem_map_iff.mpr p_s) /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; abel, simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; abel, simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub (additive M) _ f n @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub' (additive M) _ f n /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁], end @[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b | 0 := by simp | (n+1) := by simp lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : ∏ x in s, f x ^ n = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) @[to_additive] lemma prod_flip {n : ℕ} (f : ℕ → β) : ∏ r in range (n + 1), f (n - r) = ∏ k in range (n + 1), f k := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n)], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h : ∀ a ha, f a * f (g a ha) = 1) (g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (g_mem : ∀ a ha, g a ha ∈ s) (g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h g_ne g_mem g_inv, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h y (hmem y hy)) (λ y hy, g_ne y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩) (λ y hy, g_inv y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ hy, hy.symm ▸ hx1) (λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/ lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _ ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x := by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] } @[to_additive] lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i := by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] } @[to_additive] lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i := prod_eq_mul_prod_diff_singleton (mem_univ a) f @[to_additive] lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (∏ i in {a}ᶜ, f i) * f a := prod_eq_prod_diff_singleton_mul (mem_univ a) f /-- A product can be partitioned into a product of products, each equivalent under a setoid. -/ @[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."] lemma prod_partition (R : setoid α) [decidable_rel R.r] : (∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y := begin refine (finset.prod_image' f (λ x hx, _)).symm, refl, end /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin rw [prod_partition R, ←finset.prod_eq_one], intros xbar xbar_in_s, obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s, end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λj hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ @[to_additive eq_of_card_le_one_of_sum_eq "If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum."] lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _), rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : (∑ x in s, n • (f x)) = n • ((∑ x in s, f x)) := @prod_pow (multiplicative β) _ _ _ _ _ attribute [to_additive sum_nsmul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : (∑ x in s, b) = s.card • b := @prod_const (multiplicative β) _ _ _ _ attribute [to_additive] prod_const lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [non_assoc_semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] @[norm_cast] lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s @[norm_cast] lemma sum_int_cast [add_comm_group β] [has_one β] (s : finset α) (f : α → ℤ) : ↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) := (int.cast_add_hom β).map_sum f s lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card • (f b) := @prod_comp (multiplicative β) _ _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp lemma eq_sum_range_sub [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = f 0 + ∑ i in range n, (f (i+1) - f i) := by { rw finset.sum_range_sub, abel } lemma eq_sum_range_sub' [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = ∑ i in range (n + 1), if i = 0 then f 0 else f i - f (i - 1) := begin conv_lhs { rw [finset.eq_sum_range_sub f] }, simp [finset.sum_range_succ', add_comm] end section opposite open opposite /-- Moving to the opposite additive commutative monoid commutes with summing. -/ @[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) : op (∑ x in s, f x) = ∑ x in s, op (f x) := (op_add_equiv : β ≃+ βᵒᵖ).map_sum _ _ @[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) : unop (∑ x in s, f x) = ∑ x in s, unop (f x) := (op_add_equiv : β ≃+ βᵒᵖ).symm.map_sum _ _ end opposite section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bUnion t).card = ∑ u in s, card (t u) := calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h ... = ∑ u in s, card (t u) : by simp lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bUnion t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card : by rw bUnion_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) := (s.sum_hom (gsmul z)).symm @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := by simpa only [sub_eq_add_neg] using sum_add_distrib.trans (congr_arg _ sum_neg_distrib) section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by haveI := classical.dec_eq α; calc (∏ x in s, f x) = ∏ x in insert a (erase s a), f x : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃a∈s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero section comm_group_with_zero variables [comm_group_with_zero β] @[simp] lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := begin classical, by_cases h : ∃ x ∈ s, f x = 0, { simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h }, { push_neg at h, have h' := prod_ne_zero_iff.mpr h, have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx), apply mul_right_cancel' h', simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] } end end comm_group_with_zero end finset namespace fintype open finset /-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`. See `function.bijective.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts `function.bijective`. See `function.bijective.sum_comp` for a version without `h`. "] lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bij (λ x _, e x) (λ x _, mem_univ (e x)) (λ x _, h x) (λ x x' _ _ h, he.injective h) (λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩) /-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that automatically fills in most arguments. See `equiv.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that automatically fills in most arguments. See `equiv.sum_comp` for a version without `h`. "] lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bijective e e.bijective f g h @[to_additive] lemma prod_finset_coe [comm_monoid β] : ∏ (i : (s : set α)), f i = ∏ i in s, f i := (finset.prod_subtype s (λ _, iff.rfl) f).symm end fintype namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset lemma abs_sum_le_sum_abs [linear_ordered_add_comm_group α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } @[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a • (a ::ₘ 0)) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s • (b ::ₘ 0)), { rw [singleton_coe, count_nsmul, ← singleton_coe, count_singleton, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_nsmul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), k ∣ multiset.count a s) : ∃ (u : multiset α), s = k • u := begin use ∑ a in s.to_finset, (s.count a / k) • (a ::ₘ 0), have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • (x ::ₘ 0) = ∑ (x : α) in s.to_finset, count x s • (x ::ₘ 0), { refine congr_arg s.to_finset.sum _, apply funext, intro x, rw [← mul_nsmul, nat.mul_div_cancel' (h x)] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq] end end multiset @[simp, norm_cast] lemma nat.coe_prod {R : Type*} [comm_semiring R] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (nat.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma int.coe_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _ lemma nat_abs_sum_le {ι : Type*} (s : finset ι) (f : ι → ℤ) : (∑ i in s, f i).nat_abs ≤ ∑ i in s, (f i).nat_abs := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty, int.nat_abs_zero] }, { intros i s his IH, simp only [his, finset.sum_insert, not_false_iff], exact (int.nat_abs_add_le _ _).trans (add_le_add le_rfl IH) } end
7a133aed184056c25c28012ca9f23cb8b3d55c24
367134ba5a65885e863bdc4507601606690974c1
/src/order/filter/at_top_bot.lean
5f1ecbd476efa95135488b609d4430920b06b0d4
[ "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
56,771
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, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases import data.finset.preimage /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 (Ici a) /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 (Iic a) lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_sets a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis (order_dual α) _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' (order_dual α) _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.ne_bot_iff.2 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot (order_dual α) _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets (order_dual α) _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma eventually_gt_at_top [preorder α] [no_top_order α] (a : α) : ∀ᶠ x in at_top, a < x := Ioi_mem_at_top a lemma eventually_lt_at_bot [preorder α] [no_bot_order α] (a : α) : ∀ᶠ x in at_bot, x < a := Iio_mem_at_bot a lemma at_top_basis_Ioi [nonempty α] [semilattice_sup α] [no_top_order α] : (@at_top α _).has_basis (λ _, true) Ioi := at_top_basis.to_has_basis (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) $ λ a ha, (no_top a).imp $ λ b hb, ⟨ha, Ici_subset_Ioi.2 hb⟩ lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := countable_encodable _, .. at_bot_basis } lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] : (at_top : filter $ α).is_countably_generated := at_top_countable_basis.is_countably_generated lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] : (at_bot : filter $ α).is_countably_generated := at_bot_countable_basis.is_countably_generated lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq (order_dual α) _ @[nontriviality] lemma subsingleton.at_top_eq (α) [subsingleton α] [preorder α] : (at_top : filter α) = ⊤ := begin refine top_unique (λ s hs x, _), letI : unique α := ⟨⟨x⟩, λ y, subsingleton.elim y x⟩, rw [at_top, infi_unique, unique.default_eq x, mem_principal_sets] at hs, exact hs left_mem_Ici end @[nontriviality] lemma subsingleton.at_bot_eq (α) [subsingleton α] [preorder α] : (at_bot : filter α) = ⊤ := subsingleton.at_top_eq (order_dual α) lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure (order_dual α) _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp [at_top_basis.frequently_iff] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top (order_dual α) _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := by simp [at_top_basis_Ioi.frequently_iff] lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' (order_dual α) _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq (order_dual α) _ _ _ _ lemma tendsto_at_top [preorder β] {m : α → β} {f : filter α} : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_Ici] lemma tendsto_at_bot [preorder β] {m : α → β} {f : filter α} : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, tendsto_at_top.2 $ λ b, mp_sets (tendsto_at_top.1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ (order_dual β) _ _ _ _ h /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b ≤ u a' := begin have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b < u a' := begin cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin intros N, let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N} have Ane : A.nonempty, from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩, let M := finset.max' A Ane, have ex : ∃ n ≥ N, M < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M, { use nat.find ex, rw ← and_assoc, split, { simpa using nat.find_spec ex }, { intros k hk hk', simpa [hk] using nat.find_min ex hk' } }, use [n, hnN], intros k hk, by_cases H : k ≤ N, { have : u k ∈ A, from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H), have : u k ≤ M, from finset.le_max' A (u k) this, exact lt_of_le_of_lt this hnM }, { push_neg at H, calc u k ≤ M : hn_min k (le_of_lt H) hk ... < u n : hnM }, end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores (order_dual β) _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores (order_dual β) _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (tendsto_at_top.mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg lemma tendsto.nsmul_at_top (hf : tendsto f l at_top) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n •ℕ f x) l at_top := tendsto_at_top.2 $ λ y, (tendsto_at_top.1 hf y).mp $ (tendsto_at_top.1 hf 0).mono $ λ x h₀ hy, calc y ≤ f x : hy ... = 1 •ℕ f x : (one_nsmul _).symm ... ≤ n •ℕ f x : nsmul_le_nsmul h₀ hn lemma tendsto.nsmul_at_bot (hf : tendsto f l at_bot) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n •ℕ f x) l at_bot := @tendsto.nsmul_at_top α (order_dual β) _ l f hf n hn lemma tendsto_bit0_at_top : tendsto bit0 (at_top : filter β) at_top := tendsto_at_top_add tendsto_id tendsto_id lemma tendsto_bit0_at_bot : tendsto bit0 (at_bot : filter β) at_bot := tendsto_at_bot_add tendsto_id tendsto_id end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_neg_at_top_at_bot : tendsto (has_neg.neg : β → β) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top : tendsto (has_neg.neg : β → β) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual β) _ end ordered_group section ordered_semiring variables [ordered_semiring α] {l : filter β} {f g : β → α} lemma tendsto_bit1_at_top : tendsto bit1 (at_top : filter α) at_top := tendsto_at_top_add_nonneg_right tendsto_bit0_at_top (λ _, zero_le_one) lemma tendsto.at_top_mul_at_top (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_top := begin refine tendsto_at_top_mono' _ _ hg, filter_upwards [hg.eventually (eventually_ge_at_top 0), hf.eventually (eventually_ge_at_top 1)], exact λ x, le_mul_of_one_le_left end lemma tendsto_mul_self_at_top : tendsto (λ x : α, x * x) at_top at_top := tendsto_id.at_top_mul_at_top tendsto_id /-- The monomial function `x^n` tends to `+∞` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_at_top`. -/ lemma tendsto_pow_at_top {n : ℕ} (hn : 1 ≤ n) : tendsto (λ x : α, x ^ n) at_top at_top := begin refine tendsto_at_top_mono' _ ((eventually_ge_at_top 1).mono $ λ x hx, _) tendsto_id, simpa only [pow_one] using pow_le_pow hx hn end end ordered_semiring lemma zero_pow_eventually_eq [monoid_with_zero α] : (λ n : ℕ, (0 : α) ^ n) =ᶠ[at_top] (λ n, 0) := eventually_at_top.2 ⟨1, λ n hn, zero_pow (zero_lt_one.trans_le hn)⟩ section ordered_ring variables [ordered_ring α] {l : filter β} {f g : β → α} lemma tendsto.at_top_mul_at_bot (hf : tendsto f l at_top) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_bot := have _ := (hf.at_top_mul_at_top $ tendsto_neg_at_bot_at_top.comp hg), by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_top (hf : tendsto f l at_bot) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_bot := have tendsto (λ x, (-f x) * g x) l at_top := ( (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top hg), by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_bot (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_top := have tendsto (λ x, (-f x) * (-g x)) l at_top := (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top (tendsto_neg_at_bot_at_top.comp hg), by simpa only [neg_mul_neg] using this end ordered_ring section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_top_at_top : tendsto (abs : α → α) at_top at_top := tendsto_at_top_mono le_abs_self tendsto_id /-- $\lim_{x\to-\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_bot_at_top : tendsto (abs : α → α) at_bot at_top := tendsto_at_top_mono neg_le_abs_self tendsto_neg_at_bot_at_top end linear_ordered_add_comm_group section linear_ordered_semiring variables [linear_ordered_semiring α] {l : filter β} {f : β → α} lemma tendsto.at_top_of_const_mul {c : α} (hc : 0 < c) (hf : tendsto (λ x, c * f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (c * b)).mono $ λ x hx, le_of_mul_le_mul_left hx hc lemma tendsto.at_top_of_mul_const {c : α} (hc : 0 < c) (hf : tendsto (λ x, f x * c) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (b * c)).mono $ λ x hx, le_of_mul_le_mul_right hx hc end linear_ordered_semiring lemma nonneg_of_eventually_pow_nonneg [linear_ordered_ring α] {a : α} (h : ∀ᶠ n in at_top, 0 ≤ a ^ (n : ℕ)) : 0 ≤ a := let ⟨n, hn⟩ := (tendsto_bit1_at_top.eventually h).exists in pow_bit1_nonneg_iff.1 hn section linear_ordered_field variables [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.const_mul_at_top'` instead. -/ lemma tendsto.const_mul_at_top (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := tendsto.at_top_of_const_mul (inv_pos.2 hr) $ by simpa only [inv_mul_cancel_left' hr.ne'] /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.at_top_mul_const'` instead. -/ lemma tendsto.at_top_mul_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := by simpa only [mul_comm] using hf.const_mul_at_top hr /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ lemma tendsto.at_top_div_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x / r) l at_top := hf.at_top_mul_const (inv_pos.2 hr) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the left) tends to negative infinity. -/ lemma tendsto.neg_const_mul_at_top (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.const_mul_at_top (neg_pos.2 hr)) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the right) tends to negative infinity. -/ lemma tendsto.at_top_mul_neg_const (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, f x * r) l at_bot := by simpa only [mul_comm] using hf.neg_const_mul_at_top hr /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to negative infinity. -/ lemma tendsto.const_mul_at_bot (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).const_mul_at_top hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to negative infinity. -/ lemma tendsto.at_bot_mul_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x * r) l at_bot := by simpa only [mul_comm] using hf.const_mul_at_bot hr /-- If a function tends to negative infinity along a filter, then this function divided by a positive constant also tends to negative infinity. -/ lemma tendsto.at_bot_div_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x / r) l at_bot := hf.at_bot_mul_const (inv_pos.2 hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the left) tends to positive infinity. -/ lemma tendsto.neg_const_mul_at_bot (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, r * f x) l at_top := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_bot_at_top.comp (hf.const_mul_at_bot (neg_pos.2 hr)) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the right) tends to positive infinity. -/ lemma tendsto.at_bot_mul_neg_const (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, f x * r) l at_top := by simpa only [mul_comm] using hf.neg_const_mul_at_bot hr lemma tendsto_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : 0 < c) : tendsto (λ x, c * x^n) at_top at_top := tendsto.const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_neg_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : c < 0) : tendsto (λ x, c * x^n) at_top at_bot := tendsto.neg_const_mul_at_top hc (tendsto_pow_at_top hn) end linear_ordered_field open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ (order_dual β) _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := tendsto_at_top_at_top.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := tendsto_at_bot_at_bot.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin refine ⟨_, (tendsto_at_top_at_top_of_monotone (λ b₁ b₂, (hm b₁ b₂).2) hu).comp⟩, rw [tendsto_at_top, tendsto_at_top], exact λ hc b, (hc (e b)).mono (λ a, (hm b (f a)).1) end /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := @tendsto_at_top_embedding α (order_dual β) (order_dual γ) _ _ f e l (function.swap hm) hu lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_iff.2 _), refine ⟨↑s, s.finite_to_set, _, λ i, mem_principal_self _, _⟩, simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin by_cases ne : nonempty β₁ ∧ nonempty β₂, { cases ne, resetI, simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm }, { rw not_and_distrib at ne, cases ne; { have : ¬ (nonempty (β₁ × β₂)), by simp [ne], rw [at_top.filter_eq_bot_of_not_nonempty ne, at_top.filter_eq_bot_of_not_nonempty this], simp only [bot_prod, prod_bot] } } end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _ /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_Ici, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.order_dual gc hgi lemma map_coe_at_top_of_Ici_subset [semilattice_sup α] {a : α} {s : set α} (h : Ici a ⊆ s) : map (coe : s → α) at_top = at_top := begin have : directed (≥) (λ x : s, 𝓟 (Ici x)), { intros x y, use ⟨x ⊔ y ⊔ a, h le_sup_right⟩, simp only [ge_iff_le, principal_mono, Ici_subset_Ici, ← subtype.coe_le_coe, subtype.coe_mk], exact ⟨le_sup_left.trans le_sup_left, le_sup_right.trans le_sup_left⟩ }, haveI : nonempty s := ⟨⟨a, h le_rfl⟩⟩, simp only [le_antisymm_iff, at_top, le_infi_iff, le_principal_iff, mem_map, mem_set_of_eq, map_infi_eq this, map_principal], split, { intro x, refine mem_sets_of_superset (mem_infi_sets ⟨x ⊔ a, h le_sup_right⟩ (mem_principal_self _)) _, rintro _ ⟨y, hy, rfl⟩, exact le_trans le_sup_left (subtype.coe_le_coe.2 hy) }, { intro x, filter_upwards [mem_at_top (↑x ⊔ a)], intros b hb, exact ⟨⟨b, h $ le_sup_right.trans hb⟩, subtype.coe_le_coe.1 (le_sup_left.trans hb), rfl⟩ } end /-- The image of the filter `at_top` on `Ici a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ici_at_top [semilattice_sup α] (a : α) : map (coe : Ici a → α) at_top = at_top := map_coe_at_top_of_Ici_subset (subset.refl _) /-- The image of the filter `at_top` on `Ioi a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] (a : α) : map (coe : Ioi a → α) at_top = at_top := begin rcases no_top a with ⟨b, hb⟩, exact map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb) end /-- The `at_top` filter for an open interval `Ioi a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ioi_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ioi a → α) at_top := begin nontriviality, rcases nontrivial_iff_nonempty.1 ‹_› with ⟨b, hb⟩, rw [← map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb), comap_map subtype.coe_injective] end /-- The `at_top` filter for an open interval `Ici a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ici_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ici a → α) at_top := by rw [← map_coe_Ici_at_top a, comap_map subtype.coe_injective] /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] (a : α) : map (coe : Iio a → α) at_bot = at_bot := @map_coe_Ioi_at_top (order_dual α) _ _ _ /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iio_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iio a → α) at_bot := @at_top_Ioi_eq (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iic_at_bot [semilattice_inf α] (a : α) : map (coe : Iic a → α) at_bot = at_bot := @map_coe_Ici_at_top (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iic_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iic a → α) at_bot := @at_top_Ici_eq (order_dual α) _ _ lemma tendsto_Ioi_at_top [semilattice_sup α] {a : α} {f : β → Ioi a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ioi_eq, tendsto_comap_iff] lemma tendsto_Iio_at_bot [semilattice_inf α] {a : α} {f : β → Iio a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iio_eq, tendsto_comap_iff] lemma tendsto_Ici_at_top [semilattice_sup α] {a : α} {f : β → Ici a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ici_eq, tendsto_comap_iff] lemma tendsto_Iic_at_bot [semilattice_inf α] {a : α} {f : β → Iic a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iic_eq, tendsto_comap_iff] @[simp] lemma tendsto_comp_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ioi a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ioi_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ici_at_top [semilattice_sup α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ici a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ici_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iio a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iio_at_bot a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iic_at_bot [semilattice_inf α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iic a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iic_at_bot a, tendsto_map'_iff] lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.order_dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.order_dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := (at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi, ⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩ namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_basis with ⟨g, gbasis, gmon, -⟩, contrapose, simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { exact (at_top_basis.tendsto_iff gbasis).2 (λ i _, ⟨i, trivial, λ j hj, gmon trivial trivial hj (h j).1⟩) }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin rcases hf.exists_antimono_basis with ⟨B, h⟩, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp $ strict_mono_tendsto_at_top hψ⟩, end end is_countably_generated end filter open filter finset section variables {R : Type*} [linear_ordered_semiring R] lemma exists_lt_mul_self (a : R) : ∃ x ≥ 0, a < x * x := let ⟨x, hxa, hx0⟩ :=((tendsto_mul_self_at_top.eventually (eventually_gt_at_top a)).and (eventually_ge_at_top 0)).exists in ⟨x, hx0, hxa⟩ lemma exists_le_mul_self (a : R) : ∃ x ≥ 0, a ≤ x * x := let ⟨x, hx0, hxa⟩ := exists_lt_mul_self a in ⟨x, hx0, hxa.le⟩ end namespace order_iso variables [preorder α] [preorder β] @[simp] lemma comap_at_top (e : α ≃o β) : comap e at_top = at_top := by simp [at_top, ← e.surjective.infi_comp] @[simp] lemma comap_at_bot (e : α ≃o β) : comap e at_bot = at_bot := e.dual.comap_at_top @[simp] lemma map_at_top (e : α ≃o β) : map ⇑e at_top = at_top := by rw [← e.comap_at_top, map_comap_of_surjective e.surjective] @[simp] lemma map_at_bot (e : α ≃o β) : map ⇑e at_bot = at_bot := e.dual.map_at_top lemma tendsto_at_top (e : α ≃o β) : tendsto e at_top at_top := e.map_at_top.le lemma tendsto_at_bot (e : α ≃o β) : tendsto e at_bot at_bot := e.map_at_bot.le @[simp] lemma tendsto_at_top_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_top ↔ tendsto f l at_top := by rw [← e.comap_at_top, tendsto_comap_iff] @[simp] lemma tendsto_at_bot_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_bot ↔ tendsto f l at_bot := e.dual.tendsto_at_top_iff end order_iso /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
4d6a02ba378e3670ba8885fccffb941236da72aa
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/rewrite_search/search.lean
41ed34462976385e67a315793d7c163840acd894
[ "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,650
lean
/- Copyright (c) 2020 Kevin Lacker, Keeley Hoek, Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker, Keeley Hoek, Scott Morrison -/ import data.buffer.basic import meta.rb_map import tactic.rewrite_search.discovery import tactic.rewrite_search.types /-! # The graph algorithm part of rewrite search `search.lean` contains the logic to do a graph search. The search algorithm starts with an equation to prove, treats the left hand side and right hand side as two vertices in a graph, and uses rewrite rules to find a path that connects the two sides. -/ open tactic namespace tactic.rewrite_search /-- An edge represents a proof that can get from one expression to another. It represents the fact that, starting from the vertex `fr`, the expression in `proof` can prove the vertex `to`. `how` contains information that the explainer will use to generate Lean code for the proof. -/ meta structure edge := (from_id to_id : ℕ) (proof : tactic expr) (how : how) /-- Converting an edge to a human-readable string. -/ meta def edge.to_string : edge → format | e := format!"{e.from_id} → {e.to_id}" meta instance edge.has_to_format : has_to_format edge := ⟨edge.to_string⟩ /-- A vertex represents an expression that is equivalent to either the left or right side of our initial equation. * `id` is a numerical id used to refer to this vertex in the context of a single graph. * `exp` is the expression this vertex represents. * `pp` is the string format of the expression; we store this in the vertex to avoid recalculating it. * `side` is whether this vertex descends from the left or right side of the equation. * `parent` is the edge that originally added this vertex to the graph. -/ meta structure vertex := (id : ℕ) (exp : expr) (pp : string) (side : side) (parent : option edge) /-- The graph represents two trees, one descending from each of the left and right sides of our initial equation. * `conf` and `rules` determine what rewrites are used to generate new graph vertices. Here, the format of a rewrite rule is an expression for rewriting, plus a flag for the direction to apply it in. * `vertices` maps vertex.id to vertex. * `vmap` maps vertex.pp to a list of vertex.id with that pp, so we can quickly find collisions. * `solving_edge` represents a solution that will prove our target equation. It is an edge that would connect the two trees, so `solving_edge.fr` and `solving_edge.to` are vertices in different trees. * `lhs` and `rhs` are the left and right expressions we are trying to prove are equal. -/ meta structure graph := (conf : config) (rules : list (expr × bool)) (vertices : buffer vertex) (vmap : native.rb_map string (list ℕ)) (solving_edge : option edge) (lhs : expr) (rhs : expr) /-- Construct a graph to search for a proof of a given equation. This graph initially contains only two disconnected vertices corresponding to the two sides of the equation. When `find_proof` is called, we will run a search and add new vertices and edges. -/ meta def mk_graph (conf : config) (rules : list (expr × bool)) (eq : expr) : tactic graph := do (lhs, rhs) ← tactic.match_eq eq <|> tactic.match_iff eq, lhs_pp ← to_string <$> tactic.pp lhs, rhs_pp ← to_string <$> tactic.pp rhs, let lhs_vertex : vertex := ⟨0, lhs, lhs_pp, side.L, none⟩, let rhs_vertex : vertex := ⟨1, rhs, rhs_pp, side.R, none⟩, return ⟨conf, rules, [lhs_vertex, rhs_vertex].to_buffer, native.rb_map.of_list [(lhs_pp, [0]), (rhs_pp, [1])], none, lhs, rhs⟩ variables (g : graph) namespace graph /-- Find a list of edges that connect the given edge to the root of its tree. The edges are returned in leaf-to-root order, while they are in root-to-leaf direction, so if you want them in the logical order you must reverse the returned list. -/ private meta def walk_up_parents : option edge → tactic (list edge) | none := return [] | (some e) := do v ← g.vertices.read_t e.from_id, edges ← walk_up_parents v.parent, return (e :: edges) /-- Returns two lists that represent a solution. The first list is a path from LHS to some interior vertex, the second is a path from the RHS to that interior vertex. -/ private meta def solution_paths : tactic (list edge × list edge) := do e ← g.solving_edge, v ← g.vertices.read_t e.to_id, path1 ← walk_up_parents g e, path2 ← walk_up_parents g v.parent, match v.side with | side.L := return (path2.reverse, path1.reverse) | side.R := return (path1.reverse, path2.reverse) end /-- Finds the id of a vertex in a list whose expression is defeq to the provided expression. Returns none if there is none. -/ private meta def find_defeq : expr → list ℕ → tactic (option ℕ) | exp [] := return none | exp (id :: rest) := do v ← g.vertices.read_t id, ((do tactic.is_def_eq v.exp exp, return (some id)) <|> (find_defeq exp rest)) /-- Add the new vertex and edge to the graph, that can be proved in one step starting at a given vertex, with a given rewrite expression. For efficiency, it's important that this is the only way the graph is mutated, and it only appends to the end of the `vertices` buffer. -/ private meta def add_rewrite (v : vertex) (rw : rewrite) : tactic graph := do pp ← to_string <$> tactic.pp rw.exp, let existing_ids := match g.vmap.find pp with | some ids := ids | none := [] end, maybe_id ← find_defeq g rw.exp existing_ids, match maybe_id with | (some id) := do existing_vertex ← g.vertices.read_t id, if v.side = existing_vertex.side then return g else return { g with solving_edge := some ⟨v.id, existing_vertex.id, rw.proof, rw.how⟩ } | none := do let new_vertex_id := g.vertices.size, let new_edge : edge := ⟨v.id, new_vertex_id, rw.proof, rw.how⟩, let new_vertex : vertex := ⟨new_vertex_id, rw.exp, pp, v.side, (some new_edge)⟩, trace_if_enabled `rewrite_search format!"new edge: {v.pp} → {new_vertex.pp}", return { g with vertices := g.vertices.push_back new_vertex, vmap := g.vmap.insert pp (new_vertex_id :: existing_ids) } end /-- Add all single-step rewrites starting at a particular vertex to the graph. -/ private meta def expand_vertex (v : vertex) : tactic graph := do rws ← get_rewrites g.rules v.exp g.conf, list.mfoldl (λ g rw, add_rewrite g v rw) g rws.to_list /-- Repeatedly expand edges, starting at a given vertex id, until a solution is found. -/ private meta def find_solving_edge : graph → ℕ → tactic graph | g vertex_id := if vertex_id ≥ g.conf.max_iterations then fail "search failed: max iterations reached" else if h : vertex_id < g.vertices.size then do let v := g.vertices.read (fin.mk vertex_id h), g ← expand_vertex g v, match g.solving_edge with | some _ := return g | none := find_solving_edge g (vertex_id + 1) end else fail "search failed: all vertices explored" /-- Use `mk_eq_trans` to combine a list of proof expressions into a single proof expression. -/ private meta def combine_proofs (proofs : list expr) : tactic expr := match proofs with | [] := fail "cannot combine empty proof list" | (proof :: rest) := list.mfoldl mk_eq_trans proof rest end /-- Construct a proof unit, given a path through the graph. This reverses the direction of the proof on the right hand side, with `mk_eq_symm`. -/ private meta def proof_for_edges : (side × list edge) → tactic (option proof_unit) | (s, []) := return none | (s, edges) := do proofs ← match s with | side.L := edges.mmap (λ e, e.proof) | side.R := edges.reverse.mmap (λ e, e.proof >>= mk_eq_symm) end, proof ← combine_proofs proofs, let hows := edges.map (λ e, e.how), return $ some ⟨proof, s, hows⟩ /-- Checks to see if an empty series of rewrites will solve this, because it's an expression of the form a = a. -/ private meta def find_trivial_proof : tactic (graph × expr × list proof_unit) := do is_def_eq g.lhs g.rhs, exp ← mk_eq_refl g.lhs, return (g, exp, []) /-- Run the search to find a proof for the provided graph. Normally, this is the only external method needed to run the graph search. -/ meta def find_proof : tactic (graph × expr × list proof_unit) := find_trivial_proof g <|> do g ← find_solving_edge g 0, (left_edges, right_edges) ← solution_paths g, units ← [(side.L, left_edges), (side.R, right_edges)].mmap_filter proof_for_edges, proof ← combine_proofs $ units.map $ λ u, u.proof, return (g, proof, units) end graph end tactic.rewrite_search
605dc6a64dabb75b024a61cc61f0b5c351734d9e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/group_auto.lean
e1d9375c053e2ee2cda900b1e46919a7f30928d4
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,966
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.measure_theory.integration import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Measures on Groups We develop some properties of measures on (topological) groups * We define properties on measures: left and right invariant measures. * We define the measure `μ.inv : A ↦ μ(A⁻¹)` and show that it is right invariant iff `μ` is left invariant. -/ namespace measure_theory /-- A measure `μ` on a topological group is left invariant if the measure of left translations of a set are equal to the measure of the set itself. To left translate sets we use preimage under left multiplication, since preimages are nicer to work with than images. -/ def is_add_left_invariant {G : Type u_1} [measurable_space G] [Add G] (μ : set G → ennreal) := ∀ (g : G) {A : set G} (h : is_measurable A), μ ((fun (h : G) => g + h) ⁻¹' A) = μ A /-- A measure `μ` on a topological group is right invariant if the measure of right translations of a set are equal to the measure of the set itself. To right translate sets we use preimage under right multiplication, since preimages are nicer to work with than images. -/ def is_add_right_invariant {G : Type u_1} [measurable_space G] [Add G] (μ : set G → ennreal) := ∀ (g : G) {A : set G} (h : is_measurable A), μ ((fun (h : G) => h + g) ⁻¹' A) = μ A namespace measure theorem map_mul_left_eq_self {G : Type u_1} [measurable_space G] [topological_space G] [Mul G] [has_continuous_mul G] [borel_space G] {μ : measure G} : (∀ (g : G), coe_fn (map (Mul.mul g)) μ = μ) ↔ is_mul_left_invariant ⇑μ := sorry theorem map_mul_right_eq_self {G : Type u_1} [measurable_space G] [topological_space G] [Mul G] [has_continuous_mul G] [borel_space G] {μ : measure G} : (∀ (g : G), coe_fn (map fun (h : G) => h * g) μ = μ) ↔ is_mul_right_invariant ⇑μ := sorry /-- The measure `A ↦ μ (A⁻¹)`, where `A⁻¹` is the pointwise inverse of `A`. -/ protected def neg {G : Type u_1} [measurable_space G] [Neg G] (μ : measure G) : measure G := coe_fn (map Neg.neg) μ theorem neg_apply {G : Type u_1} [measurable_space G] [add_group G] [topological_space G] [topological_add_group G] [borel_space G] (μ : measure G) {s : set G} (hs : is_measurable s) : coe_fn (measure.neg μ) s = coe_fn μ (-s) := sorry @[simp] protected theorem neg_neg {G : Type u_1} [measurable_space G] [add_group G] [topological_space G] [topological_add_group G] [borel_space G] (μ : measure G) : measure.neg (measure.neg μ) = μ := sorry theorem regular.neg {G : Type u_1} [measurable_space G] [add_group G] [topological_space G] [topological_add_group G] [borel_space G] {μ : measure G} [t2_space G] (hμ : regular μ) : regular (measure.neg μ) := regular.map hμ (homeomorph.neg G) end measure @[simp] theorem regular_inv_iff {G : Type u_1} [measurable_space G] [group G] [topological_space G] [topological_group G] [borel_space G] {μ : measure G} [t2_space G] : measure.regular (measure.inv μ) ↔ measure.regular μ := sorry theorem is_add_left_invariant.neg {G : Type u_1} [measurable_space G] [add_group G] [topological_space G] [topological_add_group G] [borel_space G] {μ : measure G} (h : is_add_left_invariant ⇑μ) : is_add_right_invariant ⇑(measure.neg μ) := sorry theorem is_mul_right_invariant.inv {G : Type u_1} [measurable_space G] [group G] [topological_space G] [topological_group G] [borel_space G] {μ : measure G} (h : is_mul_right_invariant ⇑μ) : is_mul_left_invariant ⇑(measure.inv μ) := sorry @[simp] theorem is_mul_right_invariant_inv {G : Type u_1} [measurable_space G] [group G] [topological_space G] [topological_group G] [borel_space G] {μ : measure G} : is_mul_right_invariant ⇑(measure.inv μ) ↔ is_mul_left_invariant ⇑μ := sorry @[simp] theorem is_add_left_invariant_neg {G : Type u_1} [measurable_space G] [add_group G] [topological_space G] [topological_add_group G] [borel_space G] {μ : measure G} : is_add_left_invariant ⇑(measure.neg μ) ↔ is_add_right_invariant ⇑μ := sorry /-! Properties of regular left invariant measures -/ theorem is_mul_left_invariant.null_iff_empty {G : Type u_1} [measurable_space G] [topological_space G] [borel_space G] {μ : measure G} [group G] [topological_group G] (hμ : measure.regular μ) (h2μ : is_mul_left_invariant ⇑μ) (h3μ : μ ≠ 0) {s : set G} (hs : is_open s) : coe_fn μ s = 0 ↔ s = ∅ := sorry theorem is_mul_left_invariant.null_iff {G : Type u_1} [measurable_space G] [topological_space G] [borel_space G] {μ : measure G} [group G] [topological_group G] (hμ : measure.regular μ) (h2μ : is_mul_left_invariant ⇑μ) {s : set G} (hs : is_open s) : coe_fn μ s = 0 ↔ s = ∅ ∨ μ = 0 := sorry theorem is_mul_left_invariant.measure_ne_zero_iff_nonempty {G : Type u_1} [measurable_space G] [topological_space G] [borel_space G] {μ : measure G} [group G] [topological_group G] (hμ : measure.regular μ) (h2μ : is_mul_left_invariant ⇑μ) (h3μ : μ ≠ 0) {s : set G} (hs : is_open s) : coe_fn μ s ≠ 0 ↔ set.nonempty s := sorry /-- For nonzero regular left invariant measures, the integral of a continuous nonnegative function `f` is 0 iff `f` is 0. -/ -- @[to_additive] (fails for now) theorem lintegral_eq_zero_of_is_mul_left_invariant {G : Type u_1} [measurable_space G] [topological_space G] [borel_space G] {μ : measure G} [group G] [topological_group G] (hμ : measure.regular μ) (h2μ : is_mul_left_invariant ⇑μ) (h3μ : μ ≠ 0) {f : G → ennreal} (hf : continuous f) : (lintegral μ fun (x : G) => f x) = 0 ↔ f = 0 := sorry end Mathlib
d05f623f04a50d2eafcb0c7108917addd932b6e7
9dc8cecdf3c4634764a18254e94d43da07142918
/src/field_theory/minpoly.lean
2cfa3279a3de65b58e4a39a27f200438662cafc5
[ "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
23,936
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import data.polynomial.field_division import ring_theory.integral_closure import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ open_locale classical polynomial open polynomial set function variables {A B : Type*} section min_poly_def variables (A) [comm_ring A] [ring B] [algebra A B] /-- Suppose `x : B`, where `B` is an `A`-algebra. The minimal polynomial `minpoly A x` of `x` is a monic polynomial with coefficients in `A` of smallest degree that has `x` as its root, if such exists (`is_integral A x`) or zero otherwise. For example, if `V` is a `𝕜`-vector space for some field `𝕜` and `f : V →ₗ[𝕜] V` then the minimal polynomial of `f` is `minpoly 𝕜 f`. -/ noncomputable def minpoly (x : B) : A[X] := if hx : is_integral A x then well_founded.min degree_lt_wf _ hx else 0 end min_poly_def namespace minpoly section ring variables [comm_ring A] [ring B] [algebra A B] variables {x : B} /-- A minimal polynomial is monic. -/ lemma monic (hx : is_integral A x) : monic (minpoly A x) := by { delta minpoly, rw dif_pos hx, exact (well_founded.min_mem degree_lt_wf _ hx).1 } /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 := (monic hx).ne_zero lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 := dif_neg hx variables (A x) /-- An element is a root of its minimal polynomial. -/ @[simp] lemma aeval : aeval x (minpoly A x) = 0 := begin delta minpoly, split_ifs with hx, { exact (well_founded.min_mem degree_lt_wf _ hx).2 }, { exact aeval_zero _ } end /-- A minimal polynomial is not `1`. -/ lemma ne_one [nontrivial B] : minpoly A x ≠ 1 := begin intro h, refine (one_ne_zero : (1 : B) ≠ 0) _, simpa using congr_arg (polynomial.aeval x) h end lemma map_ne_one [nontrivial B] {R : Type*} [semiring R] [nontrivial R] (f : A →+* R) : (minpoly A x).map f ≠ 1 := begin by_cases hx : is_integral A x, { exact mt ((monic hx).eq_one_of_map_eq_one f) (ne_one A x) }, { rw [eq_zero hx, polynomial.map_zero], exact zero_ne_one }, end /-- A minimal polynomial is not a unit. -/ lemma not_is_unit [nontrivial B] : ¬ is_unit (minpoly A x) := begin haveI : nontrivial A := (algebra_map A B).domain_nontrivial, by_cases hx : is_integral A x, { exact mt (eq_one_of_is_unit_of_monic (monic hx)) (ne_one A x) }, { rw [eq_zero hx], exact not_is_unit_zero } end lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range := begin have h : is_integral A x, { by_contra h, rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx, exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) }, have key := minpoly.aeval A x, rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key, exact ⟨-(minpoly A x).coeff 0, key.symm⟩, end /-- The defining property of the minimal polynomial of an element `x`: it is the monic polynomial with smallest degree that has `x` as its root. -/ lemma min {p : A[X]} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := begin delta minpoly, split_ifs with hx, { exact le_of_not_lt (well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩) }, { simp only [degree_zero, bot_le] } end @[nontriviality] lemma subsingleton [subsingleton B] : minpoly A x = 1 := begin nontriviality A, have := minpoly.min A x monic_one (subsingleton.elim _ _), rw degree_one at this, cases le_or_lt (minpoly A x).degree 0 with h h, { rwa (monic ⟨1, monic_one, by simp⟩ : (minpoly A x).monic).degree_le_zero_iff_eq_one at h }, { exact (this.not_lt h).elim }, end end ring section comm_ring variables [comm_ring A] section ring variables [ring B] [algebra A B] [nontrivial B] variables {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ lemma nat_degree_pos (hx : is_integral A x) : 0 < nat_degree (minpoly A x) := begin rw pos_iff_ne_zero, intro ndeg_eq_zero, have eq_one : minpoly A x = 1, { rw eq_C_of_nat_degree_eq_zero ndeg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x end /-- The degree of a minimal polynomial is positive. -/ lemma degree_pos (hx : is_integral A x) : 0 < degree (minpoly A x) := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos hx) /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/ lemma eq_X_sub_C_of_algebra_map_inj (a : A) (hf : function.injective (algebra_map A B)) : minpoly A (algebra_map A B a) = X - C a := begin nontriviality A, have hdegle : (minpoly A (algebra_map A B a)).nat_degree ≤ 1, { apply with_bot.coe_le_coe.1, rw [←degree_eq_nat_degree (ne_zero (@is_integral_algebra_map A B _ _ _ a)), with_top.coe_one, ←degree_X_sub_C a], refine min A (algebra_map A B a) (monic_X_sub_C a) _, simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self] }, have hdeg : (minpoly A (algebra_map A B a)).degree = 1, { apply (degree_eq_iff_nat_degree_eq (ne_zero (@is_integral_algebra_map A B _ _ _ a))).2, apply le_antisymm hdegle (nat_degree_pos (@is_integral_algebra_map A B _ _ _ a)) }, have hrw := eq_X_add_C_of_degree_eq_one hdeg, simp only [monic (@is_integral_algebra_map A B _ _ _ a), one_mul, monic.leading_coeff, ring_hom.map_one] at hrw, have h0 : (minpoly A (algebra_map A B a)).coeff 0 = -a, { have hroot := aeval A (algebra_map A B a), rw [hrw, add_comm] at hroot, simp only [aeval_C, aeval_X, aeval_add] at hroot, replace hroot := eq_neg_of_add_eq_zero_left hroot, rw [←ring_hom.map_neg _ a] at hroot, exact (hf hroot) }, rw hrw, simp only [h0, ring_hom.map_neg, sub_eq_add_neg], end end ring section is_domain variables [is_domain A] [ring B] [algebra A B] variables {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : A[X]} (hx : is_integral A x) (hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) : polynomial.aeval x a ≠ 0 := begin intro ha, refine not_lt_of_ge (minpoly.min A x hamonic ha) _, obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd, have hbmonic : b.monic, { rw monic.def, have := monic hx, rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this }, have hzerob : b ≠ 0 := hbmonic.ne_zero, have degbzero : 0 < b.nat_degree, { apply nat.pos_of_ne_zero, intro h, have h₁ := eq_C_of_nat_degree_eq_zero h, rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁, rw h₁ at hb_nunit, have := is_unit_one, contradiction }, rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob], exact_mod_cast lt_add_of_pos_right _ degbzero, end variables [is_domain B] /-- A minimal polynomial is irreducible. -/ lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) := begin cases irreducible_or_factor (minpoly A x) (not_is_unit A x) with hirr hred, { exact hirr }, exfalso, obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred, have coeff_prod : a.leading_coeff * b.leading_coeff = 1, { rw [←monic.def.1 (monic hx), ←hab_eq], simp only [leading_coeff_mul] }, have hamonic : (a * C b.leading_coeff).monic, { rw monic.def, simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have hbmonic : (b * C a.leading_coeff).monic, { rw [monic.def, mul_comm], simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have prod : minpoly A x = (a * C b.leading_coeff) * (b * C a.leading_coeff), { symmetry, calc a * C b.leading_coeff * (b * C a.leading_coeff) = a * b * (C a.leading_coeff * C b.leading_coeff) : by ring ... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul] ... = a * b : by rw [coeff_prod, C_1, mul_one] ... = minpoly A x : hab_eq }, have hzero := aeval A x, rw [prod, aeval_mul, mul_eq_zero] at hzero, cases hzero, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hamonic _ hzero, exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ }, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hbmonic _ hzero, rw mul_comm at prod, exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ }, end end is_domain end comm_ring section field variables [field A] section ring variables [ring B] [algebra A B] variables {x : B} variables (A x) /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. See also `gcd_domain_degree_le_of_ne_zero` which relaxes the assumptions on `A` in exchange for stronger assumptions on `B`. -/ lemma degree_le_of_ne_zero {p : A[X]} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := calc degree (minpoly A x) ≤ degree (p * C (leading_coeff p)⁻¹) : min A x (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz lemma ne_zero_of_finite_field_extension (e : B) [finite_dimensional A B] : minpoly A e ≠ 0 := minpoly.ne_zero $ is_integral_of_noetherian (is_noetherian.iff_fg.2 infer_instance) _ /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. See also `minpoly.gcd_unique` which relaxes the assumptions on `A` in exchange for stronger assumptions on `B`. -/ lemma unique {p : A[X]} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) (pmin : ∀ q : A[X], q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minpoly A x := begin have hx : is_integral A x := ⟨p, pmonic, hp⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero A x hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min A x pmonic hp) (pmin (minpoly A x) (monic hx) (aeval A x)) } end /-- If an element `x` is a root of a polynomial `p`, then the minimal polynomial of `x` divides `p`. See also `minpoly.gcd_domain_dvd` which relaxes the assumptions on `A` in exchange for stronger assumptions on `B`. -/ lemma dvd {p : A[X]} (hp : polynomial.aeval x p = 0) : minpoly A x ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, dvd_zero] }, have hx : is_integral A x, { rw ← is_algebraic_iff_is_integral, exact ⟨p, hp0, hp⟩ }, rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero A x hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end lemma dvd_map_of_is_scalar_tower (A K : Type*) {R : Type*} [comm_ring A] [field K] [comm_ring R] [algebra A K] [algebra A R] [algebra K R] [is_scalar_tower A K R] (x : R) : minpoly K x ∣ (minpoly A x).map (algebra_map A K) := by { refine minpoly.dvd K x _, rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } /-- If `y` is a conjugate of `x` over a field `K`, then it is a conjugate over a subring `R`. -/ lemma aeval_of_is_scalar_tower (R : Type*) {K T U : Type*} [comm_ring R] [field K] [comm_ring T] [algebra R K] [algebra K T] [algebra R T] [is_scalar_tower R K T] [comm_semiring U] [algebra K U] [algebra R U] [is_scalar_tower R K U] (x : T) (y : U) (hy : polynomial.aeval y (minpoly K x) = 0) : polynomial.aeval y (minpoly R x) = 0 := by { rw is_scalar_tower.aeval_apply R K, exact eval₂_eq_zero_of_dvd_of_eval₂_eq_zero (algebra_map K U) y (minpoly.dvd_map_of_is_scalar_tower R K x) hy } variables {A x} theorem eq_of_irreducible_of_monic [nontrivial B] {p : A[X]} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) : p = minpoly A x := let ⟨q, hq⟩ := dvd A x hp2 in eq_of_monic_of_associated hp3 (monic ⟨p, ⟨hp3, hp2⟩⟩) $ mul_one (minpoly A x) ▸ hq.symm ▸ associated.mul_left _ $ associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit A x lemma eq_of_irreducible [nontrivial B] {p : A[X]} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) : p * C p.leading_coeff⁻¹ = minpoly A x := begin have : p.leading_coeff ≠ 0 := leading_coeff_ne_zero.mpr hp1.ne_zero, apply eq_of_irreducible_of_monic, { exact associated.irreducible ⟨⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rwa [←C_mul, inv_mul_cancel, C_1], by rwa [←C_mul, mul_inv_cancel, C_1]⟩, rfl⟩ hp1 }, { rw [aeval_mul, hp2, zero_mul] }, { rwa [polynomial.monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel] }, end /-- If `y` is the image of `x` in an extension, their minimal polynomials coincide. We take `h : y = algebra_map L T x` as an argument because `rw h` typically fails since `is_integral R y` depends on y. -/ lemma eq_of_algebra_map_eq {K S T : Type*} [field K] [comm_ring S] [comm_ring T] [algebra K S] [algebra K T] [algebra S T] [is_scalar_tower K S T] (hST : function.injective (algebra_map S T)) {x : S} {y : T} (hx : is_integral K x) (h : y = algebra_map S T x) : minpoly K x = minpoly K y := minpoly.unique _ _ (minpoly.monic hx) (by rw [h, ← is_scalar_tower.algebra_map_aeval, minpoly.aeval, ring_hom.map_zero]) (λ q q_monic root_q, minpoly.min _ _ q_monic (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero K S T hST (h ▸ root_q : polynomial.aeval (algebra_map S T x) q = 0))) lemma add_algebra_map {B : Type*} [comm_ring B] [algebra A B] {x : B} (hx : is_integral A x) (a : A) : minpoly A (x + (algebra_map A B a)) = (minpoly A x).comp (X - C a) := begin refine (minpoly.unique _ _ ((minpoly.monic hx).comp_X_sub_C _) _ (λ q qmo hq, _)).symm, { simp [aeval_comp] }, { have : (polynomial.aeval x) (q.comp (X + C a)) = 0 := by simpa [aeval_comp] using hq, have H := minpoly.min A x (qmo.comp_X_add_C _) this, rw [degree_eq_nat_degree qmo.ne_zero, degree_eq_nat_degree ((minpoly.monic hx).comp_X_sub_C _).ne_zero, with_bot.coe_le_coe, nat_degree_comp, nat_degree_X_sub_C, mul_one], rwa [degree_eq_nat_degree (minpoly.ne_zero hx), degree_eq_nat_degree (qmo.comp_X_add_C _).ne_zero, with_bot.coe_le_coe, nat_degree_comp, nat_degree_X_add_C, mul_one] at H } end lemma sub_algebra_map {B : Type*} [comm_ring B] [algebra A B] {x : B} (hx : is_integral A x) (a : A) : minpoly A (x - (algebra_map A B a)) = (minpoly A x).comp (X + C a) := by simpa [sub_eq_add_neg] using add_algebra_map hx (-a) section alg_hom_fintype /-- A technical finiteness result. -/ noncomputable def fintype.subtype_prod {E : Type*} {X : set E} (hX : X.finite) {L : Type*} (F : E → multiset L) : fintype (Π x : X, {l : L // l ∈ F x}) := let hX := finite.fintype hX in by exactI pi.fintype variables (F E K : Type*) [field F] [ring E] [comm_ring K] [is_domain K] [algebra F E] [algebra F K] [finite_dimensional F E] /-- Function from Hom_K(E,L) to pi type Π (x : basis), roots of min poly of x -/ -- Marked as `noncomputable!` since this definition takes multiple seconds to compile, -- and isn't very computable in practice (since neither `finrank` nor `fin_basis` are). noncomputable! def roots_of_min_poly_pi_type (φ : E →ₐ[F] K) (x : range (finite_dimensional.fin_basis F E : _ → E)) : {l : K // l ∈ (((minpoly F x.1).map (algebra_map F K)).roots : multiset K)} := ⟨φ x, by rw [mem_roots_map (minpoly.ne_zero_of_finite_field_extension F x.val), subtype.val_eq_coe, ←aeval_def, aeval_alg_hom_apply, minpoly.aeval, map_zero]⟩ lemma aux_inj_roots_of_min_poly : injective (roots_of_min_poly_pi_type F E K) := begin intros f g h, suffices : (f : E →ₗ[F] K) = g, { rwa fun_like.ext'_iff at this ⊢ }, rw funext_iff at h, exact linear_map.ext_on (finite_dimensional.fin_basis F E).span_eq (λ e he, subtype.ext_iff.mp (h ⟨e, he⟩)), end /-- Given field extensions `E/F` and `K/F`, with `E/F` finite, there are finitely many `F`-algebra homomorphisms `E →ₐ[K] K`. -/ noncomputable instance alg_hom.fintype : fintype (E →ₐ[F] K) := @fintype.of_injective _ _ (fintype.subtype_prod (finite_range (finite_dimensional.fin_basis F E)) (λ e, ((minpoly F e).map (algebra_map F K)).roots)) _ (aux_inj_roots_of_min_poly F E K) end alg_hom_fintype section gcd_domain variables {R S : Type*} (K L : Type*) [comm_ring R] [is_domain R] [normalized_gcd_monoid R] [field K] [comm_ring S] [is_domain S] [algebra R K] [is_fraction_ring R K] [algebra R S] [field L] [algebra S L] [algebra K L] [algebra R L] [is_scalar_tower R K L] [is_scalar_tower R S L] {s : S} (hs : is_integral R s) include hs /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. See `minpoly.gcd_domain_eq_field_fractions'` if `S` is already a `K`-algebra. -/ lemma gcd_domain_eq_field_fractions : minpoly K (algebra_map S L s) = (minpoly R s).map (algebra_map R K) := begin refine (eq_of_irreducible_of_monic _ _ _).symm, { exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map (polynomial.monic.is_primitive (monic hs))).1 (irreducible hs) }, { rw [aeval_map, aeval_def, is_scalar_tower.algebra_map_eq R S L, ← eval₂_map, eval₂_at_apply, eval_map, ← aeval_def, aeval, map_zero] }, { exact (monic hs).map _ } end /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. Compared to `minpoly.gcd_domain_eq_field_fractions`, this version is useful if the element is in a ring that is already a `K`-algebra. -/ lemma gcd_domain_eq_field_fractions' [algebra K S] [is_scalar_tower R K S] : minpoly K s = (minpoly R s).map (algebra_map R K) := begin let L := fraction_ring S, rw [← gcd_domain_eq_field_fractions K L hs], refine minpoly.eq_of_algebra_map_eq (is_fraction_ring.injective S L) (is_integral_of_is_scalar_tower _ hs) rfl end variable [no_zero_smul_divisors R S] /-- For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. See also `minpoly.dvd` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma gcd_domain_dvd {P : R[X]} (hP : P ≠ 0) (hroot : polynomial.aeval s P = 0) : minpoly R s ∣ P := begin let K := fraction_ring R, let L := fraction_ring S, let P₁ := P.prim_part, suffices : minpoly R s ∣ P₁, { exact dvd_trans this (prim_part_dvd _) }, apply (is_primitive.dvd_iff_fraction_map_dvd_fraction_map K (monic hs).is_primitive P.is_primitive_prim_part).2, let y := algebra_map S L s, have hy : is_integral R y := hs.algebra_map, rw [← gcd_domain_eq_field_fractions K L hs], refine dvd _ _ _, rw [aeval_map, aeval_def, is_scalar_tower.algebra_map_eq R S L, ← eval₂_map, eval₂_at_apply, eval_map, ← aeval_def, aeval_prim_part_eq_zero hP hroot, map_zero] end /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. See also `minpoly.degree_le_of_ne_zero` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma gcd_domain_degree_le_of_ne_zero {p : R[X]} (hp0 : p ≠ 0) (hp : polynomial.aeval s p = 0) : degree (minpoly R s) ≤ degree p := begin rw [degree_eq_nat_degree (minpoly.ne_zero hs), degree_eq_nat_degree hp0], norm_cast, exact nat_degree_le_of_dvd (gcd_domain_dvd hs hp0 hp) hp0 end omit hs /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. See also `minpoly.unique` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma gcd_domain_unique {P : R[X]} (hmo : P.monic) (hP : polynomial.aeval s P = 0) (Pmin : ∀ Q : R[X], Q.monic → polynomial.aeval s Q = 0 → degree P ≤ degree Q) : P = minpoly R s := begin have hs : is_integral R s := ⟨P, hmo, hP⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := gcd_domain_degree_le_of_ne_zero hs hnz (by simp [hP]), contrapose! this, refine degree_sub_lt _ (ne_zero hs) _, { exact le_antisymm (min R s hmo hP) (Pmin (minpoly R s) (monic hs) (aeval R s)) }, { rw [(monic hs).leading_coeff, hmo.leading_coeff] } end end gcd_domain variables (B) [nontrivial B] /-- If `B/K` is a nontrivial algebra over a field, and `x` is an element of `K`, then the minimal polynomial of `algebra_map K B x` is `X - C x`. -/ lemma eq_X_sub_C (a : A) : minpoly A (algebra_map A B a) = X - C a := eq_X_sub_C_of_algebra_map_inj a (algebra_map A B).injective lemma eq_X_sub_C' (a : A) : minpoly A a = X - C a := eq_X_sub_C A a variables (A) /-- The minimal polynomial of `0` is `X`. -/ @[simp] lemma zero : minpoly A (0:B) = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero] using eq_X_sub_C B (0:A) /-- The minimal polynomial of `1` is `X - 1`. -/ @[simp] lemma one : minpoly A (1:B) = X - 1 := by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using eq_X_sub_C B (1:A) end ring section is_domain variables [ring B] [is_domain B] [algebra A B] variables {x : B} /-- A minimal polynomial is prime. -/ lemma prime (hx : is_integral A x) : prime (minpoly A x) := begin refine ⟨ne_zero hx, not_is_unit A x, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval A x], replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa, exact or.imp (dvd A x) (dvd A x) this end /-- If `L/K` is a field extension and an element `y` of `K` is a root of the minimal polynomial of an element `x ∈ L`, then `y` maps to `x` under the field embedding. -/ lemma root {x : B} (hx : is_integral A x) {y : A} (h : is_root (minpoly A x) y) : algebra_map A B y = x := have key : minpoly A x = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd ((irreducible_X_sub_C y).dvd_symm (irreducible hx) (dvd_iff_is_root.2 h)) (dvd_iff_is_root.2 h)), by { have := aeval A x, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this } /-- The constant coefficient of the minimal polynomial of `x` is `0` if and only if `x = 0`. -/ @[simp] lemma coeff_zero_eq_zero (hx : is_integral A x) : coeff (minpoly A x) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact ring_hom.map_zero _ }, { rintro rfl, simp } end /-- The minimal polynomial of a nonzero element has nonzero constant coefficient. -/ lemma coeff_zero_ne_zero (hx : is_integral A x) (h : x ≠ 0) : coeff (minpoly A x) 0 ≠ 0 := by { contrapose! h, simpa only [hx, coeff_zero_eq_zero] using h } end is_domain end field end minpoly
3cc2beaf2e16afdba9cdf36f4369efee838beef0
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/Script/AddressSpace.lean
d41c51cc0d6d0c0345112e3fbca65affd9fb2f1b
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
541
lean
import Lean.Parser import Papyrus.IR.AddressSpace namespace Papyrus.Script open Lean Parser @[runParserAttributeHooks] def addrspace := leading_parser nonReservedSymbol "addrspace" true >> "(" >> termParser >> ")" def expandAddrspace : (addrSpace : Syntax) → MacroM Syntax | `(addrspace| addrspace($x:term)) => x | stx => Macro.throwErrorAt stx "ill-formed address space" def expandOptAddrspace : (addrspace? : Option Syntax) → MacroM Syntax | some addrspace => expandAddrspace addrspace | none => mkCIdent ``AddressSpace.default
97759fed03f61981aa412c0c630e0b8392219d8f
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/differential_object.lean
268eb4e9ff21ac3a2e45ee3054108b4281d3d1ea
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
8,872
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.int.basic import category_theory.shift import category_theory.concrete_category.basic /-! # Differential objects in a category. A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. We build the category of differential objects, and some basic constructions such as the forgetful functor, zero morphisms and zero objects, and the shift functor on differential objects. -/ open category_theory.limits universes v u namespace category_theory variables (C : Type u) [category.{v} C] -- TODO: generaize to `has_shift C A` for an arbitrary `[add_monoid A]` `[has_one A]`. variables [has_zero_morphisms C] [has_shift C ℤ] /-- A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. -/ @[nolint has_inhabited_instance] structure differential_object := (X : C) (d : X ⟶ X⟦1⟧) (d_squared' : d ≫ d⟦(1:ℤ)⟧' = 0 . obviously) restate_axiom differential_object.d_squared' attribute [simp] differential_object.d_squared variables {C} namespace differential_object /-- A morphism of differential objects is a morphism commuting with the differentials. -/ @[ext, nolint has_inhabited_instance] structure hom (X Y : differential_object C) := (f : X.X ⟶ Y.X) (comm' : X.d ≫ f⟦1⟧' = f ≫ Y.d . obviously) restate_axiom hom.comm' attribute [simp, reassoc] hom.comm namespace hom /-- The identity morphism of a differential object. -/ @[simps] def id (X : differential_object C) : hom X X := { f := 𝟙 X.X } /-- The composition of morphisms of differential objects. -/ @[simps] def comp {X Y Z : differential_object C} (f : hom X Y) (g : hom Y Z) : hom X Z := { f := f.f ≫ g.f, } end hom instance category_of_differential_objects : category (differential_object C) := { hom := hom, id := hom.id, comp := λ X Y Z f g, hom.comp f g, } @[simp] lemma id_f (X : differential_object C) : ((𝟙 X) : X ⟶ X).f = 𝟙 (X.X) := rfl @[simp] lemma comp_f {X Y Z : differential_object C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).f = f.f ≫ g.f := rfl @[simp] lemma eq_to_hom_f {X Y : differential_object C} (h : X = Y) : hom.f (eq_to_hom h) = eq_to_hom (congr_arg _ h) := by { subst h, rw [eq_to_hom_refl, eq_to_hom_refl], refl } variables (C) /-- The forgetful functor taking a differential object to its underlying object. -/ def forget : (differential_object C) ⥤ C := { obj := λ X, X.X, map := λ X Y f, f.f, } instance forget_faithful : faithful (forget C) := { } instance has_zero_morphisms : has_zero_morphisms (differential_object C) := { has_zero := λ X Y, ⟨{ f := 0 }⟩} variables {C} @[simp] lemma zero_f (P Q : differential_object C) : (0 : P ⟶ Q).f = 0 := rfl /-- An isomorphism of differential objects gives an isomorphism of the underlying objects. -/ @[simps] def iso_app {X Y : differential_object C} (f : X ≅ Y) : X.X ≅ Y.X := ⟨f.hom.f, f.inv.f, by { dsimp, rw [← comp_f, iso.hom_inv_id, id_f] }, by { dsimp, rw [← comp_f, iso.inv_hom_id, id_f] }⟩ @[simp] lemma iso_app_refl (X : differential_object C) : iso_app (iso.refl X) = iso.refl X.X := rfl @[simp] lemma iso_app_symm {X Y : differential_object C} (f : X ≅ Y) : iso_app f.symm = (iso_app f).symm := rfl @[simp] lemma iso_app_trans {X Y Z : differential_object C} (f : X ≅ Y) (g : Y ≅ Z) : iso_app (f ≪≫ g) = iso_app f ≪≫ iso_app g := rfl /-- An isomorphism of differential objects can be constructed from an isomorphism of the underlying objects that commutes with the differentials. -/ @[simps] def mk_iso {X Y : differential_object C} (f : X.X ≅ Y.X) (hf : X.d ≫ f.hom⟦1⟧' = f.hom ≫ Y.d) : X ≅ Y := { hom := ⟨f.hom, hf⟩, inv := ⟨f.inv, by { dsimp, rw [← functor.map_iso_inv, iso.comp_inv_eq, category.assoc, iso.eq_inv_comp, functor.map_iso_hom, hf] }⟩, hom_inv_id' := by { ext1, dsimp, exact f.hom_inv_id }, inv_hom_id' := by { ext1, dsimp, exact f.inv_hom_id } } end differential_object namespace functor universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms D] [has_shift D ℤ] /-- A functor `F : C ⥤ D` which commutes with shift functors on `C` and `D` and preserves zero morphisms can be lifted to a functor `differential_object C ⥤ differential_object D`. -/ @[simps] def map_differential_object (F : C ⥤ D) (η : (shift_functor C (1:ℤ)).comp F ⟶ F.comp (shift_functor D (1:ℤ))) (hF : ∀ c c', F.map (0 : c ⟶ c') = 0) : differential_object C ⥤ differential_object D := { obj := λ X, { X := F.obj X.X, d := F.map X.d ≫ η.app X.X, d_squared' := begin rw [functor.map_comp, ← functor.comp_map F (shift_functor D (1:ℤ))], slice_lhs 2 3 { rw [← η.naturality X.d] }, rw [functor.comp_map], slice_lhs 1 2 { rw [← F.map_comp, X.d_squared, hF] }, rw [zero_comp, zero_comp], end }, map := λ X Y f, { f := F.map f.f, comm' := begin dsimp, slice_lhs 2 3 { rw [← functor.comp_map F (shift_functor D (1:ℤ)), ← η.naturality f.f] }, slice_lhs 1 2 { rw [functor.comp_map, ← F.map_comp, f.comm, F.map_comp] }, rw [category.assoc] end }, map_id' := by { intros, ext, simp }, map_comp' := by { intros, ext, simp }, } end functor end category_theory namespace category_theory namespace differential_object variables (C : Type u) [category.{v} C] variables [has_zero_object C] [has_zero_morphisms C] [has_shift C ℤ] open_locale zero_object instance has_zero_object : has_zero_object (differential_object C) := by { refine ⟨⟨⟨0, 0⟩, λ X, ⟨⟨⟨⟨0⟩⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨⟨0⟩⟩, λ f, _⟩⟩⟩⟩; ext, } end differential_object namespace differential_object variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_zero_morphisms C] [has_shift C ℤ] instance concrete_category_of_differential_objects : concrete_category (differential_object C) := { forget := forget C ⋙ category_theory.forget C } instance : has_forget₂ (differential_object C) C := { forget₂ := forget C } end differential_object /-! The category of differential objects itself has a shift functor. -/ namespace differential_object variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] [has_shift C ℤ] noncomputable theory /-- The shift functor on `differential_object C`. -/ @[simps] def shift_functor (n : ℤ) : differential_object C ⥤ differential_object C := { obj := λ X, { X := X.X⟦n⟧, d := X.d⟦n⟧' ≫ (shift_comm _ _ _).hom, d_squared' := by rw [functor.map_comp, category.assoc, shift_comm_hom_comp_assoc, ←functor.map_comp_assoc, X.d_squared, functor.map_zero, zero_comp] }, map := λ X Y f, { f := f.f⟦n⟧', comm' := by { dsimp, rw [category.assoc, shift_comm_hom_comp, ← functor.map_comp_assoc, f.comm, functor.map_comp_assoc], }, }, map_id' := by { intros X, ext1, dsimp, rw functor.map_id }, map_comp' := by { intros X Y Z f g, ext1, dsimp, rw functor.map_comp } } local attribute [simp] eq_to_hom_map local attribute [reducible] discrete.add_monoidal shift_comm /-- The shift functor on `differential_object C` is additive. -/ @[simps] def shift_functor_add (m n : ℤ) : shift_functor C (m + n) ≅ shift_functor C m ⋙ shift_functor C n := begin refine nat_iso.of_components (λ X, mk_iso (shift_add X.X _ _) _) _, { dsimp, -- This is just `simp, simp [eq_to_hom_map]`. simp_rw [category.assoc, obj_μ_inv_app, μ_inv_hom_app_assoc, functor.map_comp, obj_μ_app, category.assoc, μ_naturality_assoc, μ_inv_hom_app_assoc, obj_μ_inv_app, category.assoc, μ_naturalityₗ_assoc, μ_inv_hom_app_assoc, μ_inv_naturalityᵣ_assoc], simp only [eq_to_hom_map, eq_to_hom_app, eq_to_iso.hom, eq_to_hom_trans_assoc, eq_to_iso.inv], }, { intros X Y f, ext, dsimp, exact nat_trans.naturality _ _ } end local attribute [reducible] endofunctor_monoidal_category section local attribute [instance] endofunctor_monoidal_category /-- The shift by zero is naturally isomorphic to the identity. -/ @[simps] def shift_ε : 𝟭 (differential_object C) ≅ shift_functor C 0 := begin refine nat_iso.of_components (λ X, mk_iso ((shift_monoidal_functor C ℤ).ε_iso.app X.X) _) _, { dsimp, simp, dsimp, simp }, { introv, ext, dsimp, simp } end end local attribute [simp] eq_to_hom_map instance : has_shift (differential_object C) ℤ := has_shift_mk _ _ { F := shift_functor C, ε := shift_ε C, μ := λ m n, (shift_functor_add C m n).symm } end differential_object end category_theory
122b21c68082e0ed80adf1a34e8d168257e7cabb
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/LP_operations.lean
7a7c3c9ead396b4dbcaf8b24a6b6ab5914945539
[]
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
43,160
lean
import data.matrix.pequiv data.rat.basic tactic.fin_cases data.list.min_max partition open matrix fintype finset function pequiv local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose section universes u v variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] {R : Type v} /- Belongs in mathlib -/ lemma mul_right_eq_of_mul_eq [semiring R] {M : matrix l m R} {N : matrix m n R} {O : matrix l n R} {P : matrix n o R} (h : M ⬝ N = O) : M ⬝ (N ⬝ P) = O ⬝ P := by rw [← matrix.mul_assoc, h] end variables {m n : ℕ} /-- The tableau consists of a matrix and a constant `offset` column. `to_partition` stores the indices of the current row and column variables. `restricted` is the set of variables that are restricted to be nonnegative -/ structure tableau (m n : ℕ) := (to_matrix : matrix (fin m) (fin n) ℚ) (offset : cvec m) (to_partition : partition m n) (restricted : finset (fin (m + n))) namespace tableau open partition section predicates variable (T : tableau m n) /-- The affine subspace represented by the tableau ignoring nonnegativity restrictiions -/ def flat : set (cvec (m + n)) := { x | T.to_partition.rowp.to_matrix ⬝ x = T.to_matrix ⬝ T.to_partition.colp.to_matrix ⬝ x + T.offset } /-- The sol_set is the subset of ℚ^(m+n) that satisifies the tableau -/ def sol_set : set (cvec (m + n)) := flat T ∩ { x | ∀ i, i ∈ T.restricted → 0 ≤ x i 0 } /-- Predicate for a variable being unbounded above in the `sol_set` -/ def is_unbounded_above (i : fin (m + n)) : Prop := ∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ q ≤ x i 0 /-- Predicate for a variable being unbounded below in the `sol_set` -/ def is_unbounded_below (i : fin (m + n)) : Prop := ∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ x i 0 ≤ q def is_maximised (x : cvec (m + n)) (i : fin (m + n)) : Prop := ∀ y : cvec (m + n), y ∈ sol_set T → y i 0 ≤ x i 0 /-- Is this equivalent to `∀ (x : cvec (m + n)), x ∈ sol_set T → x i 0 = x j 0`? No -/ def equal_in_flat (i j : fin (m + n)) : Prop := ∀ (x : cvec (m + n)), x ∈ flat T → x i 0 = x j 0 /-- Returns an element of the `flat` after assigning values to the column variables -/ def of_col (T : tableau m n) (x : cvec n) : cvec (m + n) := T.to_partition.colp.to_matrixᵀ ⬝ x + T.to_partition.rowp.to_matrixᵀ ⬝ (T.to_matrix ⬝ x + T.offset) /-- A `tableau` is feasible if its `offset` column is nonnegative in restricted rows -/ def feasible : Prop := ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.offset i 0 /-- Given a row index `r` and a column index `s` it returns a tableau with `r` and `s` switched, but with the same `sol_set` -/ def pivot (r : fin m) (c : fin n) : tableau m n := let p := (T.to_matrix r c)⁻¹ in { to_matrix := λ i j, if i = r then if j = c then p else -T.to_matrix r j * p else if j = c then T.to_matrix i c * p else T.to_matrix i j - T.to_matrix i c * T.to_matrix r j * p, to_partition := T.to_partition.swap r c, offset := λ i k, if i = r then -T.offset r k * p else T.offset i k - T.to_matrix i c * T.offset r k * p, restricted := T.restricted } end predicates section predicate_lemmas variable {T : tableau m n} lemma mem_flat_iff {x : cvec (m + n)} : x ∈ T.flat ↔ ∀ r, x (T.to_partition.rowg r) 0 = univ.sum (λ c : fin n, T.to_matrix r c * x (T.to_partition.colg c) 0) + T.offset r 0 := have hx : x ∈ T.flat ↔ ∀ i, (T.to_partition.rowp.to_matrix ⬝ x) i 0 = (T.to_matrix ⬝ T.to_partition.colp.to_matrix ⬝ x + T.offset) i 0, by rw [flat, set.mem_set_of_eq, matrix.ext_iff.symm, forall_swap, unique.forall_iff]; refl, begin rw hx, refine forall_congr (λ i, _), rw [mul_matrix_apply, add_val, rowp_eq_some_rowg, matrix.mul_assoc, matrix.mul], conv in (T.to_matrix _ _ * (T.to_partition.colp.to_matrix ⬝ x) _ _) { rw [mul_matrix_apply, colp_eq_some_colg] }, end variable (T) @[simp] lemma colp_mul_of_col (x : cvec n) : T.to_partition.colp.to_matrix ⬝ of_col T x = x := by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat, mul_right_eq_of_mul_eq (rowp_mul_colp_transpose _), mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _), mul_right_eq_of_mul_eq (colp_mul_colp_transpose _), mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _)] @[simp] lemma rowp_mul_of_col (x : cvec n) : T.to_partition.rowp.to_matrix ⬝ of_col T x = T.to_matrix ⬝ x + T.offset := by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat, mul_right_eq_of_mul_eq (rowp_mul_colp_transpose _), mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _), mul_right_eq_of_mul_eq (colp_mul_colp_transpose _), mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _)] lemma of_col_mem_flat (x : cvec n) : T.of_col x ∈ T.flat := by simp [matrix.mul_assoc, matrix.mul_add, flat] @[simp] lemma of_col_colg (x : cvec n) (c : fin n) : of_col T x (T.to_partition.colg c) = x c := funext $ λ v, calc of_col T x (T.to_partition.colg c) v = (T.to_partition.colp.to_matrix ⬝ of_col T x) c v : by rw [mul_matrix_apply, colp_eq_some_colg] ... = x c v : by rw [colp_mul_of_col] @[simp] lemma of_col_rowg (c : cvec n) (r : fin m) : of_col T c (T.to_partition.rowg r) = (T.to_matrix ⬝ c + T.offset) r := funext $ λ v, calc of_col T c (T.to_partition.rowg r) v = (T.to_partition.rowp.to_matrix ⬝ of_col T c) r v : by rw [mul_matrix_apply, rowp_eq_some_rowg] ... = (T.to_matrix ⬝ c + T.offset) r v : by rw [rowp_mul_of_col] variable {T} /-- Condition for the solution given by setting column index `j` to `q` and all other columns to zero being in the `sol_set` -/ lemma of_col_single_mem_sol_set {q : ℚ} {c : fin n} (hT : T.feasible) (hi : ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ q * T.to_matrix i c) (hj : T.to_partition.colg c ∉ T.restricted ∨ 0 ≤ q) : T.of_col (q • (single c 0).to_matrix) ∈ T.sol_set := ⟨of_col_mem_flat _ _, λ v, (T.to_partition.eq_rowg_or_colg v).elim begin rintros ⟨r, hr⟩ hres, subst hr, rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply, symm_single, single_apply], exact add_nonneg (hi _ hres) (hT _ hres) end begin rintros ⟨j, hj⟩ hres, subst hj, simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix], by_cases hjc : j = c; simp [*, le_refl] at * end⟩ lemma feasible_iff_of_col_zero_mem_sol_set : T.feasible ↔ T.of_col 0 ∈ T.sol_set := suffices (∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.offset i 0) ↔ ∀ v : fin (m + n), v ∈ T.restricted → (0 : ℚ) ≤ T.of_col 0 v 0, by simpa [sol_set, feasible, of_col_mem_flat], ⟨λ h v hv, (T.to_partition.eq_rowg_or_colg v).elim (by rintros ⟨i, hi⟩; subst hi; simp; tauto) (by rintros ⟨j, hj⟩; subst hj; simp), λ h i hi, by simpa using h _ hi⟩ lemma is_unbounded_above_colg_aux {c : fin n} (hT : T.feasible) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i c) (q : ℚ): of_col T (max q 0 • (single c 0).to_matrix) ∈ sol_set T ∧ q ≤ of_col T (max q 0 • (single c 0).to_matrix) (T.to_partition.colg c) 0 := ⟨of_col_single_mem_sol_set hT (λ i hi, mul_nonneg (le_max_right _ _) (h _ hi)) (or.inr (le_max_right _ _)), by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩ /-- A column variable is unbounded above if it is in a column where every negative entry is in a row owned by an unrestricted variable -/ lemma is_unbounded_above_colg {c : fin n} (hT : T.feasible) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i c) : T.is_unbounded_above (T.to_partition.colg c) := λ q, ⟨_, is_unbounded_above_colg_aux hT h q⟩ lemma is_unbounded_below_colg_aux {c : fin n} (hT : T.feasible) (hres : T.to_partition.colg c ∉ T.restricted) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i c ≤ 0) (q : ℚ) : of_col T (min q 0 • (single c 0).to_matrix) ∈ sol_set T ∧ of_col T (min q 0 • (single c 0).to_matrix) (T.to_partition.colg c) 0 ≤ q := ⟨of_col_single_mem_sol_set hT (λ i hi, mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi)) (or.inl hres), by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩ /-- A column variable is unbounded below if it is unrestricted and it is in a column where every positive entry is in a row owned by an unrestricted variable -/ lemma is_unbounded_below_colg {c : fin n} (hT : T.feasible) (hres : T.to_partition.colg c ∉ T.restricted) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i c ≤ 0) : T.is_unbounded_below (T.to_partition.colg c) := λ q, ⟨_, is_unbounded_below_colg_aux hT hres h q⟩ /-- A row variable `r` is unbounded above if it is unrestricted and there is a column `s` where every restricted row variable has a nonpositive entry in that column, and `r` has a negative entry in that column. -/ lemma is_unbounded_above_rowg_of_nonpos {r : fin m} (hT : T.feasible) (s : fin n) (hres : T.to_partition.colg s ∉ T.restricted) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i s ≤ 0) (his : T.to_matrix r s < 0) : is_unbounded_above T (T.to_partition.rowg r) := λ q, ⟨T.of_col (min ((q - T.offset r 0) / T.to_matrix r s) 0 • (single s 0).to_matrix), of_col_single_mem_sol_set hT (λ i' hi', mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi')) (or.inl hres), begin rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply, symm_single_apply], cases le_total 0 ((q - T.offset r 0) / T.to_matrix r s) with hq hq, { rw [min_eq_right hq], rw [le_div_iff_of_neg his, zero_mul, sub_nonpos] at hq, simpa }, { rw [min_eq_left hq, div_mul_cancel _ (ne_of_lt his)], simp } end⟩ /-- A row variable `r` is unbounded above if there is a column `s` where every restricted row variable has a nonpositive entry in that column, and `r` has a positive entry in that column. -/ lemma is_unbounded_above_rowg_of_nonneg {r : fin m} (hT : T.feasible) (s : fin n) (hs : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i s) (his : 0 < T.to_matrix r s) : is_unbounded_above T (T.to_partition.rowg r) := λ q, ⟨T.of_col (max ((q - T.offset r 0) / T.to_matrix r s) 0 • (single s 0).to_matrix), of_col_single_mem_sol_set hT (λ i hi, mul_nonneg (le_max_right _ _) (hs i hi)) (or.inr (le_max_right _ _)), begin rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply, symm_single_apply], cases le_total ((q - T.offset r 0) / T.to_matrix r s) 0 with hq hq, { rw [max_eq_right hq], rw [div_le_iff his, zero_mul, sub_nonpos] at hq, simpa }, { rw [max_eq_left hq, div_mul_cancel _ (ne_of_gt his)], simp } end⟩ /-- The sample solution of a feasible tableau maximises the variable in row `r`, if every entry in that row is nonpositive and every entry in that row owned by a restricted variable is `0` -/ lemma is_maximised_of_col_zero {r : fin m} (hf : T.feasible) (h : ∀ j, T.to_matrix r j ≤ 0 ∧ (T.to_partition.colg j ∉ T.restricted → T.to_matrix r j = 0)) : T.is_maximised (T.of_col 0) (T.to_partition.rowg r) := λ x hx, begin rw [of_col_rowg, matrix.mul_zero, zero_add, mem_flat_iff.1 hx.1], refine add_le_of_nonpos_of_le _ (le_refl _), refine sum_nonpos (λ j _, _), by_cases hj : (T.to_partition.colg j) ∈ T.restricted, { refine mul_nonpos_of_nonpos_of_nonneg (h _).1 (hx.2 _ hj) }, { rw [(h _).2 hj, _root_.zero_mul] } end /-- Expression for the sum of all but one entries in the a row of a tableau. -/ lemma row_sum_erase_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n} : (univ.erase s).sum (λ j : fin n, T.to_matrix r j * x (T.to_partition.colg j) 0) = x (T.to_partition.rowg r) 0 - T.offset r 0 - T.to_matrix r s * x (colg (T.to_partition) s) 0 := begin rw [mem_flat_iff] at hx, conv_rhs { rw [hx r, ← insert_erase (mem_univ s), sum_insert (not_mem_erase _ _)] }, simp end /-- An expression for a column variable in terms of row variables. -/ lemma colg_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : x (T.to_partition.colg s) 0 = (x (T.to_partition.rowg r) 0 -(univ.erase s).sum (λ j : fin n, T.to_matrix r j * x (T.to_partition.colg j) 0) - T.offset r 0) * (T.to_matrix r s)⁻¹ := by simp [row_sum_erase_eq hx, mul_left_comm (T.to_matrix r s)⁻¹, mul_assoc, mul_left_comm (T.to_matrix r s), mul_inv_cancel hrs] /-- Another expression for a column variable in terms of row variables. -/ lemma colg_eq' {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : x (T.to_partition.colg s) 0 = univ.sum (λ (j : fin n), (if j = s then (T.to_matrix r s)⁻¹ else (-(T.to_matrix r j * (T.to_matrix r s)⁻¹))) * x (colg (swap (T.to_partition) r s) j) 0) - (T.offset r 0) * (T.to_matrix r s)⁻¹ := have (univ.erase s).sum (λ j : fin n, ite (j = s) (T.to_matrix r s)⁻¹ (-(T.to_matrix r j * (T.to_matrix r s)⁻¹)) * x (colg (swap (T.to_partition) r s) j) 0) = (univ.erase s).sum (λ j : fin n, -T.to_matrix r j * x (T.to_partition.colg j) 0 * (T.to_matrix r s)⁻¹), from finset.sum_congr rfl $ λ j hj, by simp [if_neg (mem_erase.1 hj).1, colg_swap_of_ne _ (mem_erase.1 hj).1, mul_comm, mul_assoc, mul_left_comm], by rw [← finset.insert_erase (mem_univ s), finset.sum_insert (not_mem_erase _ _), if_pos rfl, colg_swap, colg_eq hx hrs, this, ← finset.sum_mul]; simp [_root_.add_mul, mul_comm, _root_.mul_add] /-- Pivoting twice in the same place does nothing -/ @[simp] lemma pivot_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : (T.pivot r s).pivot r s = T := begin cases T, simp [pivot, function.funext_iff], split; intros; split_ifs; simp [*, mul_assoc, mul_left_comm (T_to_matrix r s), mul_left_comm (T_to_matrix r s)⁻¹, mul_comm (T_to_matrix r s), inv_mul_cancel hrs] end /- These two sets are equal_in_flat, the stronger lemma is `flat_pivot` -/ private lemma subset_flat_pivot {r : fin m} {s : fin n} (h : T.to_matrix r s ≠ 0) : T.flat ⊆ (T.pivot r s).flat := λ x hx, have ∀ i : fin m, (univ.erase s).sum (λ j : fin n, ite (j = s) (T.to_matrix i s * (T.to_matrix r s)⁻¹) (T.to_matrix i j + -(T.to_matrix i s * T.to_matrix r j * (T.to_matrix r s)⁻¹)) * x ((T.to_partition.swap r s).colg j) 0) = (univ.erase s).sum (λ j : fin n, T.to_matrix i j * x (T.to_partition.colg j) 0 - T.to_matrix r j * x (T.to_partition.colg j) 0 * T.to_matrix i s * (T.to_matrix r s)⁻¹), from λ i, finset.sum_congr rfl (λ j hj, by rw [if_neg (mem_erase.1 hj).1, colg_swap_of_ne _ (mem_erase.1 hj).1]; simp [mul_add, add_mul, mul_comm, mul_assoc, mul_left_comm]), begin rw mem_flat_iff, assume i, by_cases hir : i = r, { rw eq_comm at hir, subst hir, dsimp [pivot], simp [mul_inv_cancel h, neg_mul_eq_neg_mul_symm, if_true, add_comm, mul_inv_cancel, rowg_swap, eq_self_iff_true, colg_eq' hx h], congr, funext, congr }, { dsimp [pivot], simp only [if_neg hir], rw [← insert_erase (mem_univ s), sum_insert (not_mem_erase _ _), if_pos rfl, colg_swap, this, sum_sub_distrib, ← sum_mul, ← sum_mul, row_sum_erase_eq hx, rowg_swap_of_ne _ hir], simp [row_sum_erase_eq hx, mul_add, add_mul, mul_comm, mul_left_comm, mul_assoc], simp [mul_assoc, mul_left_comm (T.to_matrix r s), mul_left_comm (T.to_matrix r s)⁻¹, mul_comm (T.to_matrix r s), inv_mul_cancel h] } end variable (T) @[simp] lemma pivot_pivot_element (r : fin m) (s : fin n) : (T.pivot r s).to_matrix r s = (T.to_matrix r s)⁻¹ := by simp [pivot, if_pos rfl] @[simp] lemma pivot_pivot_row {r : fin m} {j s : fin n} (h : j ≠ s) : (T.pivot r s).to_matrix r j = -T.to_matrix r j / T.to_matrix r s := by dsimp [pivot]; rw [if_pos rfl, if_neg h, div_eq_mul_inv] @[simp] lemma pivot_pivot_column {i r : fin m} {s : fin n} (h : i ≠ r) : (T.pivot r s).to_matrix i s = T.to_matrix i s / T.to_matrix r s := by dsimp [pivot]; rw [if_neg h, if_pos rfl, div_eq_mul_inv] @[simp] lemma pivot_of_ne_of_ne {i r : fin m} {j s : fin n} (hir : i ≠ r) (hjs : j ≠ s) : (T.pivot r s).to_matrix i j = T.to_matrix i j - T.to_matrix i s * T.to_matrix r j / T.to_matrix r s := by dsimp [pivot]; rw [if_neg hir, if_neg hjs, div_eq_mul_inv] @[simp] lemma offset_pivot_row {r : fin m} {s : fin n} : (T.pivot r s).offset r 0 = -T.offset r 0 / T.to_matrix r s := by simp [pivot, if_pos rfl, div_eq_mul_inv] @[simp] lemma offset_pivot_of_ne {i r : fin m} {s : fin n} (hir : i ≠ r) : (T.pivot r s).offset i 0 = T.offset i 0 - T.to_matrix i s * T.offset r 0 / T.to_matrix r s := by dsimp [pivot]; rw [if_neg hir, div_eq_mul_inv] @[simp] lemma restricted_pivot (r s) : (T.pivot r s).restricted = T.restricted := rfl @[simp] lemma to_partition_pivot (r s) : (T.pivot r s).to_partition = T.to_partition.swap r s := rfl variable {T} @[simp] lemma flat_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : (T.pivot r s).flat = T.flat := set.subset.antisymm (by conv_rhs { rw ← pivot_pivot hrs }; exact subset_flat_pivot (by simp [hrs])) (subset_flat_pivot hrs) @[simp] lemma sol_set_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : (T.pivot r s).sol_set = T.sol_set := by rw [sol_set, flat_pivot hrs]; refl lemma feasible_pivot (hTf : T.feasible) {r : fin m} {c : fin n} (hc : T.offset r 0 / T.to_matrix r c ≤ 0) (h : ∀ i : fin m, i ≠ r → T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.offset i 0 - T.to_matrix i c * T.offset r 0 / T.to_matrix r c) : (T.pivot r c).feasible := assume i hi, if hir : i = r then begin subst hir, rw [offset_pivot_row], simpa [neg_div] using hc end else begin rw [to_partition_pivot, rowg_swap_of_ne _ hir, restricted_pivot] at hi, rw [offset_pivot_of_ne _ hir], simpa [offset_pivot_of_ne _ hir] using h _ hir hi end /-- Two row variables are `equal_in_flat` iff the corresponding rows of the tableau are equal -/ lemma equal_in_flat_row_row {i i' : fin m} : T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.rowg i') ↔ (T.offset i 0 = T.offset i' 0 ∧ ∀ j : fin n, T.to_matrix i j = T.to_matrix i' j) := ⟨λ h, have Hoffset : T.offset i 0 = T.offset i' 0, by simpa [of_col_rowg] using h (T.of_col 0) (of_col_mem_flat _ _), ⟨Hoffset, λ j, begin have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_rowg, add_val, add_val, matrix_mul_apply, matrix_mul_apply, symm_single_apply, Hoffset, add_right_cancel_iff] at this, end⟩, λ h x hx, by simp [mem_flat_iff.1 hx, h.1, h.2]⟩ /-- A row variable is equal_in_flat to a column variable iff its row has zeros, and a single one in that column. -/ lemma equal_in_flat_row_col {i : fin m} {j : fin n} : T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.colg j) ↔ (∀ j', j' ≠ j → T.to_matrix i j' = 0) ∧ T.offset i 0 = 0 ∧ T.to_matrix i j = 1 := ⟨λ h, have Hoffset : T.offset i 0 = 0, by simpa using h (T.of_col 0) (of_col_mem_flat _ _), ⟨assume j' hj', begin have := h (T.of_col (single j' (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_colg, add_val, Hoffset, add_zero, matrix_mul_apply, symm_single_apply, pequiv.to_matrix, single_apply_of_ne hj', if_neg (option.not_mem_none _)] at this end, Hoffset, begin have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_colg, add_val, Hoffset, add_zero, matrix_mul_apply, symm_single_apply, pequiv.to_matrix, single_apply] at this end⟩, by rintros ⟨h₁, h₂, h₃⟩ x hx; rw [mem_flat_iff.1 hx, h₂, sum_eq_single j]; simp *; tauto⟩ end predicate_lemmas /-- definition used to define well-foundedness of a pivot rule -/ inductive rel_gen {α : Type*} (f : α → option α) : α → α → Prop | of_mem : ∀ {x y}, x ∈ f y → rel_gen x y | trans : ∀ {x y z}, rel_gen x y → rel_gen y z → rel_gen x z /-- A pivot rule is a function that selects a nonzero pivot, given a tableau, such that iterating using this pivot rule terminates. -/ structure pivot_rule (m n : ℕ) : Type := (pivot_indices : tableau m n → option (fin m × fin n)) (well_founded : well_founded (rel_gen (λ T, pivot_indices T >>= λ i, T.pivot i.1 i.2))) (ne_zero : ∀ {T r s}, (r, s) ∈ pivot_indices T → T.to_matrix r s ≠ 0) def pivot_rule.rel (p : pivot_rule m n) : tableau m n → tableau m n → Prop := rel_gen (λ T, p.pivot_indices T >>= λ i, T.pivot i.1 i.2) lemma pivot_rule.rel_wf (p : pivot_rule m n) : well_founded p.rel := p.well_founded def iterate (p : pivot_rule m n) : tableau m n → tableau m n | T := have ∀ (r : fin m) (s : fin n), (r, s) ∈ p.pivot_indices T → p.rel (T.pivot r s) T, from λ r s hrs, rel_gen.of_mem $ by rw option.mem_def.1 hrs; exact rfl, option.cases_on (p.pivot_indices T) (λ _, T) (λ i this, have wf : p.rel (T.pivot i.1 i.2) T, from this _ _ (by cases i; exact rfl), iterate (T.pivot i.1 i.2)) this using_well_founded { rel_tac := λ _ _, `[exact ⟨_, p.rel_wf⟩], dec_tac := tactic.assumption } lemma iterate_pivot {p : pivot_rule m n} {T : tableau m n} {r : fin m} {s : fin n} (hrs : (r, s) ∈ p.pivot_indices T) : (T.pivot r s).iterate p = T.iterate p := by conv_rhs {rw iterate}; simp [option.mem_def.1 hrs] @[simp] lemma pivot_indices_iterate (p : pivot_rule m n) : ∀ (T : tableau m n), p.pivot_indices (T.iterate p) = none | T := have ∀ r s, (r, s) ∈ p.pivot_indices T → p.rel (T.pivot r s) T, from λ r s hrs, rel_gen.of_mem $ by rw option.mem_def.1 hrs; exact rfl, begin rw iterate, cases h : p.pivot_indices T with i, { simp [h] }, { cases i with r s, simp [h, pivot_indices_iterate (T.pivot r s)] } end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, p.rel_wf⟩], dec_tac := `[tauto] } /- Is there some nice elaborator attribute for this, to avoid `P` having to be explicit? -/ lemma iterate_induction_on (P : tableau m n → Prop) (p : pivot_rule m n) : ∀ T : tableau m n, P T → (∀ T' r s, P T' → (r, s) ∈ p.pivot_indices T' → P (T'.pivot r s)) → P (T.iterate p) | T := λ hT ih, have ∀ r s, (r, s) ∈ p.pivot_indices T → p.rel (T.pivot r s) T, from λ r s hrs, rel_gen.of_mem $ by rw option.mem_def.1 hrs; exact rfl, begin rw iterate, cases h : p.pivot_indices T with i, { simp [hT, h] }, { cases i with r s, simp [h, iterate_induction_on _ (ih _ _ _ hT h) ih] } end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, p.rel_wf⟩], dec_tac := `[tauto] } @[simp] lemma iterate_flat (p : pivot_rule m n) (T : tableau m n) : (T.iterate p).flat = T.flat := iterate_induction_on (λ T', T'.flat = T.flat) p T rfl $ assume T' r s (hT' : T'.flat = T.flat) hrs, by rw [← hT', flat_pivot (p.ne_zero hrs)] @[simp] lemma iterate_sol_set (p : pivot_rule m n) (T : tableau m n) : (T.iterate p).sol_set = T.sol_set := iterate_induction_on (λ T', T'.sol_set = T.sol_set) p T rfl $ assume T' r s (hT' : T'.sol_set = T.sol_set) hrs, by rw [← hT', sol_set_pivot (p.ne_zero hrs)] namespace simplex def find_pivot_column (T : tableau m n) (obj : fin m) : option (fin n) := option.cases_on (fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted)) (fin.find (λ c : fin n, 0 < T.to_matrix obj c)) some def find_pivot_row (T : tableau m n) (obj: fin m) (c : fin n) : option (fin m) := let l := (list.fin_range m).filter (λ r : fin m, obj ≠ r ∧ T.to_partition.rowg r ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix r c < 0) in l.argmin (λ r', abs (T.offset r' 0 / T.to_matrix r' c)) lemma find_pivot_column_spec {T : tableau m n} {obj : fin m} {s : fin n} : s ∈ find_pivot_column T obj → (T.to_matrix obj s ≠ 0 ∧ T.to_partition.colg s ∉ T.restricted) ∨ (0 < T.to_matrix obj s ∧ T.to_partition.colg s ∈ T.restricted) := begin simp [find_pivot_column], cases h : fin.find (λ s : fin n, T.to_matrix obj s ≠ 0 ∧ T.to_partition.colg s ∉ T.restricted), { finish [h, fin.find_eq_some_iff, fin.find_eq_none_iff, lt_irrefl (0 : ℚ)] }, { finish [fin.find_eq_some_iff] } end -- lemma find_pivot_column_eq_none_aux {T : tableau m n} {i : fin m} {s : fin n} : -- find_pivot_column T i = none ↔ (∀ s, T.to_matrix i s ≤ 0) := -- begin -- simp [find_pivot_column, fin.find_eq_none_iff], -- cases h : fin.find (λ s : fin n, T.to_matrix i s ≠ 0 ∧ T.to_partition.colg s ∉ T.restricted), -- { finish [fin.find_eq_none_iff] }, -- { simp [find_eq_some_iff] at *, } -- end lemma find_pivot_column_eq_none {T : tableau m n} {obj : fin m} (hT : T.feasible) (h : find_pivot_column T obj = none) : T.is_maximised (T.of_col 0) (T.to_partition.rowg obj) := is_maximised_of_col_zero hT begin revert h, simp [find_pivot_column], cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted), { finish [fin.find_eq_none_iff] }, { simp [h] } end lemma find_pivot_row_spec {T : tableau m n} {obj r : fin m} {c : fin n} : r ∈ find_pivot_row T obj c → obj ≠ r ∧ T.to_partition.rowg r ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix r c < 0 ∧ (∀ r' : fin m, obj ≠ r' → T.to_partition.rowg r' ∈ T.restricted → T.to_matrix obj c / T.to_matrix r' c < 0 → abs (T.offset r 0 / T.to_matrix r c) ≤ abs (T.offset r' 0 / T.to_matrix r' c)) := by simp only [list.mem_argmin_iff, list.mem_filter, find_pivot_row, list.mem_fin_range, true_and, and_imp]; tauto lemma find_pivot_row_eq_none_aux {T : tableau m n} {obj : fin m} {c : fin n} (hrow : find_pivot_row T obj c = none) (hs : c ∈ find_pivot_column T obj) : ∀ r, obj ≠ r → T.to_partition.rowg r ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix r c := by simpa [find_pivot_row, list.filter_eq_nil] using hrow lemma find_pivot_row_eq_none {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible) (hrow : find_pivot_row T obj c = none) (hs : c ∈ find_pivot_column T obj) : T.is_unbounded_above (T.to_partition.rowg obj) := have hrow : ∀ r, obj ≠ r → T.to_partition.rowg r ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix r c, from find_pivot_row_eq_none_aux hrow hs, have hc : (T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted), from find_pivot_column_spec hs, have hToc : T.to_matrix obj c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hc, (lt_or_gt_of_ne hToc).elim (λ hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c (hc.elim and.right (λ h, (not_lt_of_gt hToc h.1).elim)) (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc)) hToc) (λ hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc)) hToc) /-- This `pivot_rule` maximises the sample value of `i` -/ def simplex_pivot_rule (i : fin m) : pivot_rule m n := { pivot_indices := λ T, find_pivot_column T i >>= λ s, find_pivot_row T i s >>= λ r, some (r, s), well_founded := sorry, ne_zero := λ T r s, begin simp only [option.mem_def, option.bind_eq_some, find_pivot_row, list.argmin_eq_some_iff, and_imp, exists_imp_distrib, prod.mk.inj_iff, list.mem_filter], intros, substs x r, assume h, simp [h, lt_irrefl, *] at * end } end simplex def simplex (T : tableau m n) (i : fin m) : tableau m n := T.iterate (simplex.simplex_pivot_rule i) namespace simplex /-- The simplex algorithm does not pivot the variable it is trying to optimise -/ lemma simplex_pivot_indices_ne {T : tableau m n} {i : fin m} {r s} : (r, s) ∈ (simplex_pivot_rule i).pivot_indices T → i ≠ r := by simp only [simplex_pivot_rule, find_pivot_row, fin.find_eq_some_iff, option.mem_def, list.mem_filter, option.bind_eq_some, prod.mk.inj_iff, exists_imp_distrib, and_imp, list.argmin_eq_some_iff, @forall_swap _ (_ = r), @forall_swap (_ ≠ r), imp_self, forall_true_iff] {contextual := tt} /-- `simplex` does not move the row variable it is trying to maximise. -/ lemma rowg_simplex (T : tableau m n) (i : fin m) : (T.simplex i).to_partition.rowg i = T.to_partition.rowg i := iterate_induction_on (λ T', T'.to_partition.rowg i = T.to_partition.rowg i) _ _ rfl $ assume T' r s (hT' : T'.to_partition.rowg i = T.to_partition.rowg i) hrs, by rw [to_partition_pivot, rowg_swap_of_ne _ (simplex_pivot_indices_ne hrs), hT'] lemma simplex_pivot_rule_eq_none {T : tableau m n} {i : fin m} (hT : T.feasible) (h : (simplex_pivot_rule i).pivot_indices T = none) : is_maximised T (T.of_col 0) (T.to_partition.rowg i) ∨ is_unbounded_above T (T.to_partition.rowg i) := begin cases hs : find_pivot_column T i with s, { exact or.inl (find_pivot_column_eq_none hT hs) }, { dsimp [simplex_pivot_rule] at h, rw [hs, option.some_bind, option.bind_eq_none] at h, have : find_pivot_row T i s = none, { exact option.eq_none_iff_forall_not_mem.2 (λ r, by simpa using h (r, s) r) }, exact or.inr (find_pivot_row_eq_none hT this hs) } end @[simp] lemma mem_simplex_pivot_rule_indices {T : tableau m n} {i : fin m} {r s} : (r, s) ∈ (simplex_pivot_rule i).pivot_indices T ↔ s ∈ find_pivot_column T i ∧ r ∈ find_pivot_row T i s := begin simp only [simplex_pivot_rule, option.mem_def, option.bind_eq_some, prod.mk.inj_iff, and_comm _ (_ = r), @and.left_comm _ (_ = r), exists_eq_left, and.assoc], simp only [and_comm _ (_ = s), @and.left_comm _ (_ = s), exists_eq_left] end lemma simplex_pivot_rule_feasible {T : tableau m n} {i : fin m} (hT : T.feasible) {r s} (hrs : (r, s) ∈ (simplex_pivot_rule i).pivot_indices T) : (T.pivot r s).feasible := λ i' hi', begin rw [mem_simplex_pivot_rule_indices] at hrs, have hs := find_pivot_column_spec hrs.1, have hr := find_pivot_row_spec hrs.2, dsimp only [pivot], by_cases hir : i' = r, { subst i', rw [if_pos rfl, neg_mul_eq_neg_mul_symm, neg_nonneg], exact mul_nonpos_of_nonneg_of_nonpos (hT _ hr.2.1) (le_of_lt (neg_of_mul_neg_left hr.2.2.1 (le_of_lt (by simp * at *)))) }, { rw if_neg hir, rw [to_partition_pivot, rowg_swap_of_ne _ hir, restricted_pivot] at hi', by_cases hii : i = i', { subst i', refine add_nonneg (hT _ hi') (neg_nonneg.2 _), rw [mul_assoc, mul_left_comm], exact mul_nonpos_of_nonneg_of_nonpos (hT _ hr.2.1) (le_of_lt hr.2.2.1) }, { by_cases hTi'r : 0 < T.to_matrix i' s / T.to_matrix r s, { have hTi's0 : T.to_matrix i' s ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTi'r, have hTrs0 : T.to_matrix r s ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTi'r, have hTii' : T.to_matrix i s / T.to_matrix i' s < 0, { suffices : (T.to_matrix i s / T.to_matrix r s) / (T.to_matrix i' s / T.to_matrix r s) < 0, { simp only [div_eq_mul_inv, mul_assoc, mul_inv', inv_inv', mul_left_comm (T.to_matrix r s), mul_left_comm (T.to_matrix r s)⁻¹, mul_comm (T.to_matrix r s), inv_mul_cancel hTrs0, mul_one] at this, simpa [mul_comm, div_eq_mul_inv] }, { exact div_neg_of_neg_of_pos hr.2.2.1 hTi'r } }, have := hr.2.2.2 _ hii hi' hTii', rwa [abs_div, abs_div, abs_of_nonneg (hT _ hr.2.1), abs_of_nonneg (hT _ hi'), le_div_iff (abs_pos_iff.2 hTi's0), div_eq_mul_inv, mul_right_comm, ← abs_inv, mul_assoc, ← abs_mul, ← div_eq_mul_inv, abs_of_nonneg (le_of_lt hTi'r), ← sub_nonneg, ← mul_div_assoc, div_eq_mul_inv, mul_comm (T.offset r 0)] at this }, { refine add_nonneg (hT _ hi') (neg_nonneg.2 _), rw [mul_assoc, mul_left_comm], exact mul_nonpos_of_nonneg_of_nonpos (hT _ hr.2.1) (le_of_not_gt hTi'r) } } } end lemma simplex_feasible {T : tableau m n} (hT : T.feasible) (i : fin m) : (simplex T i).feasible := iterate_induction_on feasible _ _ hT (λ _ _ _ hT, simplex_pivot_rule_feasible hT) lemma simplex_unbounded_or_maximised {T : tableau m n} (hT : T.feasible) (i : fin m) : is_maximised (simplex T i) ((simplex T i).of_col 0) (T.to_partition.rowg i) ∨ is_unbounded_above (simplex T i) (T.to_partition.rowg i) := by rw ← rowg_simplex; exact simplex_pivot_rule_eq_none (simplex_feasible hT i) (pivot_indices_iterate _ _) @[simp] lemma simplex_flat {T : tableau m n} (i : fin m) : flat (T.simplex i) = T.flat := iterate_flat _ _ @[simp] lemma simplex_sol_set {T : tableau m n} (i : fin m) : sol_set (T.simplex i) = T.sol_set := iterate_sol_set _ _ end simplex section add_row /-- adds a new row without making it a restricted variable. -/ def add_row (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) : tableau (m + 1) n := { to_matrix := λ i j, if hm : i.1 < m then T.to_matrix (fin.cast_lt i hm) j else fac 0 (T.to_partition.colg j) + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.to_matrix i' j), offset := λ i j, if hm : i.1 < m then T.offset (fin.cast_lt i hm) j else const + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.offset i' 0), to_partition := T.to_partition.add_row, restricted := T.restricted.map ⟨fin.castp, λ ⟨_, _⟩ ⟨_, _⟩ h, fin.eq_of_veq (fin.veq_of_eq h : _)⟩ } @[simp] lemma add_row_to_partition (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) : (T.add_row fac const).to_partition = T.to_partition.add_row := rfl lemma add_row_to_matrix (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) : (T.add_row fac const).to_matrix = λ i j, if hm : i.1 < m then T.to_matrix (fin.cast_lt i hm) j else fac 0 (T.to_partition.colg j) + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.to_matrix i' j) := rfl lemma add_row_offset (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) : (T.add_row fac const).offset = λ i j, if hm : i.1 < m then T.offset (fin.cast_lt i hm) j else const + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.offset i' 0) := rfl lemma add_row_restricted (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) : (T.add_row fac const).restricted = T.restricted.image fin.castp := by simp [add_row, map_eq_image] @[simp] lemma fin.cast_lt_cast_succ {n : ℕ} (a : fin n) (h : a.1 < n) : a.cast_succ.cast_lt h = a := by cases a; refl lemma minor_mem_flat_of_mem_add_row_flat {T : tableau m n} {fac : rvec (m + n)} {const : ℚ} {x : cvec (m + 1 + n)} : x ∈ (T.add_row fac const).flat → minor x fin.castp id ∈ T.flat := begin rw [mem_flat_iff, mem_flat_iff], intros h r, have := h (fin.cast_succ r), simp [add_row_rowg_cast_succ, add_row_offset, add_row_to_matrix, (show (fin.cast_succ r).val < m, from r.2), add_row_colg] at this, simpa end lemma minor_mem_sol_set_of_mem_add_row_sol_set {T : tableau m n} {fac : rvec (m + n)} {const : ℚ} {x : cvec (m + 1 + n)} : x ∈ (T.add_row fac const).sol_set → minor x fin.castp id ∈ T.sol_set := and_implies minor_mem_flat_of_mem_add_row_flat begin assume h v, simp only [set.mem_set_of_eq, add_row_restricted, mem_image, exists_imp_distrib] at h, simpa [add_row_restricted, matrix.minor, id.def] using h (fin.castp v) v end lemma add_row_new_eq_sum_fac (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) (x : cvec (m + 1 + n)) (hx : x ∈ (T.add_row fac const).flat) : x fin.lastp 0 = univ.sum (λ v : fin (m + n), fac 0 v * x (fin.castp v) 0) + const := calc x fin.lastp 0 = x ((T.add_row fac const).to_partition.rowg (fin.last _)) 0 : by simp [add_row_rowg_last] ... = univ.sum (λ j : fin n, _) + (T.add_row fac const).offset _ _ : mem_flat_iff.1 hx _ ... = const + univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) + (univ.sum (λ j, univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.to_matrix i j * x (T.to_partition.add_row.colg j) 0)) + univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.offset i 0)) : by simp [add_row_to_matrix, add_row_offset, fin.last, add_mul, sum_add_distrib, sum_mul] ... = const + univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) + (univ.sum (λ i, univ.sum (λ j, fac 0 (T.to_partition.rowg i) * T.to_matrix i j * x (T.to_partition.add_row.colg j) 0)) + univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.offset i 0)) : by rw [sum_comm] ... = const + univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) + univ.sum (λ i : fin m, (fac 0 (T.to_partition.rowg i) * x (fin.castp (T.to_partition.rowg i)) 0)) : begin rw [← sum_add_distrib], have : ∀ r : fin m, x (fin.castp (T.to_partition.rowg r)) 0 = sum univ (λ (c : fin n), T.to_matrix r c * x (fin.castp (T.to_partition.colg c)) 0) + T.offset r 0, from mem_flat_iff.1 (minor_mem_flat_of_mem_add_row_flat hx), simp [this, mul_add, add_row_colg, mul_sum, mul_assoc] end ... = ((univ.image T.to_partition.colg).sum (λ v, (fac 0 v * x (fin.castp v) 0)) + (univ.image T.to_partition.rowg).sum (λ v, (fac 0 v * x (fin.castp v) 0))) + const : by rw [sum_image, sum_image]; simp [add_row_rowg_cast_succ, add_row_colg, T.to_partition.injective_rowg.eq_iff, T.to_partition.injective_colg.eq_iff] ... = _ : begin rw [← sum_union], congr, simpa [finset.ext, eq_comm] using T.to_partition.eq_rowg_or_colg, { simp [finset.ext, eq_comm, T.to_partition.rowg_ne_colg] {contextual := tt} } end end add_row open tableau.simplex /-- Boolean returning whether -/ def max_nonneg (T : tableau m n) (i : fin m) : bool := 0 ≤ (simplex T i).offset i 0 lemma max_nonneg_iff (T : tableau m n) (hT : T.feasible) (i : fin m) : T.max_nonneg i ↔ ∃ x : cvec (m + n), x ∈ T.sol_set ∧ 0 ≤ x (T.to_partition.rowg i) 0 := by simp [max_nonneg, bool.of_to_bool_iff]; exact ⟨λ h, ⟨(T.simplex i).of_col 0, by rw [← simplex_sol_set i, ← feasible_iff_of_col_zero_mem_sol_set]; exact simplex_feasible hT _, _⟩ , _⟩ section assertge end assertge end tableau section test open tableau tableau.simplex def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ := λ i j, (l.nth_le i sorry).nth_le j sorry instance has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) := ⟨λ f, repr (vector.of_fn f).to_list⟩ instance {m n} : has_repr (matrix (fin m) (fin n) ℚ) := has_repr_fin_fun -- def T : tableau 4 5 := -- { to_matrix := list.to_matrix 4 5 [[1, 3/4, -20, 1/2, -6], [0, 1/4, -8, -1, 9], -- [0, 1/2, -12, 1/2, 3], [0,0,0,1,0]], -- offset := (list.to_matrix 1 4 [[-3,0,0,1]])ᵀ, -- to_partition := default _, -- restricted := univ.erase 6 } def T : tableau 25 10 := { to_matrix := list.to_matrix 25 10 [[0, 0, 0, 0, 1, 0, 1, 0, 1, -1], [-1, 1, 0, -1, 1, 0, 1, -1, 0, 0], [0, -1, 1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 0, 1, -1, 1, -1, 1, -1], [0, 1, 1, -1, -1, 1, -1, 1, -1, 1], [0, -1, 1, -1, 1, 1, 0, 1, 0, -1], [-1, 0, 0, -1, -1, 1, 1, 0, -1, -1], [-1, 0, 0, -1, 0, -1, 0, 0, -1, 1], [-1, 0, 0, 1, -1, 1, -1, -1, 1, 0], [1, 0, 0, 0, 1, -1, 1, 0, -1, 1], [0, -1, 1, 0, 0, 1, 0, -1, 0, 0], [-1, 1, -1, 1, 1, 0, 1, 0, 1, 0], [1, 1, 1, 1, -1, 0, 0, 0, -1, 0], [-1, -1, 0, 0, 1, 0, 1, 1, -1, 0], [0, 0, -1, 1, -1, 0, 0, 1, 0, -1], [-1, 0, -1, 1, 1, 1, 0, 0, 0, 0], [ 1, 0, -1, 1, 0, -1, -1, 1, -1, 1], [-1, 1, -1, 1, -1, -1, -1, 1, -1, 1], [-1, 0, 0, 0, 1, -1, 1, -1, -1, 1], [-1, -1, -1, 1, 0, 1, -1, 1, 0, 0], [-1, 0, 0, 0, -1, -1, 1, -1, 0, 1], [-1, 0, 0, -1, 1, 1, 1, -1, 1, 0], [0, -1, 0, 0, 0, -1, 0, 1, 0, -1], [1, -1, 1, 0, 0, 1, 0, 1, 0, -1], [0, -1, -1, 0, 0, 0, -1, 0, 1, 0]], offset := λ i _, if i.1 < 8 then 0 else 1, to_partition := default _, restricted := univ } def Beale : tableau 4 4 := { to_matrix := list.to_matrix 4 4 [[3/4, -150, 1/50, -6], [-1/4, 60,1/25,-9], [-1/2,90,1/50,-3], [0,0,-1,0]], offset := λ i k, if i = 3 then 1 else 0, to_partition := default _, restricted := univ } def Yudin_golstein : tableau 4 4 := { to_matrix := list.to_matrix 4 4 [[1,-1,1,-1], [-2,3,5,-6], [-6,5,3,-2], [-3,-1,-2,-4]], offset := λ i k, if i = 3 then 1 else 0, to_partition := default _, restricted := univ } def Kuhn : tableau 4 4 := { to_matrix := list.to_matrix 4 4 [[2,3,-1,-12], [2,9,-1,-9], [-1/3,-1,1/3,2], [-2,-3,1,12]], offset := λ i k, if i = 3 then 2 else 0, to_partition := default _, restricted := univ } def me : tableau 3 2 := { to_matrix := list.to_matrix 3 2 [[1/2, 1], [1, 1], [-1, 1]], offset := 0, to_partition := default _, restricted := univ } def tableau.flip_up : tableau m n → tableau m n := λ T, { to_matrix := λ i j, T.to_matrix ⟨(-i-1 : ℤ).nat_mod m, sorry⟩ j, offset := λ i j, T.offset ⟨(-i - 1 : ℤ).nat_mod m, sorry⟩ j, to_partition := T.to_partition, restricted := univ } #eval let A := me in ((A.simplex 0).to_matrix, (A.flip_up.simplex 3).to_matrix) -- def T : tableau 4 5 := -- { to_matrix := list.to_matrix 4 5 [[1, 3/5, 20, 1/2, -6], [19, 1, -8, -1, 9], -- [5, 1/2, -12, 1/2, 3], [13,0.1,11,21,0]], -- offset := (list.to_matrix 1 4 [[3,1,51,1]])ᵀ, -- to_partition := default _, -- restricted := univ } --set_option profiler true #print algebra.sub -- def T : tableau 25 10 := -- { to_matrix := list.to_matrix 25 10 -- [[1,0,1,-1,-1,-1,1,-1,1,1],[0,1,-1,1,1,1,-1,1,-1,1],[0,1,-1,1,-1,0,-1,-1,-1,0],[1,1,-1,-1,-1,-1,-1,1,-1,-1],[0,-1,1,1,0,-1,1,-1,1,-1],[0,1,1,0,1,1,0,1,0,1],[0,1,0,1,0,1,1,0,-1,-1],[0,0,-1,1,1,0,0,0,1,-1],[0,0,1,0,1,-1,-1,0,1,1],[0,-1,0,0,1,-1,-1,1,0,0],[0,-1,1,0,0,1,0,-1,1,0],[1,1,1,-1,1,-1,-1,0,-1,1],[1,1,-1,-1,-1,1,-1,1,-1,-1],[-1,-1,-1,1,1,1,1,1,-1,-1],[0,1,0,0,1,-1,0,0,-1,1],[-1,-1,-1,-1,1,1,1,0,-1,1],[0,0,-1,-1,0,1,1,-1,1,1],[1,0,1,0,0,0,1,0,0,1],[-1,0,-1,0,1,1,-1,1,1,-1],[0,1,-1,1,-1,0,0,-1,-1,-1],[1,1,0,1,1,0,1,1,-1,1],[0,0,0,0,0,1,-1,1,0,-1],[1,1,0,0,-1,1,0,0,1,0],[0,0,-1,1,-1,1,-1,1,-1,-1],[0,0,0,0,1,-1,1,1,-1,-1]], -- offset := λ i _, 1, -- to_partition := default _, -- restricted := univ } #print random_gen #print tc.rec #print nat #eval let s := T.simplex 0 in (s.to_partition.row_indices).1 end test
4028045465c05b774df9d0f15ffa93672a59212d
359199d7253811b032ab92108191da7336eba86e
/src/homework/hw3.lean
fcabad5f27ae84b3136140548606372a7d4367af
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
17,845
lean
/- Prove the following simple logical conjectures. Give a formal and an English proof of each one. Your English language proofs should be complete in the sense that they identify all the axioms and/or theorems that you use. -/ -- #1 example : true := true.intro /- True is true by its introduction rule. -/ -- #2 example : false := _ /- A proof cannot be constructed for false. -/ -- #3 example : ∀ (P : Prop), P ∨ P ↔ P := begin assume P, apply iff.intro _ _, -- forwards assume p_or_p, apply or.elim p_or_p, assume p, exact p, assume p, exact p, -- backwards assume p, exact or.intro_left P p, end /- To prove the provided proposition, first assume that we have some proposition, P. Then, apply the if-and- only-if introduction rule to the two proofs that it requires. The first proof that it requires is that of the forwards direction implies proposition, P ∨ P → P. The second proof that it requires is that of the backwards direction implies proposition, P → P ∨ P. To acquire the first proof, begin by assuming that the premise of the proposition is true. Then, apply the or elimination rule to this assumed proof. With this, perform case analysis. For both cases, assume that there is a proof of P, and then, exact (or apply) that proof. To get the second proof, first assume P, then use the left introduction rule on our assumed proof of P and the proposition P. -/ -- #4 example : ∀ (P : Prop), P ∧ P ↔ P := begin assume P, apply iff.intro _ _, -- forwards assume pandp, apply and.elim_left pandp, -- backwards assume p, apply and.intro p p, end /- To prove the provided proposition, first assume that we have some proposition, P. Then, apply the if-and- only-if introduction rule to the two proofs that it requires. The first proof that it requires is that of the forwards direction implies proposition. The second proof that it requires is that of the backwards direction implies proposition. The proof of P ∧ P → P is begun by assuming that P ∧ P is true through the "implies" introduction rule. With this, we may start working on our proof of P. We prove P by applying the left "and" elimination rule on our proof of P ∧ P, pandp, which gives to us a proof of P. The proof of P → P ∧ P is started by assuming that P is true. To prove an "and" proposition, we need both sides of the proposition to be true, so we apply the "and" introduction rule to the proofs of P. -/ -- #5 example : ∀ (P Q : Prop), P ∨ Q ↔ Q ∨ P := begin assume P Q, apply iff.intro _ _, -- forwards assume porq, apply or.elim porq, assume p, apply or.intro_right Q p, assume q, apply or.intro_left P q, -- backwards assume qorp, apply or.elim qorp, assume q, apply or.intro_right P q, assume p, apply or.intro_left Q p, end /- To prove the provided proposition, first assume that we have some proposition, P. Then, apply the if-and- only-if introduction rule to the two proofs that it requires. The first proof that it requires is that of the forwards direction implies proposition. The second proof that it requires is that of the backwards direction implies proposition. The proof of P ∨ Q → Q ∨ P starts by assuming that our P ∨ Q proposition is true ("implies" introduction rule). We must then apply the "or" elimination rule to our proof of the aforementioned proposition to perform case analysis, where we show that in either case (P is true or Q is true) our conclusion will be true. For the first case we assume P, and to get our proof of the larger "or" proposition we use the right "or" introduction rule on our proposition Q and our assumed P. For the second case we assume Q and use the left "or" introduction rule on our proposition P and our assumed Q. The proof of Q ∨ P → P ∨ Q begins by assuming our premise. The "or" elimination rule is used on our (assumed) proof of the premise. With that, we start on our first case by assuming a proof of Q and generating the needed proof with the right "or" introduction rule on the proposition P and the proof of Q. We account for the second case by assuming a proof of P and using the left "or" introduction rule on the proposition Q and our proof of P. -/ -- #6 example : ∀ (P Q : Prop), P ∧ Q ↔ Q ∧ P := begin assume P Q, apply iff.intro _ _, -- forwards assume pandq, -- now, to prove Q ∧ P, I need a proof of Q AND a proof of P apply and.intro _ _, apply and.elim_right pandq, -- fills in the first slot above with a proof of Q apply and.elim_left pandq, -- fills in the second slot above with a proof of P -- backwards assume qandp, -- assuming that the left side of my proposition is true (the proposition: Q ∧ P → P ∧ Q) apply and.intro _ _, apply and.elim_right qandp, apply and.elim_left qandp, end /- To prove the provided proposition, first assume that we have some proposition, P. Then, apply the if-and- only-if introduction rule to the two proofs that it requires. The first proof that it requires is that of the forwards direction implies proposition. The second proof that it requires is that of the backwards direction implies proposition. To prove that if P ∧ Q, then Q ∧ P, first assume that P ∧ Q is true by the "implies" introduction rule. To prove an "and" proposition, we need to have two proofs - one for each side of the "and". As such, we use the right "and" elimination rule to get a proof of Q and the left "and" elimination rule to get a proof of P. The "and" introduction rule uses these two proofs to give us a proof of the larger "and" proposition, Q ∧ P. Proving that if Q ∧ P, then P ∧ Q requires that we first assume that Q ∧ P is true (we have a proof of this). We follow a similar process to the one above by using the right "and" elimination rule to get a proof of P from our assumed proof of the premise and the left "and" elimination rule to get a proof of Q. The "and" introduction rule takes our proof of P and our proof of Q to spit out our proof of P ∧ Q. -/ -- #7 example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := -- "if P and (Q or R), then (P and Q) or (P and R)" -- "if (P and Q) or (P and R), then P and (Q or R)" begin assume P Q R, apply iff.intro _ _, -- forwards assume pqr, have p : P := and.elim_left pqr, have qr : Q ∨ R := and.elim_right pqr, apply or.elim qr, -- creates 2 goals (case analysis) assume q, apply or.intro_left (P ∧ R) (and.intro p q), assume r, apply or.intro_right (P ∧ Q) (and.intro p r), -- backwards assume pandq_or_pandr, apply and.intro _ _, apply or.elim pandq_or_pandr, -- before: goals were to provide a proof of P and a proof of Q ∨ R; now: get a proof of p from the sub-and props. -- assume the left side of the first sub-and prop (which is P ∧ Q) assume pandq, apply and.elim_left pandq, -- assume the left side of the second sub-and prop (which is P ∧ R) assume pandr, apply and.elim_left pandr, -- 1 goal left: prove Q ∨ R apply or.elim pandq_or_pandr, assume pandq, -- to get proof of Q apply or.intro_left R (and.elim_right pandq), -- q (proof of Q) is in the parentheses assume pandr, -- to get proof of R apply or.intro_right Q (and.elim_right pandr), end /- To prove the provided proposition, first assume that we have some proposition, P. Then, apply the if-and- only-if introduction rule to the two proofs that it requires. The first proof that it requires is that of the forwards direction implies proposition. The second proof that it requires is that of the backwards direction implies proposition. P ∧ (Q ∨ R) → (P ∧ Q) ∨ (P ∧ R) by the use of the "implies" introduction rule, which assumes our premise is true. Given this proof, we may have an additional proof of P, which is obtained by using the left "and" elimination rule, and a a proof of Q ∨ R, which is obtained by using the right "and" elimination rule. We further divide up our original proposition by using the "or" elimination rule on the proof of Q ∨ R. With this, we may perform case analysis. First, we assume Q and obtain a proof of the conclusion with the proposition P ∧ R and our constructed proof of P ∧ Q (left "or" intro rule). Then, we assume R and use the right "or" intro rule to obtain a proof of the conclusion in this case with the proposition P ∧ Q and our constructed "and" proof of P ∧ R. Like with P ∧ Q, we used the "and" introduction rule. (P ∧ Q) ∨ (P ∧ R) → P ∧ (Q ∨ R) with the assumption that (P ∧ Q) ∨ (P ∧ R) is true. We want to prove an "and" proposition, so we use the "and" introduction rule, which needs proofs of its side propositions. We use the "or" elimination rule to perform case analysis for its sides. The left side, we assume as true and apply the left "and" elimination rule to retrieve a proof of P. Then, we assume P ∧ R is true and apply the left "and" elimination rule to it to get a proof of P. The remaining side to prove is Q ∨ R, so we apply the "or" elimination rule to do case analysis. We assume P ∧ Q and prove the larger "or" proposition by applying the left "or" intro rule on our proof of q which was obtained by applying the right "and" elimination rule on P ∧ Q. Finally, we assume P ∧ R is true, this proof is applied with the right "or" intro rule with the proposition Q and a proof of R through the right "and" elimination rule on P ∧ R. -/ -- #8 example : ∀ (P Q R : Prop), P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := begin assume P Q R, apply iff.intro _ _, -- forwards assume p_or_qandr, apply or.elim p_or_qandr, assume p, apply and.intro _ _, ---- Goal: Prove P ∨ Q. apply or.intro_left Q p, ---- Goal: Prove P ∨ R. apply or.intro_left R p, assume qandr, apply and.intro _ _, ---- Goal: Prove P ∨ Q. (w/ a proof of Q) apply or.intro_right P (and.elim_left qandr), ---- Goal: Prove P ∨ R. (w/ a proof of R) apply or.intro_right P (and.elim_right qandr), -- backwards assume porq_and_porr, have porq : P ∨ Q := and.elim_left porq_and_porr, have porr : P ∨ R := and.elim_right porq_and_porr, apply or.elim porq, assume p, apply or.intro_left (Q ∧ R) p, assume q, apply or.elim porr, --! assume p, apply or.intro_left (Q ∧ R) p, assume r, apply or.intro_right P (and.intro q r), end /- To prove the provided proposition, first assume that we have some proposition, P. Then, apply the if-and- only-if introduction rule to the two proofs that it requires. The first proof that it requires is that of the forwards direction implies proposition. The second proof that it requires is that of the backwards direction implies proposition. P ∨ (Q ∧ R) → (P ∨ Q) ∧ (P ∨ R) by first assuming that our premise is true. Then, apply the "or" elimination rule to perform case analysis. In the first case, we must assume P, with which we use the context to prove our conclusion. We do this by using the "and" introduction rule. The first proof that we need for this rule is obtained by using the left "or" introduction rule with the proposition Q and the proof of P. The second proof is obtained by using the left "or" introduction rule with the proposition R and the proof of P. With this side done, we then assume Q ∧ R. We also need the "and" introduction rule for this, so we obtain the necessary proofs with the right "or" introduction rule on proposition P and a proof of Q (from the left "and" elimination rule) -/ -- #9 example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P := -- **Forwards: P ∧ (P ∨ Q) → P** -- **Backwards: P → P ∧ (P ∨ Q)** begin assume P Q, apply iff.intro _ _, -- forwards assume p_and_porq, exact and.elim_left p_and_porq, -- backwards assume p, apply and.intro p _, apply or.intro_left Q p, end /- First, assume some propositions P and Q. Then, apply the if-and-only-if introduction rule on the two required proofs, which are the left-hand/ forwards direction proposition and the right-hand /backwards direction proposition. For the former, we prove by first assuming that the premise is true and, then, exacting (applying) the left and elimination rule on that proof to get the proof of P. Finally, to prove the latter proposition, first assume P, second apply the and introduction rule on the proof of P. We need another proof to fulfill the rule, which we can obtain by applying the left or introduction rule on the proposition Q and the assumed proof of P. -/ -- #10 example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P := -- **Forwards: P ∨ (P ∧ Q) → P** -- **Backwards: P → P ∨ (P ∧ Q)** begin assume P Q, apply iff.intro _ _, -- forwards assume p_or_pandq, apply or.elim p_or_pandq, assume p, apply p, assume pandq, apply and.elim_left pandq, -- backwards assume p, apply or.intro_left (P ∧ Q) p, end /- To prove the above proposition, first assume some proposition P. Then, use the if-and-only -f introduction rule to apply our two required proofs, which are the left-hand and the right-hand sides of our if-and-only-if proposition. Proving our left-hand side proposition (forwards implies) requires that we first assume its premise is true (P ∨ (P ∧ Q)). Then, apply the or elimination rule to this proof in order to perform case analysis. In the first case, assume P, and with that proof, apply it to get our proof of P. Then, assume P ∧ Q, and apply the left and elimination rule to that proof to obtain the proof of P. Finally, to prove that P → (P ∨ (P ∧ Q)), assume P and apply the left introduction rule on the proposition P ∧ Q and the proof of P. -/ -- #11 example : ∀ (P : Prop), P ∨ true ↔ true := -- **Forwards: P ∨ true → true** -- **Backwards: true → P ∨ true** begin assume P, apply iff.intro _ _, -- forwards assume portrue, apply true.intro, -- backwards assume t, apply or.intro_right P t, end /- To prove the above proposition, first assume some proposition P. Then, use the if-and-only -f introduction rule to apply our two required proofs, which are the left-hand and the right-hand sides of our if-and-only-if proposition. For the left-hand side proof, assume the premise is true. Given that proof, apply the true introduction rule to obtain the proof of true, which we must have given our proof of the premise. For the right-hand side of our proposition, we prove it by assuming true and applying the right or introduction rule to the proposition P and the proof of true to get our needed proof of the larger or proposition. -/ -- #12 example : ∀ (P : Prop), P ∨ false ↔ P := -- **Forwards: P ∨ false → P** -- **Backwards: P → P ∨ false** begin assume P, apply iff.intro _ _, -- forwards assume p_or_false, cases p_or_false, exact p_or_false, apply false.elim p_or_false, -- alternatively, contradiction -- backwards assume p, apply or.intro_left false p, end /- To prove the above proposition, first assume some proposition P. Then, use the if-and-only -f introduction rule to apply our two required proofs, which are the left-hand and the right-hand sides of our if-and-only-if proposition. To get a proof the left-hand side proposition, first assume that it is true. Since it is an or proposition, it has two cases we need to analyze. An or proposition will be true when at least one of its side propositions is true. Given a proof that this is the case, the remaining proof to be obtained is for false → P. For this, apply the false elimination rule to the proposition. To get a proof of the right-hand side of our if-and-only -if proposition, first assume P by the implies introduction rule. Then, use the left or introduction rule to obtain a proof of the larger or proposition with the proposition false and our proof of P. -/ -- #13 example : ∀ (P : Prop), P ∧ true ↔ P := -- **Forwards: P ∧ true → P** -- **Backwards: P → P ∧ true** begin assume P, apply iff.intro _ _, -- forwards assume p_and_true, apply and.elim_left p_and_true, -- backwards assume p, apply and.intro p true.intro, end /- To prove the above proposition, first assume some proposition P. Then, use the if-and-only -f introduction rule to apply our two required proofs, which are the left-hand and the right-hand sides of our if-and-only-if proposition. To acquire the left-hand side proof, first assume that we have it by the implies introduction rule. Given that proof, we may then apply the left and elimination rule to it, which will provide us with the proof of P that we need. Remaining to be proved is the left-hand side of the if-and- only-if proposition (P ∧ true). To obtain this proof, first assume the premise. Then, apply the and introduction rule using our assumed proof and the proof of true (to obtain the proof of the larger and proposition). -/ -- #14 example : ∀ (P : Prop), P ∧ false ↔ false := -- **Forwards: P ∧ false → false** -- **Backwards: false → P ∧ false** begin assume P, apply iff.intro _ _, -- forwards assume p_and_false, apply and.elim_right p_and_false, -- backwards assume f, apply false.elim f, -- **???** end /- To prove the above proposition, first assume some proposition P. Then, use the if-and-only -if introduction rule to apply our two required proofs, which are the left-hand and the right-hand sides of our if-and-only-if proposition. To acquire the left-hand side proof, assume the premise of the left-hand side proposition, which can be done by the implies introduction rule. Given that proof, we may perform the right and elimination rule to obtain our proof of false. What we have left to prove is the right-hand side of our if- and-only-if proposition. Begin by assuming that we have a proof of false, then apply the false elimination rule to that proof. -/
7eda70bf5511095421262727e3faff48ca22c0e6
1ce2e14f78a7f514bae439fbbb1f7fa2932dd7dd
/src/factorize.lean
66ffe9324e5499572f4e7e3a8f3033a16a45b32e
[ "MIT" ]
permissive
wudcscheme/lean-mathgirls
b88faf76d12e5ca07b83d6e5580663380b0bb45c
95b64a33ffb34f3c45e212c4adff3cc988dcbc60
refs/heads/master
1,678,994,115,961
1,585,127,877,000
1,585,127,877,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,770
lean
import data.list import tactic.norm_num import .common .tree_sort .list local attribute [simp, reducible] nat.factors @[simp, reducible] def list.zip_with_count {α: Type*} [decidable_eq α] (l: list α): list (α × ℕ) := list.map (λ x, (x, list.count x l)) l @[simp, reducible] def factorize (n: ℕ) : list (ℕ × ℕ) := list.erase_dup (nat.factors n).zip_with_count #eval factorize (2*2*3*5*5) example: (factorize (2*2*3)) ~ [(2, 2), (3, 1)] := by norm_num; reflexivity theorem factors_ge_2 {n p m: ℕ}: (p, m) ∈ (factorize n) -> p ≥ 2 := begin intro h, simp at h, cases h with a w, rw w.right.left.symm, have: nat.prime a, by apply nat.mem_factors w.left, apply nat.prime.two_le, assumption, end theorem factors_are_nat_factors {n p m: ℕ}: (p, m) ∈ (factorize n) -> p ∈ (nat.factors n) := begin intro h, simp at h, cases h with a w, rw w.right.left.symm, apply w.left, end theorem factors_are_prime {n p m: ℕ}: (p, m) ∈ (factorize n) -> nat.prime p := begin intro h, simp at h, cases h with a w, rw w.right.left.symm, apply nat.mem_factors w.left, end @[simp, reducible] def Prod: list ℕ -> ℕ := list.prod theorem prod_singleton_id {x}: Prod [x] = x := by simp theorem prod_singleton_of_lift_id {x}: (Prod ∘ (λ x, [x])) x = x := by simp @[simp, reducible] def divisors_aux: list (ℕ × ℕ) -> list ℕ | [] := [1] | (p::ps) := (<| p |>) <*> (divisors_aux ps) #eval divisors_aux (factorize (2*2*3*5*5)) @[simp, reducible] def divisors (n: ℕ) := divisors_aux (factorize n) #eval divisors (2*2*3*5*5) #eval divisors (2*2*3) example: tree_sort.sort (λ a b, to_bool (a < b)) (divisors (2*2*3)) = [1, 2, 3, 4, 6, 12] := by norm_num; reflexivity
edc6b95cdf12498ebf810e9065f7936a2ade4400
ae9f8bf05de0928a4374adc7d6b36af3411d3400
/src/formal_ml/topological_space.lean
4806d5b7bfb2a91595cf4992e1810425f2faf073
[ "Apache-2.0" ]
permissive
NeoTim/formal-ml
bc42cf6beba9cd2ed56c1cd054ab4eb5402ed445
c9cbad2837104160a9832a29245471468748bb8d
refs/heads/master
1,671,549,160,900
1,601,362,989,000
1,601,362,989,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,272
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import topology.basic import topology.order import topology.constructions import topology.bases import data.set.countable import formal_ml.set import topology.instances.nnreal import topology.instances.ennreal /- The nnreal and ennreal are only needed for two methods. Could move those to a separate file. -/ lemma topological_space_le_def {α:Type*} (S T:topological_space α): S ≤ T ↔ (T.is_open ≤ S.is_open) := begin refl, end lemma topological_space_generate_from_refl {α:Type*} (T:topological_space α): (topological_space.generate_from (T.is_open)) = T := begin apply complete_lattice.le_antisymm, { rw topological_space_le_def, intros U A1, unfold topological_space.generate_from, simp, apply topological_space.generate_open.basic, exact A1, }, { apply (@le_generate_from_iff_subset_is_open α (T.is_open) T).mpr, apply set.subset.refl, } end lemma topological_space_induced_is_open {α β:Type*} (f:α → β) (T:topological_space β): (topological_space.induced f T).is_open = (λs, ∃s', T.is_open s' ∧ f ⁻¹' s' = s) := begin refl, end lemma topological_space_induced_is_open2 {α β:Type*} (f:α → β) (T:topological_space β): (topological_space.induced f T).is_open = (set.image (set.preimage f) T.is_open) := begin refl, end lemma topological_space_generate_from_is_open {α:Type*} {B:set (set α)}: (topological_space.generate_from B).is_open = topological_space.generate_open B := begin refl, end lemma topological_space_induced_def {α β:Type*} {Bβ:set (set β)} (f:α → β): topological_space.induced f (@topological_space.generate_from β Bβ) = @topological_space.generate_from α (set.image (set.preimage f) Bβ) := begin rw @induced_generate_from_eq, end lemma topological_space_induced_fst_def {α β:Type*} {Bα:set (set α)}: topological_space.induced (@prod.fst α β) (@topological_space.generate_from α Bα) = @topological_space.generate_from (α × β) {U:set (α × β)|∃ A∈ Bα, U = set.prod A set.univ} := begin rw topological_space_induced_def, rw set.preimage_fst_def, end lemma topological_space_induced_snd_def {α β:Type*} {Bβ:set (set β)}: topological_space.induced (@prod.snd α β) (@topological_space.generate_from β Bβ) = @topological_space.generate_from (α × β) {U:set (α × β)|∃ B∈ Bβ, U = set.prod set.univ B} := begin rw topological_space_induced_def, rw set.preimage_snd_def, end lemma semilattice_inf_inf_intro {α:Type*} [SL:semilattice_inf α] (x y z:α): (z ≤ x) → (z ≤ y) → (∀ w, (w≤ x)→ (w≤ y)→ (w≤ z))→ (x ⊓ y = z) := begin intros A1 A2 A3, apply semilattice_inf.le_antisymm, { -- x ⊓ y ≤ z apply A3, { apply semilattice_inf.inf_le_left, }, { apply semilattice_inf.inf_le_right, } }, { -- ⊢ z ≤ x ⊓ y apply semilattice_inf.le_inf, { apply A1, }, { apply A2, } } end lemma topological_space_inf_def {α:Type*} {S:set (set α)} {T:set (set α)}: (@topological_space.generate_from α S) ⊓ (@topological_space.generate_from α T)= (@topological_space.generate_from α (S∪ T)) := begin apply semilattice_inf_inf_intro, { apply generate_from_mono, apply set.subset_union_left }, { apply generate_from_mono, apply set.subset_union_right }, { intros, have A1:S ⊆ w.is_open, { apply (@le_generate_from_iff_subset_is_open α S w).mp a, }, have A2:T ⊆ w.is_open, { apply (@le_generate_from_iff_subset_is_open α T w).mp a_1, }, have A2:S ∪ T ⊆ w.is_open, { apply set.union_subset;assumption, }, apply (@le_generate_from_iff_subset_is_open α (S∪T) w).mpr A2, } end lemma prod_topological_space_def {α β:Type*} {Bα:set (set α)} {Bβ:set (set β)}:@prod.topological_space α β (topological_space.generate_from Bα) (topological_space.generate_from Bβ) = topological_space.generate_from ({U:set (α × β)|∃ A∈ Bα, U = set.prod A set.univ} ∪ {U:set (α × β)|∃ B∈ Bβ, U = set.prod set.univ B}) := begin have A1:(@prod.topological_space α β (@topological_space.generate_from α Bα) (@topological_space.generate_from β Bβ)) = topological_space.induced prod.fst (@topological_space.generate_from α Bα) ⊓ topological_space.induced prod.snd (@topological_space.generate_from β Bβ), { refl, }, rw (@topological_space_induced_fst_def α β Bα) at A1, rw (@topological_space_induced_snd_def α β Bβ) at A1, rw topological_space_inf_def at A1, apply A1, end /- We have to be careful about continuous and measurable functions when it comes to functions with two variables. Specifically, if we say a function like f:α → β → γ is continuous, this implies it is a continuous function from α to β → γ, which is usually not what we want. This would ignore the topological space of β. Instead, we want to consider a related function f:(α × β) → γ, and ask if the preimage of an open set in γ is an open set in (α × β). This is a stronger statement (I think). This little definition takes care of this. Note that if you look at the topological_semiring definition below, it matches this definition of continuity. -/ def continuous2 {α β γ:Type*} [topological_space α] [topological_space β] [topological_space γ] (f:α → β → γ):Prop := continuous (λ p:α × β, f (p.fst) (p.snd)) lemma continuous2_def {α β γ:Type*} [topological_space α] [topological_space β] [topological_space γ] (f:α → β → γ):continuous2 f ↔ continuous (λ p:α × β, f (p.fst) (p.snd)) := begin refl end lemma continuous2_of_has_continuous_mul {α:Type*} [T:topological_space α] [HM:has_mul α]:@has_continuous_mul α T HM ↔ (@continuous2 α α α T T T (@has_mul.mul α _)) := begin split;intros A1, { rw continuous2_def, apply @continuous_mul α T HM A1, }, { rw continuous2_def at A1, have A2:@has_continuous_mul α T HM := { continuous_mul := A1, }, apply A2, }, end lemma has_continuous_add_iff_continuous2 {α:Type*} [T:topological_space α] [HM:has_add α]:@has_continuous_add α T HM ↔ (@continuous2 α α α T T T (@has_add.add α _)) := begin split;intros A1, { rw continuous2_def, apply @continuous_add α T HM A1, }, { rw continuous2_def at A1, have A2:@has_continuous_add α T HM := { continuous_add := A1, }, apply A2, }, end lemma continuous2_nnreal_add: continuous2 nnreal.has_add.add := begin rw ← has_continuous_add_iff_continuous2, apply nnreal.topological_semiring.to_has_continuous_add, end lemma continuous2_real_add: continuous2 real.decidable_linear_ordered_comm_ring.add := begin have A1:real.decidable_linear_ordered_comm_ring.add = (@has_add.add ℝ _) := rfl, rw A1, rw ← has_continuous_add_iff_continuous2, apply real.topological_semiring.to_has_continuous_add, end lemma continuous2_ennreal_add: continuous2 ennreal.canonically_ordered_comm_semiring.add := begin have A1:ennreal.canonically_ordered_comm_semiring.add = (@has_add.add ennreal _) := rfl, rw A1, rw ← has_continuous_add_iff_continuous2, apply ennreal.has_continuous_add, end -- Topological basis is the true topological basis, as would be found in Munkres. -- The important distinction is that any open set can be formed via a union of elements of the -- basis. --Trivial: do not use lemma contains_nbhd_of_basis {α:Type*} [Tα:topological_space α] {Gα:set (set α)} {x:α} {V:set α}: (@topological_space.is_topological_basis α Tα Gα) → (is_open V) → (x∈ V) → (∃ S∈ Gα, x∈ S∧ S⊆V) := begin intros A1 A2 A3, apply @topological_space.mem_basis_subset_of_mem_open α Tα Gα A1 x V A3 A2, end --Trivial: do not use lemma union_basis_of_is_open {α:Type*} [Tα:topological_space α] {Gα:set (set α)} {V:set α}: (@topological_space.is_topological_basis α Tα Gα) → (is_open V) → (∃ S⊆ Gα, V = set.sUnion S) := begin intros A1 A2, apply topological_space.sUnion_basis_of_is_open, apply A1, apply A2, end --set_option pp.implicit true lemma continuous_intro {α β:Type*} {Tα:topological_space α} {Tβ:topological_space β} {Gβ:set (set β)} (f:α → β): (@topological_space.is_topological_basis β Tβ Gβ) → (∀ U∈ Gβ, is_open (f⁻¹' U)) → (@continuous α β Tα Tβ f) := begin intros A1 A2 S A3, --unfold topological_space.is_topological_basis at A1, have A4:(∃ X⊆ Gβ, S = set.sUnion X), { apply topological_space.sUnion_basis_of_is_open, apply A1, apply A3, }, cases A4 with X A5, cases A5 with A6 A7, rw A7, rw set.preimage_sUnion', apply is_open_sUnion, intro T, intro A8, cases A8 with T2 A9, cases A9 with A10 A11, subst T, apply A2, rw set.subset_def at A6, apply A6, exact A10, end lemma sUnion_eq_univ_intro {β:Type*} {Gβ:set (set β)}: (∀ x:β, ∃ B∈ Gβ, x∈ B) → (⋃₀ Gβ = set.univ) := begin intro A1, ext,split;intros A2, { simp, }, { have A3: ∃ (B : set β) (H : B ∈ Gβ), x ∈ B, { apply A1, }, cases A3 with B A4, cases A4 with A5 A6, simp, apply exists.intro B, split, exact A5, exact A6, } end /- This theorem uses a middle definition of basis. Specifically, every point must be in some set in the basis. Note that this is equivalent to the union of the sets in the basis being the universe. -/ lemma continuous_intro2 {α β:Type*} {Tα:topological_space α} {Gβ:set (set β)} (f:α → β): (∀ x:β, ∃ B∈ Gβ, x∈ B) → (∀ U∈ Gβ, is_open (f⁻¹' U)) → (@continuous α β Tα (topological_space.generate_from Gβ) f) := begin intros A0 A1, unfold continuous, intros U A2, have A3:@topological_space.generate_open β Gβ U, { rw ← topological_space_generate_from_is_open, apply A2, }, clear A2, induction A3, { apply A1, exact A3_H, }, { have A4:(⋃₀ Gβ = set.univ), { apply sUnion_eq_univ_intro, apply A0, }, { rw ← A4, rw set.preimage_sUnion', apply is_open_sUnion, intros t A5, cases A5 with B A6, cases A6 with A7 A8, subst t, apply A1, exact A7, }, }, { rw set.preimage_inter, apply is_open_inter;assumption, }, { rw set.preimage_sUnion', apply is_open_sUnion, intros t A5, cases A5 with B A6, cases A6 with A7 A8, subst t, apply A3_ih, exact A7, } end lemma generate_from_le_generate_from {α:Type*} {A B:set (set α)}: (∀ b∈ B, topological_space.generate_open A b) → (topological_space.generate_from A ≤ topological_space.generate_from B) := begin intro A1, apply le_generate_from_iff_subset_is_open.mpr, rw set.subset_def, unfold topological_space.generate_from, intros x A3, apply A1, exact A3, end lemma generate_from_eq_generate_from {α:Type*} {A B:set (set α)}: (∀ a∈ A, topological_space.generate_open B a) → (∀ b∈ B, topological_space.generate_open A b) → (topological_space.generate_from A = topological_space.generate_from B) := begin intros A1 A2, apply le_antisymm, { apply generate_from_le_generate_from, exact A2, }, { apply generate_from_le_generate_from, exact A1, }, end lemma prod_topological_space_def2 {α β:Type*} {Tα:topological_space α} {Tβ:topological_space β} {Bα:set (set α)} {Bβ:set (set β)}: (@topological_space.is_topological_basis α Tα Bα) → (@topological_space.is_topological_basis β Tβ Bβ) → (@topological_space.is_topological_basis (α × β) (@prod.topological_space α β Tα Tβ) ({U:set (α × β)|∃ A∈ Bα, ∃ B∈ Bβ, U = set.prod A B})) := begin intros A1 A2, unfold topological_space.is_topological_basis at A1, cases A1 with A3 A4, cases A4 with A5 A6, rw A6, unfold topological_space.is_topological_basis at A2, cases A2 with A7 A8, cases A8 with A9 A10, rw A10, rw prod_topological_space_def, unfold topological_space.is_topological_basis, split, { intros t₁ B1 t₂ B2 x B3, cases B1 with tA₁ B4, cases B4 with B5 B6, cases B6 with tB₁ B7, cases B7 with B7 B8, subst t₁, --unfold set.prod at B3, cases B2 with tA₂ B9, cases B9 with B10 B11, cases B11 with tB₂ B12, cases B12 with B13 B14, subst t₂, rw set.prod_inter_prod at B3, cases B3 with B15 B16, have B17:(∃ (tA₃ : set α) (H : tA₃ ∈ Bα), x.fst ∈ tA₃ ∧ tA₃ ⊆ tA₁ ∩ tA₂), { apply A3, exact B5, exact B10, exact B15, }, have B18:(∃ (tB₃ : set β) (H : tB₃ ∈ Bβ), x.snd ∈ tB₃ ∧ tB₃ ⊆ tB₁ ∩ tB₂), { apply A7, exact B7, exact B13, exact B16, }, cases B17 with tA₃ B19, cases B19 with B20 B21, cases B21 with B22 B23, cases B18 with tB₃ B24, cases B24 with B25 B26, cases B26 with B27 B28, apply exists.intro (set.prod tA₃ tB₃), split, { simp, apply exists.intro tA₃, split, exact B20, apply exists.intro tB₃, split, exact B25, refl, }, { split, { split, apply B22, apply B27, }, { rw set.prod_inter_prod, rw set.prod_subset_prod_iff, left,split;assumption, } } }, { split, { ext;split;intro C1, { simp, }, { simp, have C2:x.fst ∈ ⋃₀ Bα, { rw A5, simp, }, cases C2 with S C3, cases C3 with C4 C5, have C6:x.snd ∈ ⋃₀ Bβ, { rw A9, simp, }, cases C6 with T C7, cases C7 with C8 C9, apply exists.intro (@set.prod α β S T), simp, split, { apply (exists.intro S), split, exact C4, apply (exists.intro T), split, { exact C8, }, { refl, } }, { split, { exact C5, }, { exact C9, } } } }, { apply generate_from_eq_generate_from, { intros X D1, cases D1, { cases D1 with S D2, cases D2 with D3 D4, rw ← A9 at D4, rw set.prod_sUnion_right at D4, subst X, apply topological_space.generate_open.sUnion, intros ST D5, cases D5 with T D6, cases D6 with D7 D8, subst ST, apply topological_space.generate_open.basic, simp, apply exists.intro S, split, exact D3, apply exists.intro T, split, exact D7, refl, }, { cases D1 with T D2, cases D2 with D3 D4, rw ← A5 at D4, rw set.prod_sUnion_left at D4, subst X, apply topological_space.generate_open.sUnion, intros ST D5, cases D5 with S D6, cases D6 with D7 D8, subst ST, apply topological_space.generate_open.basic, simp, apply exists.intro S, split, exact D7, apply exists.intro T, split, exact D3, refl, } }, { intros X E1, cases E1 with S E2, cases E2 with E2 E3, cases E3 with T E4, cases E4 with E5 E6, have E7:X = (set.prod S set.univ) ∩ (set.prod set.univ T), { rw E6, rw set.prod_inter_prod, simp, }, subst X, apply topological_space.generate_open.inter;apply topological_space.generate_open.basic, { left, apply exists.intro S, split, { exact E2, }, { unfold set.prod, simp,refl, } }, { right, apply exists.intro T, split, { exact E5, }, { unfold set.prod, simp,refl, } } } } }, end
ccbecfd6ff9cd681ba2847fcb0f4c8b363244a8b
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/sylow.lean
cb7eb34f450a514659041b623617d424e9086b17
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
45,451
lean
import group_theory.subgroup group_theory.order_of_element data.fintype data.nat.prime data.nat.modeq .zmod_as_fin2 algebra.pi_instances group_theory.subgroup open equiv fintype finset universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] namespace finset lemma filter_insert_of_pos [decidable_eq α] (s : finset α) {P : α → Prop} [decidable_pred P] (a : α) (h : P a) : (insert a s).filter P = insert a (s.filter P) := ext.2 (λ x, by rw [mem_filter, mem_insert, mem_insert, mem_filter, eq_comm]; exact ⟨λ h₁, by cases h₁.1; simp * at *, λ h₁, by cases h₁; simp * at *⟩) lemma filter_insert_of_neg [decidable_eq α] (s : finset α) {P : α → Prop} [decidable_pred P] (a : α) (h : ¬P a) : (insert a s).filter P = s.filter P := ext.2 (λ x, by rw [mem_filter, mem_insert, mem_filter, eq_comm]; exact ⟨λ h₁, by cases h₁.1; simp * at *, by finish⟩) lemma prod_const [comm_monoid β] (s : finset α) (b : β) [decidable_eq α] : s.prod (λ x, b) = b ^ s.card := finset.induction_on s rfl (by simp [pow_add, mul_comm] {contextual := tt}) lemma sum_const [add_comm_monoid β] (s : finset α) (b : β) [decidable_eq α] : s.sum (λ x, b) = add_monoid.smul s.card b := finset.induction_on s rfl (by simp [add_monoid.add_smul] {contextual := tt}) lemma card_pi {δ : α → Type*} [decidable_eq α] [Π a, decidable_eq (δ a)] (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ end finset lemma nat.sum_mod [decidable_eq α] (s : finset α) (f : α → ℕ) (n : ℕ) : s.sum f ≡ (s.filter (λ x, f x % n ≠ 0)).sum f [MOD n] := finset.induction_on s rfl begin assume a s has ih, by_cases ha : f a % n ≠ 0, { rw [finset.sum_insert has, finset.filter_insert_of_pos s a ha, finset.sum_insert], exact nat.modeq.modeq_add rfl ih, { finish [finset.mem_filter] } }, { rw [finset.sum_insert has, finset.filter_insert_of_neg s a ha, ← zero_add (finset.sum (finset.filter _ _) _)], rw [ne.def, ← nat.zero_mod n] at ha, exact nat.modeq.modeq_add (not_not.1 ha) ih } end namespace perm @[simp] lemma one_apply (a : α) : (1 : perm α) a = a := rfl @[simp] lemma mul_apply (x y : perm α) (a : α) : (x * y) a = x (y a) := rfl end perm namespace fintype instance quotient_fintype {α : Type*} [fintype α] (s : setoid α) [decidable_eq (quotient s)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset_fintype [fintype α] : fintype (finset α) := ⟨finset.univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance set.fintype (α : Type u) [fintype α] [decidable_eq α] : fintype (set α) := fintype.of_bijective finset.to_set ⟨λ _ _, finset.coe_eq_coe.1, λ x, by haveI := classical.prop_decidable; exact ⟨set.finite.to_finset ⟨set_fintype _⟩, finset.coe_to_finset⟩⟩ def subtype_fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ lemma card_eq_one_iff [fintype α] : card α = 1 ↔ (∃ x : α, ∀ y : α, y = x) := by rw [← card_unit, card_eq]; exact ⟨λ h, ⟨(classical.choice h).symm unit.star, λ y, (classical.choice h).bijective.1 (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, unit.star, λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff [fintype α] : card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [card_congr e]⟩ lemma card_pos_iff [fintype α] : 0 < card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have card α = 0 := card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt card_eq_zero_iff.1 (λ h, h a))⟩ lemma card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : card α ≤ card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma card_le_one_iff [fintype α] : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end open finset lemma card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] [Π a, decidable_eq (β a)] : card (Π a, β a) = univ.prod (λ a, card (β a)) := by letI f : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc card (Π a, β a) = card (Π a ∈ univ, β a) : card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, card (β a)) : finset.card_pi _ _ lemma card_fun [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : card (α → β) = card β ^ card α := by rw [card_pi, prod_const, nat.pow_eq_pow]; refl end fintype namespace set lemma card_eq_of_eq {s t : set α} [fintype s] [fintype t] (h : s = t) : card s = card t := by congr; assumption lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : card_fintype_of_finset' _ (by simp) ... = s.to_finset.card : card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = card s : (card_fintype_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma coe_to_finset' [decidable_eq α] (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext (by simp) lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} lemma coe_ssubset [decidable_eq α] {s t : finset α} : (↑s : set α) ⊂ ↑t ↔ s ⊂ t := show ↑s ⊆ ↑t ∧ ↑s ≠ ↑t ↔ s ⊆ t ∧ ¬t ⊆ s, by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : card s < card t := begin haveI := classical.prop_decidable, rw [card_fintype_of_finset' _ (λ x, mem_to_finset), card_fintype_of_finset' _ (λ x, mem_to_finset)], rw [← coe_to_finset' s, ← coe_to_finset' t, coe_ssubset] at h, exact finset.card_lt_card h, end def equiv_univ (α : Type u) : α ≃ (set.univ : set α) := { to_fun := λ a, ⟨a, mem_univ _⟩, inv_fun := λ a, a.1, left_inv := λ a, rfl, right_inv := λ ⟨a, ha⟩, rfl } @[simp] lemma card_univ (α : Type u) [fintype α] [fintype.{u} (set.univ : set α)] : fintype.card (set.univ : set α) = fintype.card α := eq.symm (card_congr (equiv_univ α)) lemma eq_of_card_eq_of_subset {s t : set α} [fintype s] [fintype t] (hcard : card s = card t) (hsub : s ⊆ t) : s = t := classical.by_contradiction (λ h, lt_irrefl (card t) (have card s < card t := set.card_lt_card ⟨hsub, h⟩, by rwa hcard at this)) end set namespace pi variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equiped with instances lemma mul_apply [∀ i, has_mul $ f i] (a b : Π i, f i) (i : I) : (a * b) i = a i * b i := rfl lemma one_apply [∀ i, has_one $ f i] (i : I) : (1 : Π i, f i) i = 1 := rfl end pi local attribute [instance, priority 0] classical.prop_decidable fintype.subtype_fintype set_fintype section should_be_in_group_theory noncomputable instance [fintype G] (H : set G) [is_subgroup H] : fintype (left_cosets H) := fintype.quotient_fintype (left_rel H) lemma card_eq_card_cosets_mul_card_subgroup [fintype G] (H : set G) [is_subgroup H] : card G = card (left_cosets H) * card H := by rw ← card_prod; exact card_congr (is_subgroup.group_equiv_left_cosets_times_subgroup _) lemma order_of_dvd_of_pow_eq_one [fintype G] {a : G} {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (nat.pos_of_ne_zero (order_of_ne_zero _))) ⟨mt nat.dvd_of_mod_eq_zero h₁, by rwa ← pow_eq_mod_order_of⟩) lemma eq_one_of_order_of_eq_one [fintype G] {a : G} (h : order_of a = 1) : a = 1 := by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] } lemma order_eq_card_gpowers [fintype G] {a : G} : order_of a = card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ nat.pos_iff_ne_zero.mpr $ order_of_ne_zero a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end @[simp] lemma card_trivial [fintype (is_subgroup.trivial G)] : fintype.card (is_subgroup.trivial G) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : G), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ local attribute [instance] left_rel normal_subgroup.to_is_subgroup instance (H : set G) [normal_subgroup H] : group (left_cosets H) := { one := ⟦1⟧, mul := λ a b, quotient.lift_on₂ a b (λ a b, ⟦a * b⟧) (λ a₁ a₂ b₁ b₂ (hab₁ : a₁⁻¹ * b₁ ∈ H) (hab₂ : a₂⁻¹ * b₂ ∈ H), quotient.sound ((is_subgroup.mul_mem_cancel_left H (is_subgroup.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact normal_subgroup.normal _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃ a b c (λ a b c, show ⟦_⟧ = ⟦_⟧, by rw mul_assoc), one_mul := λ a, quotient.induction_on a (λ a, show ⟦_⟧ = ⟦_⟧, by rw one_mul), mul_one := λ a, quotient.induction_on a (λ a, show ⟦_⟧ = ⟦_⟧, by rw mul_one), inv := λ a, quotient.lift_on a (λ a, ⟦a⁻¹⟧) (λ a b hab, quotient.sound begin show a⁻¹⁻¹ * b⁻¹ ∈ H, rw ← mul_inv_rev, exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab) end), mul_left_inv := λ a, quotient.induction_on a (λ a, show ⟦_⟧ = ⟦_⟧, by rw inv_mul_self) } instance quotient.mk.is_group_hom (H : set G) [normal_subgroup H] : @is_group_hom G (left_cosets H) _ _ quotient.mk := ⟨λ _ _, rfl⟩ instance subtype.val.is_group_hom (H : set G) [is_subgroup H] : is_group_hom (subtype.val : H → G) := ⟨λ _ _, rfl⟩ def normalizer (H : set G) : set G := { g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H } instance (H : set G) [is_subgroup H] : is_subgroup (normalizer H) := { one_mem := by simp [normalizer], mul_mem := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb], inv_mem := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by rw [ha (a⁻¹ * n * a⁻¹⁻¹)]; simp [mul_assoc] } lemma subset_normalizer (H : set G) [is_subgroup H] : H ⊆ normalizer H := λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg), is_subgroup.mul_mem_cancel_right _ hg] instance (H : set G) [is_subgroup H] : normal_subgroup { x : normalizer H | ↑x ∈ H } := { one_mem := show (1 : G) ∈ H, from is_submonoid.one_mem _, mul_mem := λ a b ha hb, show (a * b : G) ∈ H, from is_submonoid.mul_mem ha hb, inv_mem := λ a ha, show (a⁻¹ : G) ∈ H, from is_subgroup.inv_mem ha, normal := λ a ha ⟨m, hm⟩, (hm a).1 ha } lemma mem_normalizer_fintype_iff {H : set G} [fintype H] {x : G} : x ∈ normalizer H ↔ ∀ n, n ∈ H → x * n * x⁻¹ ∈ H := ⟨λ h n, (h n).1, λ h n, ⟨h n, λ h₁, have hsubs₁ : (λ n, x * n * x⁻¹) '' H ⊆ H := λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1, have hcard : card ((λ (n : G), x * n * x⁻¹) '' H) = card H := set.card_image_of_injective H (λ a₁ a₂ ha, (mul_left_inj x).1 ((mul_right_inj (x⁻¹)).1 ha)), have hsubs₂ : H ⊆ (λ n, x * n * x⁻¹) '' H := by_contradiction (λ h, by have := set.card_lt_card (set.ssubset_iff_subset_not_subset.2 ⟨hsubs₁, h⟩); exact lt_irrefl (card H) (by rwa hcard at this)), begin rw set.subset.antisymm hsubs₂ hsubs₁ at h₁, cases h₁ with m hm, have : m = n, from (mul_left_inj x).1 ((mul_right_inj (x⁻¹)).1 hm.2), exact this ▸ hm.1 end⟩ ⟩ noncomputable lemma preimage_quotient_mk_equiv_subgroup_times_set (H : set G) [is_subgroup H] (s : set (left_cosets H)) : quotient.mk ⁻¹' s ≃ (H × s) := have h : ∀ {x : left_cosets H} {a : G}, x ∈ s → a ∈ H → ⟦quotient.out x * a⟧ = ⟦quotient.out x⟧ := λ x a hx ha, quotient.sound (show (quotient.out x * a)⁻¹ * quotient.out x ∈ H, from (is_subgroup.inv_mem_iff _).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out ⟦a⟧)⁻¹ * a, @quotient.exact _ (left_rel H) _ _ $ by simp⟩, ⟨⟦a⟧, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨(quotient.out x) * a, show _ ∈ s, by simpa [h hx ha]⟩, left_inv := λ ⟨a, ha⟩, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, by simp [h hx ha] } end should_be_in_group_theory structure group_action (G : Type u) [group G] (α : Type v) := (to_fun : G → α → α) (one : ∀ a : α, to_fun (1 : G) a = a ) (mul : ∀ (x y : G) (a : α), to_fun (x * y) a = to_fun x (to_fun y a)) instance : has_coe_to_fun (group_action G α) := { F := λ _, G → α → α, coe := λ x, x.to_fun } namespace group_action @[simp] lemma one_apply (f : group_action G α) (a : α) : f 1 a = a := group_action.one f a lemma mul_apply (f : group_action G α) (x y : G) (a : α) : f (x * y) a = f x (f y a) := group_action.mul _ _ _ _ lemma bijective (f : group_action G α) (x : G) : function.bijective (f x) := function.bijective_iff_has_inverse.2 ⟨f (x⁻¹), λ a, by rw [← mul_apply, inv_mul_self, one_apply], λ a, by rw [← mul_apply, mul_inv_self, one_apply]⟩ /-- restriction of a group action on a Type α to s, a set α -/ def restriction {f : group_action G α} {s : set α} (h : ∀ a ∈ s, ∀ x : G, f x a ∈ s) : group_action G s := { to_fun := λ x a, ⟨f x a, h a.1 a.2 x⟩, mul := λ x y a, subtype.eq (group_action.mul f x y a), one := λ a, subtype.eq (group_action.one f a) } lemma restriction_apply {f : group_action G α} {s : set α} (h : ∀ a ∈ s, ∀ x : G, f x a ∈ s) (x : G) (a : s) : f x a = (restriction h) x a := rfl def orbit (f : group_action G α) (a : α) := set.range (λ x : G, f x a) lemma mem_orbit_iff {f : group_action G α} {a b : α} : b ∈ orbit f a ↔ ∃ x : G, f x a = b := by finish [orbit] def orbit_rel (f : group_action G α) (a b : α) := orbit f a = orbit f b @[simp] lemma mem_orbit (f : group_action G α) (a : α) (x : G) : f x a ∈ orbit f a := ⟨x, rfl⟩ lemma mem_orbit_self (f : group_action G α) (a : α) : a ∈ orbit f a := ⟨1, show f 1 a = a, by simp⟩ lemma orbit_eq {f : group_action G α} {a b : α} : a ∈ orbit f b → orbit f a = orbit f b := λ ⟨x, (hx : f x b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : f y a = c)⟩, ⟨y * x, show f (y * x) b = c, by rwa [mul_apply, hx]⟩, λ ⟨y, (hy : f y b = c)⟩, ⟨y * x⁻¹, show f (y * x⁻¹) a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_apply, hx]}⟩⟩) noncomputable def orbit_fintype (f : group_action G α) (a : α) [fintype G] : fintype (orbit f a) := set.fintype_range _ def stabilizer (f : group_action G α) (a : α) : set G := { x : G | f x a = a } lemma mem_stabilizer_iff {f : group_action G α} {a : α} {x : G} : x ∈ stabilizer f a ↔ f x a = a := iff.rfl lemma orbit_restriction {f : group_action G α} {s : set α} {a : s} {h : ∀ a ∈ s, ∀ x, f x a ∈ s} {b : s} : b ∈ orbit (restriction h) a ↔ (b : α) ∈ orbit f a := ⟨λ h, let ⟨x, hx⟩ := mem_orbit_iff.1 h in mem_orbit_iff.2 ⟨x, hx ▸ rfl⟩, λ h, let ⟨x, hx⟩ := mem_orbit_iff.1 h in mem_orbit_iff.2 ⟨x, subtype.eq hx⟩⟩ lemma stabilizer_restriction {f : group_action G α} {s : set α} {a : s} (h : ∀ a ∈ s, ∀ x, f x a ∈ s) : stabilizer (restriction h) a = stabilizer f a := set.ext (λ x,by rw [mem_stabilizer_iff, mem_stabilizer_iff]; exact ⟨λ h, by conv {to_rhs, rw ← h}; refl, λ h, subtype.eq h⟩) instance (f : group_action G α) (a : α) : is_subgroup (stabilizer f a) := { one_mem := one_apply _ _, mul_mem := λ x y (hx : f x a = a) (hy : f y a = a), show f (x * y) a = a, by rw mul_apply; simp *, inv_mem := λ x (hx : f x a = a), show f x⁻¹ a = a, by rw [← hx, ← mul_apply, inv_mul_self, one_apply, hx] } noncomputable lemma orbit_equiv_left_cosets (a : α) (f : group_action G α) : orbit f a ≃ left_cosets (stabilizer f a) := by letI := left_rel (stabilizer f a); exact { to_fun := λ b, quotient.mk (classical.some (mem_orbit_iff.1 b.2)), inv_fun := λ x, ⟨f (quotient.out x) a, mem_orbit _ _ _⟩, left_inv := λ b, subtype.eq (let x := classical.some (mem_orbit_iff.1 b.2) in let y := quotient.out ⟦x⟧ in show f y a = b.1, begin have : f (x⁻¹ * y) a = a := setoid.symm (quotient.mk_out x), rw [← one_mul y, ← mul_inv_self x, mul_assoc, mul_apply, this], exact classical.some_spec (mem_orbit_iff.1 b.2) end), right_inv := λ x, let hx := mem_orbit_iff.1 (mem_orbit f a (quotient.out x)) in let y := classical.some hx in have hy : f y a = f (quotient.out x) a := classical.some_spec hx, show quotient.mk y = _, begin rw ← quotient.out_eq x, refine quotient.sound _, show y⁻¹ * _ ∈ _, rw [mem_stabilizer_iff, mul_apply, ← hy, ← mul_apply, inv_mul_self, one_apply] end } def fixed_points (f : group_action G α) : set α := {a : α | ∀ x, x ∈ stabilizer f a} lemma mem_fixed_points {f : group_action G α} {x : α} : x ∈ fixed_points f ↔ (∀ y, y ∈ orbit f x → y = x) := ⟨λ h y h₁, let ⟨a, ha⟩ := mem_orbit_iff.1 h₁ in ha ▸ h a, λ h x, mem_stabilizer_iff.2 (h _ (mem_orbit _ _ _))⟩ lemma fixed_points_restriction {f : group_action G α} {s : set α} (h : ∀ a ∈ s, ∀ x, f x a ∈ s) {a : s} : a ∈ fixed_points (restriction h) ↔ (a : α) ∈ fixed_points f := show (∀ x, x ∈ stabilizer (restriction h) a) ↔ (∀ x, x ∈ stabilizer f a), by rw stabilizer_restriction h; refl lemma card_orbit_of_mem_fixed_point {f : group_action G α} {x : α} [fintype (orbit f x)] : x ∈ fixed_points f ↔ card (orbit f x) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨x, mem_orbit_self _ _⟩, λ ⟨y, hy⟩, subtype.eq (h _ hy)⟩ }, { assume h y hy, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc y = z : subtype.mk.inj (hz₁ ⟨y, hy⟩) ... = x : (subtype.mk.inj (hz₁ ⟨x, mem_orbit_self _ _⟩)).symm } end lemma mpl [fintype α] [fintype G] {p n : ℕ} (hp : nat.prime p) (h : card G = p ^ n) (f : group_action G α) : card α ≡ card (fixed_points f) [MOD p] := have hcard : ∀ s : set α, card ↥{x : α | orbit f x = s} % p ≠ 0 ↔ card ↥{x : α | orbit f x = s} = 1 := λ s, ⟨λ hs, begin have h : ∃ y, orbit f y = s := by_contradiction (λ h, begin rw not_exists at h, have : {x | orbit f x = s} = ∅ := set.eq_empty_iff_forall_not_mem.2 h, rw [set.card_eq_of_eq this, set.empty_card', nat.zero_mod] at hs, contradiction end), cases h with y hy, have hseq : {x | orbit f x = s} = orbit f y := set.ext (λ z, ⟨λ h : orbit f z = s, hy.symm ▸ h ▸ mem_orbit_self _ _, λ h, show orbit f z = s, by rwa orbit_eq h⟩), rw [card_eq_card_cosets_mul_card_subgroup (stabilizer f y), ← card_congr (orbit_equiv_left_cosets y f)] at h, have : ∃ k ≤ n, card (orbit f y) = p ^ k := (nat.dvd_prime_pow hp).1 (h ▸ dvd_mul_right _ _), rcases this with ⟨k, hk₁, hk₂⟩, rw [set.card_eq_of_eq hseq, hk₂] at hs ⊢, have : ¬p ∣ p ^ k := mt nat.mod_eq_zero_of_dvd hs, cases k, { refl }, { simpa [nat.pow_succ] using this } end, λ hs, hs.symm ▸ (nat.mod_eq_of_lt hp.gt_one).symm ▸ λ h, nat.no_confusion h⟩, have h : (finset.univ.filter (λ a, card {x | orbit f x = a} % p ≠ 0)).sum (λ a : set α, card {x | orbit f x = a}) = card (fixed_points f), from calc _ = (finset.univ.filter (λ a, card {x | orbit f x = a} % p ≠ 0)).sum (λ a : set α, 1) : finset.sum_congr rfl (λ s hs, (hcard s).1 (finset.mem_filter.1 hs).2) ... = card {a : set α | card ↥{x : α | orbit f x = a} % p ≠ 0} : begin rw [finset.sum_const, nat.smul_eq_mul, mul_one], refine eq.symm (set.card_fintype_of_finset' _ _), simp [finset.mem_filter], end ... = card (fixed_points f) : fintype.card_congr (@equiv.of_bijective _ _ (show fixed_points f → {a : set α // card ↥{x : α | orbit f x = a} % p ≠ 0}, from λ x, ⟨orbit f x.1, begin rw [hcard, fintype.card_eq_one_iff], exact ⟨⟨x, rfl⟩, λ ⟨y, hy⟩, have hy : y ∈ orbit f x := (show orbit f y = orbit f x, from hy) ▸ mem_orbit_self _ _, subtype.eq (mem_fixed_points.1 x.2 _ hy)⟩ end⟩) ⟨λ x y hxy, have hxy : orbit f x.1 = orbit f y.1 := subtype.mk.inj hxy, have hxo : x.1 ∈ orbit f y.1 := hxy ▸ mem_orbit_self _ _, subtype.eq (mem_fixed_points.1 y.2 _ hxo), λ ⟨s, hs⟩, begin rw [hcard, fintype.card_eq_one_iff] at hs, rcases hs with ⟨⟨x, hx₁⟩, hx₂⟩, exact ⟨⟨x, mem_fixed_points.2 (λ y hy, subtype.mk.inj (hx₂ ⟨y, by have := orbit_eq hy; simpa [this, hx₁] using hx₁⟩))⟩, by simpa using hx₁⟩ end⟩).symm, calc card α % p = finset.sum finset.univ (λ a : set α, card {x // orbit f x = a}) % p : by rw [card_congr (equiv_fib (orbit f)), fintype.card_sigma] ... = _ : nat.sum_mod _ _ _ ... = fintype.card ↥(fixed_points f) % p : by rw ← h; congr end group_action namespace sylow open group_action def F₁ (n : ℕ) [Zmod.pos n] (v : Zmod n → G) : Zmod (n+1) → G := λ m, if h : m.1 < n then v m.1 else ((list.range n).map (λ m : ℕ, v (m : Zmod n))).prod⁻¹ lemma F₁_injective {p : ℕ} [h0 : Zmod.pos p] : function.injective (@F₁ G _ p _) := λ x y hxy, funext (λ ⟨a, ha⟩, begin have : dite _ _ _ = dite _ _ _ := congr_fun hxy a, rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_of_lt ha), dif_pos ha, dif_pos ha] at this, rwa Zmod.mk_eq_cast end) /-- set of elements of G^n such that the product of the list of elements of the vector is one -/ def Gstar (G : Type*) [group G] (n : ℕ) [Zmod.pos n] : set (Zmod n → G) := {v | ((list.range n).map (λ m : ℕ, v (↑m : Zmod n))).prod = 1 } lemma prod_lemma (n : ℕ) [Zmod.pos n] (v : Zmod (n + 1) → G) : ((list.range (n + 1)).map (λ m : ℕ, v (m : Zmod (n + 1)))).prod = list.prod (list.map (λ (m : ℕ), v ↑m) (list.range n)) * v ↑n := by rw [list.range_concat, list.map_append, list.prod_append, list.map_singleton, list.prod_cons, list.prod_nil, mul_one] lemma mem_Gstar_iff {n : ℕ} [Zmod.pos n] (v : Zmod (n + 1) → G) : v ∈ Gstar G (n + 1) ↔ v ∈ F₁ n '' (set.univ : set (Zmod n → G)) := ⟨λ h : list.prod (list.map (λ (m : ℕ), v ↑m) (list.range (n + 1))) = 1, have h₁ : list.map (λ (m : ℕ), v ((m : Zmod n).val : Zmod (n+1))) (list.range n) = list.map (λ (m : ℕ), v m) (list.range n) := list.map_congr (λ m hm, have hm' : m < n := list.mem_range.1 hm, by simp[nat.mod_eq_of_lt hm']), ⟨λ m, v m.val, set.mem_univ _, funext (λ i, show dite _ _ _ = _, begin split_ifs, { refine congr_arg _ (fin.eq_of_veq _), simp [nat.mod_eq_of_lt h_1, nat.mod_eq_of_lt (nat.lt_succ_of_lt h_1)] }, { have hi : i = n := fin.eq_of_veq begin rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_self _)], exact le_antisymm (nat.le_of_lt_succ i.2) (le_of_not_gt h_1), end, rw [h₁, hi, inv_eq_iff_mul_eq_one, ← prod_lemma, h] } end)⟩, λ ⟨w, hw⟩, have h : list.map (λ m : ℕ, w m) (list.range n) = list.map (λ m : ℕ, v m) (list.range n) := list.map_congr (λ k hk, have hk' : k < n := list.mem_range.1 hk, hw.2 ▸ (show _ = dite _ _ _, by rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_of_lt hk'), dif_pos hk'])), begin show list.prod (list.map (λ (m : ℕ), v ↑m) (list.range (n + 1))) = 1, rw [prod_lemma, ← h, ← hw.2], show _ * dite _ _ _ = (1 : G), rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_self _), dif_neg (lt_irrefl _), mul_inv_self], end⟩ def F₂ (α : Type*) (n : ℕ) [h0 : Zmod.pos n] : group_action (multiplicative (Zmod n)) (Zmod n → α) := { to_fun := λ i v m, v (m + i), mul := λ (i j : Zmod n) (v : Zmod n → α), funext (λ m, congr_arg v (add_assoc _ _ _).symm), one := λ (v : Zmod n → α), funext (λ m, congr_arg v (add_zero m)) } lemma fixed_points_F₂_eq_const {n : ℕ} [h0 : Zmod.pos n] {v : Zmod n → G} (h : v ∈ fixed_points (F₂ G n)) (i j : Zmod n) : v i = v j := calc v i = v (j + i) : add_comm i j ▸ (congr_fun ((mem_fixed_points.1 h _) (mem_orbit (F₂ G n) v j)) i).symm ... = v j : congr_fun ((mem_fixed_points.1 h _) (mem_orbit (F₂ G n) v i)) j lemma map_succ_range : ∀ n : ℕ, list.range (nat.succ n) = 0 :: (list.range n).map nat.succ | 0 := rfl | (n+1) := by rw [list.range_concat, list.range_concat, list.map_append, ← list.cons_append, ← map_succ_range, list.range_concat, list.map_singleton] open nat lemma list.prod_const [monoid α] : ∀ {l : list α} {a : α}, (∀ b ∈ l, b = a) → l.prod = a ^ l.length | [] := λ _ _, rfl | (b::l) := λ a ha, have h : ∀ b ∈ l, b = a := λ b hb, ha b (list.mem_cons_of_mem _ hb), have hb : b = a := ha b (list.mem_cons_self _ _), by simp [_root_.pow_add, list.prod_const h, hb] lemma F₂_on_Gstar {n : ℕ} [h0 : Zmod.pos n] {v : Zmod (succ n) → G} (hv : v ∈ Gstar G (succ n)) (i : Zmod (succ n)) : (F₂ G (succ n)) (i : Zmod (succ n)) v ∈ Gstar G (succ n) := begin cases i with i hi, rw Zmod.mk_eq_cast, clear hi, induction i with i ih, { show list.prod (list.map (λ (m : ℕ), v (m + 0)) (list.range (succ n))) = 1, simpa }, { show list.prod (list.map (λ (m : ℕ), v (m + (i + 1))) (list.range (succ n))) = 1, replace ih : list.prod (list.map (λ (m : ℕ), v (m + i)) (list.range (succ n))) = 1 := ih, rw [list.range_concat, list.map_append, list.prod_append, list.map_singleton, list.prod_cons, list.prod_nil, mul_one] at ⊢ ih, have h : list.map (λ m : ℕ, v (↑m + (i + 1))) (list.range n) = list.map (λ m : ℕ, v (m + i)) (list.map (λ m : ℕ, m + 1) (list.range n)), { simp [list.map_map, function.comp] }, resetI, cases n, { exact (lt_irrefl 0 h0.pos).elim }, { have h : list.map (λ m : ℕ, v (↑m + (i + 1))) (list.range n) = list.map (λ m : ℕ, v (m + i)) (list.map succ (list.range n)), { simp [list.map_map, function.comp] }, have h₁ : (succ n : Zmod (succ (succ n))) + (↑i + 1) = i, { rw [add_left_comm, ← nat.cast_one, ← nat.cast_add, Zmod.cast_self_eq_zero, add_zero] }, have h₂ : (n : Zmod (succ (succ n))) + i + 1 = succ n + i := by simp [succ_eq_add_one], rw [map_succ_range, list.map_cons, list.prod_cons, ← h, nat.cast_zero, zero_add] at ih, have := eq_inv_mul_of_mul_eq ih, rw [list.range_concat, list.map_append, list.map_singleton, list.prod_append, list.prod_cons, list.prod_nil, mul_one, ← add_assoc, h₁, h₂, this], simp } } end def F₂Gstar (G : Type u) [group G] (n : ℕ) [Zmod.pos n] : group_action (multiplicative (Zmod (succ n))) (Gstar G (succ n)) := restriction (λ v, F₂_on_Gstar) lemma fixed_points_F₂_pow_n [fintype G] {n : ℕ} (hn : nat.prime (succ n)) [h0 : Zmod.pos n] {v : Gstar G (succ n)} (hv : v ∈ fixed_points (F₂Gstar G n)) : (v : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := let ⟨w, hw⟩ := (mem_Gstar_iff _).1 v.2 in have hv' : (v : Zmod (succ n) → G) ∈ _ := ((fixed_points_restriction _).1 hv), begin have h₁ : dite _ _ _ = (v : Zmod (succ n) → G) _ := congr_fun hw.2 ⟨n, nat.lt_succ_self n⟩, rw dif_neg (lt_irrefl _) at h₁, have h₂ : ∀ b, b < n → w b = (v : Zmod (succ n) → G) b := λ b hb, begin have : dite _ _ _ = _ := congr_fun hw.2 b, rwa [Zmod.cast_val_of_lt (lt_succ_of_lt hb), dif_pos hb] at this, end, have hb : ∀ (b : G), b ∈ list.map (λ (m : ℕ), w ↑m) (list.range n) → b = w 0 := λ b hb, let ⟨i, hi⟩ := list.mem_map.1 hb in by rw [← hi.2, h₂ _ (list.mem_range.1 hi.1), fixed_points_F₂_eq_const ((fixed_points_restriction _).1 hv) _ 0]; exact (h₂ 0 h0.pos).symm, refine (@mul_left_inj _ _ (w 0 ^ (-n : ℤ)) _ _).1 _, rw [@list.prod_const _ _ _ (w 0) hb, list.length_map, list.length_range, ← gpow_coe_nat, ← gpow_neg] at h₁, conv { to_rhs, rw [h₁, fixed_points_F₂_eq_const hv' _ 0] }, rw [← nat.cast_zero, h₂ 0 h0.pos, nat.cast_zero, ← gpow_coe_nat, ← gpow_add, int.coe_nat_add], simp, end lemma one_mem_fixed_points_F₂ [fintype G] {n : ℕ} [h0 : Zmod.pos n] : (1 : Zmod n → G) ∈ fixed_points (F₂ G n) := mem_fixed_points.2 (λ y hy, funext (λ j, let ⟨i, hi⟩ := mem_orbit_iff.1 hy in have hj : (1 : G) = y j := congr_fun hi j, hj ▸ rfl)) lemma one_mem_Gstar (n : ℕ) [Zmod.pos n] : (1 : Zmod n → G) ∈ Gstar G n := show list.prod (list.map (λ (m : ℕ), (1 : G)) (list.range n)) = 1, from have h : ∀ b : G, b ∈ list.map (λ (m : ℕ), (1 : G)) (list.range n) → b = 1 := λ b hb, let ⟨_, h⟩ := list.mem_map.1 hb in h.2.symm, by simp [list.prod_const h] attribute [trans] dvd.trans lemma exists_prime_order_of_dvd_card [fintype G] {p : ℕ} (hp : nat.prime p) (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n := p - 1 in have hn : p = n + 1 := nat.succ_sub hp.pos, have hnp : nat.prime (n + 1) := hn ▸ hp, have hn0 : Zmod.pos n := ⟨nat.lt_of_succ_lt_succ hnp.gt_one⟩, have hlt : ¬(n : Zmod (n + 1)).val < n := not_lt_of_ge (by rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_self _)]; exact le_refl _), have hcard1 : card (Gstar G (n + 1)) = card (Zmod n → G) := by rw [← set.card_univ (Zmod n → G), set.ext (@mem_Gstar_iff _ _ _ hn0), set.card_image_of_injective _ F₁_injective], have hcard : card (Gstar G (n + 1)) = card G ^ n := by conv { rw hcard1, to_rhs, rw ← card_fin n }; exact fintype.card_fun, have hZmod : @fintype.card (multiplicative (Zmod (n+1))) (fin.fintype _) = (n+1) ^ 1 := (nat.pow_one (n + 1)).symm ▸ card_fin _, have hmodeq : _ = _ := mpl hnp hZmod (@F₂Gstar G _ n hn0), have hdvdcard : (n + 1) ∣ card (Gstar G (n + 1)) := calc (n + 1) = p : hn.symm ... ∣ card G ^ 1 : by rwa nat.pow_one ... ∣ card G ^ n : nat.pow_dvd_pow _ hn0.pos ... = card (Gstar G (n + 1)) : hcard.symm, have hdvdcard₂ : (n + 1) ∣ card (fixed_points (@F₂Gstar G _ n hn0)) := nat.dvd_of_mod_eq_zero (hmodeq ▸ (nat.mod_eq_zero_of_dvd hdvdcard)), have hcard_pos : 0 < card (fixed_points (@F₂Gstar G _ n hn0)) := fintype.card_pos_iff.2 ⟨⟨⟨(1 : Zmod (succ n) → G), one_mem_Gstar _⟩, (fixed_points_restriction _).2 (one_mem_fixed_points_F₂)⟩⟩, have hle : 1 < card (fixed_points (@F₂Gstar G _ n hn0)) := calc 1 < n + 1 : hnp.gt_one ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨x, hx₁⟩, hx₂⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt hle)) in let ⟨⟨y, hy₁⟩, hy₂⟩ := classical.not_forall.1 hx₂ in have hxy : (x : Zmod (succ n) → G) 0 ≠ 1 ∨ (y : Zmod (succ n) → G) 0 ≠ 1 := or_iff_not_imp_left.2 (λ hx1 hy1, hy₂ (subtype.eq (subtype.eq (funext (λ i, show (x : Zmod (succ n) → G) i = (y : Zmod (succ n) → G) i, by rw [fixed_points_F₂_eq_const ((fixed_points_restriction _).1 hy₁) i 0, hy1, fixed_points_F₂_eq_const ((fixed_points_restriction _).1 hx₁) i 0, not_not.1 hx1]))))), have hxp : (x : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := @fixed_points_F₂_pow_n _ _ _ _ hnp hn0 _ hx₁, have hyp : (y : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := @fixed_points_F₂_pow_n _ _ _ _ hnp hn0 _ hy₁, begin rw hn, cases hxy with hx hy, { existsi (x : Zmod (succ n) → G) 0, exact or.resolve_left (hnp.2 _ (order_of_dvd_of_pow_eq_one hxp)) (λ h, hx (eq_one_of_order_of_eq_one h)) }, { existsi (y : Zmod (succ n) → G) 0, exact or.resolve_left (hnp.2 _ (order_of_dvd_of_pow_eq_one hyp)) (λ h, hy (eq_one_of_order_of_eq_one h)) } end local attribute [instance] left_rel set_fintype open is_subgroup is_submonoid is_group_hom def thing (H : set G) [is_subgroup H] : group_action H (left_cosets H) := { to_fun := λ x y, quotient.lift_on y (λ y, ⟦(x : G) * y⟧) (λ a b (hab : _ ∈ H), quotient.sound (show _ ∈ H, by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])), one := λ a, quotient.induction_on a (λ a, quotient.sound (show (1 : G) * a ≈ a, by simp)), mul := λ x y a, quotient.induction_on a (λ a, quotient.sound (by rw ← mul_assoc; refl)) } def thing2 (L₁ L₂ : set G) [is_subgroup L₂] [is_subgroup L₁] : group_action L₂ (left_cosets L₁) := { to_fun := λ x y, quotient.lift_on y (λ y, ⟦(x : G) * y⟧) (λ a b (hab : _ ∈ L₁), quotient.sound (show _ ∈ L₁, by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])), one := λ a, quotient.induction_on a (λ a, quotient.sound (show (1 : G) * a ≈ a, by simp)), mul := λ x y a, quotient.induction_on a (λ a, quotient.sound (by rw ← mul_assoc; refl)) } lemma mem_fixed_points_thing_iff_mem_normalizer {H : set G} [is_subgroup H] [fintype H] {x : G} : ⟦x⟧ ∈ fixed_points (thing H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : left_cosets H}, y ∈ orbit (thing H) ⟦x⟧ → y = ⟦x⟧ := λ _, (mem_fixed_points.1 hx _), (inv_mem_iff _).1 (mem_normalizer_fintype_iff.2 (λ n hn, have (n⁻¹ * x)⁻¹ * x ∈ H := quotient.exact (ha (mem_orbit (thing H) _ ⟨n⁻¹, inv_mem hn⟩)), by simpa only [mul_inv_rev, inv_inv] using this)), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), mem_fixed_points.2 $ λ y, quotient.induction_on y $ λ y hy, quotient.sound (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient.exact hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_right H (inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ lemma fixed_points_thing_equiv_cosets (H : set G) [is_subgroup H] [fintype H] : fixed_points (thing H) ≃ left_cosets {x : normalizer H | ↑x ∈ H} := { to_fun := λ a, quotient.hrec_on a.1 (λ a ha, @quotient.mk _ (left_rel {x : normalizer H | ↑x ∈ H}) ⟨a, mem_fixed_points_thing_iff_mem_normalizer.1 ha⟩) (λ x y hxy, function.hfunext (by rw quotient.sound hxy) (λ hx hy _, heq_of_eq (@quotient.sound _ (left_rel {x : normalizer H | ↑x ∈ H}) _ _ (by exact hxy)))) a.2, inv_fun := λ x, ⟨@quotient.lift_on _ _ (left_rel {x : normalizer H | ↑x ∈ H}) x (λ x, show fixed_points (thing H), from ⟨⟦x⟧, mem_fixed_points_thing_iff_mem_normalizer.2 x.2⟩) (λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x⁻¹ * y ∈ H), subtype.eq (quotient.sound hxy)), (@quotient.induction_on _ (left_rel {x : normalizer H | ↑x ∈ H}) _ x (by intro x; cases x with x hx; exact mem_fixed_points_thing_iff_mem_normalizer.2 hx))⟩, left_inv := λ ⟨x, hx⟩, by revert hx; exact quotient.induction_on x (by intros; refl), right_inv := λ x, @quotient.induction_on _ (left_rel {x : normalizer H | ↑x ∈ H}) _ x (by intro x; cases x; refl) } lemma sylow1 [fintype G] {p : ℕ} : ∀ {n : ℕ} (hp : nat.prime p) (hdvd : p ^ n ∣ card G), ∃ H : set G, is_subgroup H ∧ card H = p ^ n | 0 := λ _ _, ⟨trivial G, by apply_instance, by simp [-set.set_coe_eq_subtype]⟩ | (n+1) := λ hp hdvd, let ⟨H, ⟨hH1, hH2⟩⟩ := sylow1 hp (dvd.trans (pow_dvd_pow _ (le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in by exactI have hcard : card (left_cosets H) = s * p := (nat.mul_right_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, is_submonoid.one_mem H⟩⟩)).1 (by rwa [← card_eq_card_cosets_mul_card_subgroup, hH2, hs, nat.pow_succ, mul_assoc, mul_comm p]), have hm : s * p % p = card (left_cosets {x : normalizer H | ↑x ∈ H}) % p := card_congr (fixed_points_thing_equiv_cosets H) ▸ hcard ▸ mpl hp hH2 (thing H), have hm' : p ∣ card (left_cosets {x : normalizer H | ↑x ∈ H}) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := exists_prime_order_of_dvd_card hp hm' in have hxcard : card (gpowers x) = p := by rwa ← order_eq_card_gpowers, let S : set ↥(normalizer H) := set.preimage (@quotient.mk _ (left_rel {x : ↥(normalizer H) | ↑x ∈ H})) (@gpowers (left_cosets {x : ↥(normalizer H) | ↑x ∈ H}) _ x) in have is_subgroup S := @is_group_hom.preimage _ (left_cosets {x : ↥(normalizer H) | ↑x ∈ H}) _ _ _ _ _ _, have fS : fintype S := by apply_instance, let hequiv : {x : ↥(normalizer H) | ↑x ∈ H} ≃ H := { to_fun := λ ⟨x, hx⟩, ⟨x, hx⟩, inv_fun := λ ⟨x, hx⟩, ⟨⟨x, subset_normalizer _ hx⟩, hx⟩, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨_, _⟩, rfl } in ⟨subtype.val '' S, by apply_instance, by dsimp only [S]; rw [set.card_image_of_injective _ subtype.val_injective, nat.pow_succ, @card_congr _ _ fS _ (preimage_quotient_mk_equiv_subgroup_times_set _ _), card_prod, hxcard, ← hH2, card_congr hequiv]⟩ def conjugate_set (G : Type u) [group G] : group_action G (set G) := { to_fun := λ x H, {n | x⁻¹ * n * x ∈ H}, one := λ H, by simp, mul := λ x y H, by simp [mul_inv_rev, mul_assoc, function.comp] } lemma conjugate_set_eq_image (H : set G) (x : G) : conjugate_set G x H = (λ n, x * n * x⁻¹) '' H := set.ext (λ n, ⟨λ h, ⟨x⁻¹ * n * x, h, by simp [mul_assoc]⟩, λ ⟨a, ha⟩, show x⁻¹ * n * x ∈ H, from ha.2 ▸ by simp [ha.1, mul_assoc]⟩) lemma mem_conjugate_set {H : set G} {x n : G} : n ∈ conjugate_set G x H ↔ x⁻¹ * n * x ∈ H := iff.rfl lemma conj_inj_left {x : G} : function.injective (λ (n : G), x * n * x⁻¹) := λ a b h, (mul_left_inj x).1 $ (mul_right_inj (x⁻¹)).1 h instance is_group_hom_conj (x : G) : is_group_hom (λ (n : G), x * n * x⁻¹) := ⟨by simp [mul_assoc]⟩ instance is_subgroup_conj (x : G) (H : set G) [is_subgroup H] : is_subgroup (conjugate_set G x H) := by rw conjugate_set_eq_image; apply_instance /-- dlogn p a gives the value of n such that p ^ n ∣ a -/ def dlogn (p : ℕ) : ℕ → ℕ | 0 := 0 | (a+1) := if h : p > 1 then have (a + 1) / p < a + 1, from div_lt_self dec_trivial h, if p ∣ (a + 1) then dlogn ((a + 1) / p) + 1 else 0 else 0 lemma dlogn_dvd {p : ℕ} : ∀ a, p > 1 → p ^ dlogn p a ∣ a | 0 := λ _, dvd_zero _ | (a+1) := λ h, have (a + 1) / p < a + 1, from div_lt_self dec_trivial h, begin rw [dlogn, if_pos h], split_ifs, { rw [nat.pow_succ], conv {to_rhs, rw ← nat.div_mul_cancel h_1}, exact mul_dvd_mul (dlogn_dvd _ h) (dvd_refl _) }, { simp } end lemma not_dvd_div_dlogn {p : ℕ} : ∀ {a}, a > 0 → p > 1 → ¬p ∣ a / (p ^ dlogn p a) | 0 := λ h, (lt_irrefl _ h).elim | (a+1) := λ h hp hd, have (a + 1) / p < a + 1, from div_lt_self dec_trivial hp, begin rw [dlogn, if_pos hp] at hd, split_ifs at hd, { have := @not_dvd_div_dlogn ((a + 1) / p) (pos_of_mul_pos_left (by rw nat.mul_div_cancel' h_1; exact nat.succ_pos _) (nat.zero_le p)) hp, rw [nat.div_div_eq_div_mul, mul_comm, ← nat.pow_succ] at this, contradiction }, { simpa using hd } end class is_sylow [fintype G] (H : set G) {p : ℕ} (hp : prime p) extends is_subgroup H : Prop := (card_eq : card H = p ^ dlogn p (card G)) lemma exists_sylow_p_subgroup (G : Type u) [group G] [fintype G] {p : ℕ} (hp : prime p) : ∃ H : set G, is_sylow H hp := let ⟨H, ⟨hH₁, hH₂⟩⟩ := sylow1 hp (dlogn_dvd (card G) hp.gt_one) in by exactI ⟨H, by split; assumption⟩ lemma card_sylow [fintype G] (H : set G) {p : ℕ} (hp : prime p) [is_sylow H hp] : card H = p ^ dlogn p (card G) := is_sylow.card_eq _ hp lemma sylow2 [fintype G] {p : ℕ} (hp : nat.prime p) (L₁ L₂ : set G) [is_sylow L₂ hp] [is_sylow L₁ hp] : ∃ x : G, L₂ = conjugate_set G x L₁ := have hs : card (left_cosets L₁) = card G / (p ^ dlogn p (card G)) := (nat.mul_right_inj (pos_pow_of_pos (dlogn p (card G)) hp.pos)).1 $ by rw [← card_sylow L₁ hp, ← card_eq_card_cosets_mul_card_subgroup, card_sylow L₁ hp, nat.div_mul_cancel (dlogn_dvd _ hp.gt_one)], have hmodeq : card G / (p ^ dlogn p (card G)) ≡ card (fixed_points (thing2 L₁ L₂)) [MOD p] := hs ▸ mpl hp (card_sylow L₂ hp) (thing2 L₁ L₂), have hfixed : 0 < card (fixed_points (thing2 L₁ L₂)) := nat.pos_of_ne_zero (λ h, (not_dvd_div_dlogn (fintype.card_pos_iff.2 ⟨(1 : G)⟩) hp.gt_one) $ by rwa [h, nat.modeq.modeq_zero_iff] at hmodeq), let ⟨x, hx⟩ := classical.choice $ fintype.card_pos_iff.1 hfixed in begin revert hx, refine quotient.induction_on x (λ x hx, ⟨x, set.eq_of_card_eq_of_subset _ _⟩), { rw [conjugate_set_eq_image, set.card_image_of_injective _ conj_inj_left, card_sylow L₁ hp, card_sylow L₂ hp] }, assume y hy, have : (y⁻¹ * x)⁻¹ * x ∈ L₁ := quotient.exact (mem_fixed_points.1 hx ⟦y⁻¹ * x⟧ ⟨⟨y⁻¹, inv_mem hy⟩, rfl⟩), simp [mem_conjugate_set, mul_inv_rev, *, mul_assoc] at * end def conj_on_sylow [fintype G] {p : ℕ} (hp : nat.prime p) : group_action G {H : set G // is_sylow H hp} := { to_fun := λ x ⟨H, hH⟩, ⟨conjugate_set G x H, by exactI have h : is_subgroup (conjugate_set G x H) := sylow.is_subgroup_conj _ _, { card_eq := by exactI by rw [← card_sylow H hp, conjugate_set_eq_image, set.card_image_of_injective _ conj_inj_left], ..h }⟩, one := λ ⟨H, hH⟩, by simp!, mul := λ x y ⟨H, hH⟩, by simp! [mul_inv_rev, mul_assoc, function.comp, conjugate_set_eq_image, (set.image_comp _ _ _).symm] } lemma sylow3 [fintype G] {p : ℕ} (hp : nat.prime p) : card {H : set G // is_sylow H hp} ∣ card G := let ⟨H, hH⟩ := exists_sylow_p_subgroup G hp in have h : orbit (conj_on_sylow hp) ⟨H, hH⟩ = set.univ := set.eq_univ_iff_forall.2 (λ S, mem_orbit_iff.2 $ let ⟨x, (hx : S.val = _)⟩ := @sylow2 _ _ _ _ hp H S S.2 hH in ⟨x, subtype.eq (hx.symm ▸ rfl)⟩), have orbit_equiv : card (orbit (conj_on_sylow hp) ⟨H, hH⟩) = card (left_cosets (stabilizer (conj_on_sylow hp) ⟨H, hH⟩)) := card_congr (orbit_equiv_left_cosets (⟨H, hH⟩ : {H : set G // is_sylow H hp}) (conj_on_sylow hp)), by exactI begin rw [h, ← card_congr (set.equiv_univ _)] at orbit_equiv, rw [orbit_equiv, card_congr (@group_equiv_left_cosets_times_subgroup _ _ (stabilizer (conj_on_sylow hp) ⟨H, hH⟩) (by apply_instance)), card_prod], exact dvd_mul_right _ _ end lemma sylow3_part2 [fintype G] {p : ℕ} (hp : nat.prime p) : card {H : set G // is_sylow H hp} ≡ 1 [MOD p] := let ⟨H, hH⟩ := exists_sylow_p_subgroup G hp in have h : orbit (conj_on_sylow hp) ⟨H, hH⟩ = set.univ := set.eq_univ_iff_forall.2 (λ S, mem_orbit_iff.2 $ let ⟨x, (hx : S.val = _)⟩ := @sylow2 _ _ _ _ hp H S S.2 hH in ⟨x, subtype.eq (hx.symm ▸ rfl)⟩), by exactI begin have : _ % p = _ := mpl hp (card_sylow H hp) (conj_on_sylow hp), show _ = _, refine ((eq.trans _) this).trans _, congr, end end sylow
740a82b44a1828fa0e145166a5095579f337604a
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/asymptotics/superpolynomial_decay.lean
ea8d3972a69300d39829534662c86dfd11979e98
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
15,117
lean
/- Copyright (c) 2021 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import analysis.asymptotics.asymptotics import analysis.normed_space.ordered import data.polynomial.eval import topology.algebra.order.liminf_limsup /-! # Super-Polynomial Function Decay This file defines a predicate `asymptotics.superpolynomial_decay f` for a function satisfying one of following equivalent definitions (The definition is in terms of the first condition): * `x ^ n * f` tends to `𝓝 0` for all (or sufficiently large) naturals `n` * `|x ^ n * f|` tends to `𝓝 0` for all naturals `n` (`superpolynomial_decay_iff_abs_tendsto_zero`) * `|x ^ n * f|` is bounded for all naturals `n` (`superpolynomial_decay_iff_abs_is_bounded_under`) * `f` is `o(x ^ c)` for all integers `c` (`superpolynomial_decay_iff_is_o`) * `f` is `O(x ^ c)` for all integers `c` (`superpolynomial_decay_iff_is_O`) These conditions are all equivalent to conditions in terms of polynomials, replacing `x ^ c` with `p(x)` or `p(x)⁻¹` as appropriate, since asymptotically `p(x)` behaves like `X ^ p.nat_degree`. These further equivalences are not proven in mathlib but would be good future projects. The definition of superpolynomial decay for `f : α → β` is relative to a parameter `k : α → β`. Super-polynomial decay then means `f x` decays faster than `(k x) ^ c` for all integers `c`. Equivalently `f x` decays faster than `p.eval (k x)` for all polynomials `p : polynomial β`. The definition is also relative to a filter `l : filter α` where the decay rate is compared. When the map `k` is given by `n ↦ ↑n : ℕ → ℝ` this defines negligible functions: https://en.wikipedia.org/wiki/Negligible_function When the map `k` is given by `(r₁,...,rₙ) ↦ r₁*...*rₙ : ℝⁿ → ℝ` this is equivalent to the definition of rapidly decreasing functions given here: https://ncatlab.org/nlab/show/rapidly+decreasing+function # Main Theorems * `superpolynomial_decay.polynomial_mul` says that if `f(x)` is negligible, then so is `p(x) * f(x)` for any polynomial `p`. * `superpolynomial_decay_iff_zpow_tendsto_zero` gives an equivalence between definitions in terms of decaying faster than `k(x) ^ n` for all naturals `n` or `k(x) ^ c` for all integer `c`. -/ namespace asymptotics open_locale topological_space open filter /-- `f` has superpolynomial decay in parameter `k` along filter `l` if `k ^ n * f` tends to zero at `l` for all naturals `n` -/ def superpolynomial_decay {α β : Type*} [topological_space β] [comm_semiring β] (l : filter α) (k : α → β) (f : α → β) := ∀ (n : ℕ), tendsto (λ (a : α), (k a) ^ n * f a) l (𝓝 0) variables {α β : Type*} {l : filter α} {k : α → β} {f g g' : α → β} section comm_semiring variables [topological_space β] [comm_semiring β] lemma superpolynomial_decay.congr' (hf : superpolynomial_decay l k f) (hfg : f =ᶠ[l] g) : superpolynomial_decay l k g := λ z, (hf z).congr' (eventually_eq.mul (eventually_eq.refl l _) hfg) lemma superpolynomial_decay.congr (hf : superpolynomial_decay l k f) (hfg : ∀ x, f x = g x) : superpolynomial_decay l k g := λ z, (hf z).congr (λ x, congr_arg (λ a, k x ^ z * a) $ hfg x) @[simp] lemma superpolynomial_decay_zero (l : filter α) (k : α → β) : superpolynomial_decay l k 0 := λ z, by simpa only [pi.zero_apply, mul_zero] using tendsto_const_nhds lemma superpolynomial_decay.add [has_continuous_add β] (hf : superpolynomial_decay l k f) (hg : superpolynomial_decay l k g) : superpolynomial_decay l k (f + g) := λ z, by simpa only [mul_add, add_zero, pi.add_apply] using (hf z).add (hg z) lemma superpolynomial_decay.mul [has_continuous_mul β] (hf : superpolynomial_decay l k f) (hg : superpolynomial_decay l k g) : superpolynomial_decay l k (f * g) := λ z, by simpa only [mul_assoc, one_mul, mul_zero, pow_zero] using (hf z).mul (hg 0) lemma superpolynomial_decay.mul_const [has_continuous_mul β] (hf : superpolynomial_decay l k f) (c : β) : superpolynomial_decay l k (λ n, f n * c) := λ z, by simpa only [←mul_assoc, zero_mul] using tendsto.mul_const c (hf z) lemma superpolynomial_decay.const_mul [has_continuous_mul β] (hf : superpolynomial_decay l k f) (c : β) : superpolynomial_decay l k (λ n, c * f n) := (hf.mul_const c).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.param_mul (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (k * f) := λ z, tendsto_nhds.2 (λ s hs hs0, l.sets_of_superset ((tendsto_nhds.1 (hf $ z + 1)) s hs hs0) (λ x hx, by simpa only [set.mem_preimage, pi.mul_apply, ← mul_assoc, ← pow_succ'] using hx)) lemma superpolynomial_decay.mul_param (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (f * k) := (hf.param_mul).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.param_pow_mul (hf : superpolynomial_decay l k f) (n : ℕ) : superpolynomial_decay l k (k ^ n * f) := begin induction n with n hn, { simpa only [one_mul, pow_zero] using hf }, { simpa only [pow_succ, mul_assoc] using hn.param_mul } end lemma superpolynomial_decay.mul_param_pow (hf : superpolynomial_decay l k f) (n : ℕ) : superpolynomial_decay l k (f * k ^ n) := (hf.param_pow_mul n).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.polynomial_mul [has_continuous_add β] [has_continuous_mul β] (hf : superpolynomial_decay l k f) (p : polynomial β) : superpolynomial_decay l k (λ x, (p.eval $ k x) * f x) := polynomial.induction_on' p (λ p q hp hq, by simpa [add_mul] using hp.add hq) (λ n c, by simpa [mul_assoc] using (hf.param_pow_mul n).const_mul c) lemma superpolynomial_decay.mul_polynomial [has_continuous_add β] [has_continuous_mul β] (hf : superpolynomial_decay l k f) (p : polynomial β) : superpolynomial_decay l k (λ x, f x * (p.eval $ k x)) := (hf.polynomial_mul p).congr (λ _, mul_comm _ _) end comm_semiring section ordered_comm_semiring variables [topological_space β] [ordered_comm_semiring β] [order_topology β] lemma superpolynomial_decay.trans_eventually_le (hk : 0 ≤ᶠ[l] k) (hg : superpolynomial_decay l k g) (hg' : superpolynomial_decay l k g') (hfg : g ≤ᶠ[l] f) (hfg' : f ≤ᶠ[l] g') : superpolynomial_decay l k f := λ z, tendsto_of_tendsto_of_tendsto_of_le_of_le' (hg z) (hg' z) (hfg.mp (hk.mono $ λ x hx hx', mul_le_mul_of_nonneg_left hx' (pow_nonneg hx z))) (hfg'.mp (hk.mono $ λ x hx hx', mul_le_mul_of_nonneg_left hx' (pow_nonneg hx z))) end ordered_comm_semiring section linear_ordered_comm_ring variables [topological_space β] [linear_ordered_comm_ring β] [order_topology β] variables (l k f) lemma superpolynomial_decay_iff_abs_tendsto_zero : superpolynomial_decay l k f ↔ ∀ (n : ℕ), tendsto (λ (a : α), |(k a) ^ n * f a|) l (𝓝 0) := ⟨λ h z, (tendsto_zero_iff_abs_tendsto_zero _).1 (h z), λ h z, (tendsto_zero_iff_abs_tendsto_zero _).2 (h z)⟩ lemma superpolynomial_decay_iff_superpolynomial_decay_abs : superpolynomial_decay l k f ↔ superpolynomial_decay l (λ a, |k a|) (λ a, |f a|) := (superpolynomial_decay_iff_abs_tendsto_zero l k f).trans (by simp_rw [superpolynomial_decay, abs_mul, abs_pow]) variables {l k f} lemma superpolynomial_decay.trans_eventually_abs_le (hf : superpolynomial_decay l k f) (hfg : abs ∘ g ≤ᶠ[l] abs ∘ f) : superpolynomial_decay l k g := begin rw superpolynomial_decay_iff_abs_tendsto_zero at hf ⊢, refine λ z, tendsto_of_tendsto_of_tendsto_of_le_of_le' (tendsto_const_nhds) (hf z) (eventually_of_forall $ λ x, abs_nonneg _) (hfg.mono $ λ x hx, _), calc |k x ^ z * g x| = |k x ^ z| * |g x| : abs_mul (k x ^ z) (g x) ... ≤ |k x ^ z| * |f x| : mul_le_mul le_rfl hx (abs_nonneg _) (abs_nonneg _) ... = |k x ^ z * f x| : (abs_mul (k x ^ z) (f x)).symm, end lemma superpolynomial_decay.trans_abs_le (hf : superpolynomial_decay l k f) (hfg : ∀ x, |g x| ≤ |f x|) : superpolynomial_decay l k g := hf.trans_eventually_abs_le (eventually_of_forall hfg) end linear_ordered_comm_ring section field variables [topological_space β] [field β] (l k f) lemma superpolynomial_decay_mul_const_iff [has_continuous_mul β] {c : β} (hc0 : c ≠ 0) : superpolynomial_decay l k (λ n, f n * c) ↔ superpolynomial_decay l k f := ⟨λ h, (h.mul_const c⁻¹).congr (λ x, by simp [mul_assoc, mul_inv_cancel hc0]), λ h, h.mul_const c⟩ lemma superpolynomial_decay_const_mul_iff [has_continuous_mul β] {c : β} (hc0 : c ≠ 0) : superpolynomial_decay l k (λ n, c * f n) ↔ superpolynomial_decay l k f := ⟨λ h, (h.const_mul c⁻¹).congr (λ x, by simp [← mul_assoc, inv_mul_cancel hc0]), λ h, h.const_mul c⟩ variables {l k f} end field section linear_ordered_field variables [topological_space β] [linear_ordered_field β] [order_topology β] variable (f) lemma superpolynomial_decay_iff_abs_is_bounded_under (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℕ), is_bounded_under (≤) l (λ (a : α), |(k a) ^ z * f a|) := begin refine ⟨λ h z, tendsto.is_bounded_under_le (tendsto.abs (h z)), λ h, (superpolynomial_decay_iff_abs_tendsto_zero l k f).2 (λ z, _)⟩, obtain ⟨m, hm⟩ := h (z + 1), have h1 : tendsto (λ (a : α), (0 : β)) l (𝓝 0) := tendsto_const_nhds, have h2 : tendsto (λ (a : α), |(k a)⁻¹| * m) l (𝓝 0) := (zero_mul m) ▸ tendsto.mul_const m ((tendsto_zero_iff_abs_tendsto_zero _).1 hk.inv_tendsto_at_top), refine tendsto_of_tendsto_of_tendsto_of_le_of_le' h1 h2 (eventually_of_forall (λ x, abs_nonneg _)) ((eventually_map.1 hm).mp _), refine ((eventually_ne_of_tendsto_at_top hk 0).mono $ λ x hk0 hx, _), refine le_trans (le_of_eq _) (mul_le_mul_of_nonneg_left hx $ abs_nonneg (k x)⁻¹), rw [← abs_mul, ← mul_assoc, pow_succ, ← mul_assoc, inv_mul_cancel hk0, one_mul], end lemma superpolynomial_decay_iff_zpow_tendsto_zero (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℤ), tendsto (λ (a : α), (k a) ^ z * f a) l (𝓝 0) := begin refine ⟨λ h z, _, λ h n, by simpa only [zpow_coe_nat] using h (n : ℤ)⟩, by_cases hz : 0 ≤ z, { lift z to ℕ using hz, simpa using h z }, { have : tendsto (λ a, (k a) ^ z) l (𝓝 0) := tendsto.comp (tendsto_zpow_at_top_zero (not_le.1 hz)) hk, have h : tendsto f l (𝓝 0) := by simpa using h 0, exact (zero_mul (0 : β)) ▸ this.mul h }, end variable {f} lemma superpolynomial_decay.param_zpow_mul (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) (z : ℤ) : superpolynomial_decay l k (λ a, k a ^ z * f a) := begin rw superpolynomial_decay_iff_zpow_tendsto_zero _ hk at hf ⊢, refine λ z', (hf $ z' + z).congr' ((eventually_ne_of_tendsto_at_top hk 0).mono (λ x hx, _)), simp [zpow_add₀ hx, mul_assoc, pi.mul_apply], end lemma superpolynomial_decay.mul_param_zpow (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) (z : ℤ) : superpolynomial_decay l k (λ a, f a * k a ^ z) := (hf.param_zpow_mul hk z).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.inv_param_mul (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (k⁻¹ * f) := by simpa using (hf.param_zpow_mul hk (-1)) lemma superpolynomial_decay.param_inv_mul (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (f * k⁻¹) := (hf.inv_param_mul hk).congr (λ _, mul_comm _ _) variable (f) lemma superpolynomial_decay_param_mul_iff (hk : tendsto k l at_top) : superpolynomial_decay l k (k * f) ↔ superpolynomial_decay l k f := ⟨λ h, (h.inv_param_mul hk).congr' ((eventually_ne_of_tendsto_at_top hk 0).mono (λ x hx, by simp [← mul_assoc, inv_mul_cancel hx])), λ h, h.param_mul⟩ lemma superpolynomial_decay_mul_param_iff (hk : tendsto k l at_top) : superpolynomial_decay l k (f * k) ↔ superpolynomial_decay l k f := by simpa [mul_comm k] using superpolynomial_decay_param_mul_iff f hk lemma superpolynomial_decay_param_pow_mul_iff (hk : tendsto k l at_top) (n : ℕ) : superpolynomial_decay l k (k ^ n * f) ↔ superpolynomial_decay l k f := begin induction n with n hn, { simp }, { simpa [pow_succ, ← mul_comm k, mul_assoc, superpolynomial_decay_param_mul_iff (k ^ n * f) hk] using hn } end lemma superpolynomial_decay_mul_param_pow_iff (hk : tendsto k l at_top) (n : ℕ) : superpolynomial_decay l k (f * k ^ n) ↔ superpolynomial_decay l k f := by simpa [mul_comm f] using superpolynomial_decay_param_pow_mul_iff f hk n variable {f} end linear_ordered_field section normed_linear_ordered_field variable [normed_linear_ordered_field β] variables (l k f) lemma superpolynomial_decay_iff_norm_tendsto_zero : superpolynomial_decay l k f ↔ ∀ (n : ℕ), tendsto (λ (a : α), ∥(k a) ^ n * f a∥) l (𝓝 0) := ⟨λ h z, tendsto_zero_iff_norm_tendsto_zero.1 (h z), λ h z, tendsto_zero_iff_norm_tendsto_zero.2 (h z)⟩ lemma superpolynomial_decay_iff_superpolynomial_decay_norm : superpolynomial_decay l k f ↔ superpolynomial_decay l (λ a, ∥k a∥) (λ a, ∥f a∥) := (superpolynomial_decay_iff_norm_tendsto_zero l k f).trans (by simp [superpolynomial_decay]) variables {l k} variable [order_topology β] lemma superpolynomial_decay_iff_is_O (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℤ), is_O f (λ (a : α), (k a) ^ z) l := begin refine (superpolynomial_decay_iff_zpow_tendsto_zero f hk).trans _, have hk0 : ∀ᶠ x in l, k x ≠ 0 := eventually_ne_of_tendsto_at_top hk 0, refine ⟨λ h z, _, λ h z, _⟩, { refine is_O_of_div_tendsto_nhds (hk0.mono (λ x hx hxz, absurd (zpow_eq_zero hxz) hx)) 0 _, have : (λ (a : α), k a ^ z)⁻¹ = (λ (a : α), k a ^ (- z)) := funext (λ x, by simp), rw [div_eq_mul_inv, mul_comm f, this], exact h (-z) }, { suffices : is_O (λ (a : α), k a ^ z * f a) (λ (a : α), (k a)⁻¹) l, from is_O.trans_tendsto this hk.inv_tendsto_at_top, refine ((is_O_refl (λ a, (k a) ^ z) l).mul (h (- (z + 1)))).trans (is_O.of_bound 1 $ hk0.mono (λ a ha0, _)), simp only [one_mul, neg_add z 1, zpow_add₀ ha0, ← mul_assoc, zpow_neg₀, mul_inv_cancel (zpow_ne_zero z ha0), zpow_one] } end lemma superpolynomial_decay_iff_is_o (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℤ), is_o f (λ (a : α), (k a) ^ z) l := begin refine ⟨λ h z, _, λ h, (superpolynomial_decay_iff_is_O f hk).2 (λ z, (h z).is_O)⟩, have hk0 : ∀ᶠ x in l, k x ≠ 0 := eventually_ne_of_tendsto_at_top hk 0, have : is_o (λ (x : α), (1 : β)) k l := is_o_of_tendsto' (hk0.mono (λ x hkx hkx', absurd hkx' hkx)) (by simpa using hk.inv_tendsto_at_top), have : is_o f (λ (x : α), k x * k x ^ (z - 1)) l, by simpa using this.mul_is_O (((superpolynomial_decay_iff_is_O f hk).1 h) $ z - 1), refine this.trans_is_O (is_O.of_bound 1 (hk0.mono $ λ x hkx, le_of_eq _)), rw [one_mul, zpow_sub_one₀ hkx, mul_comm (k x), mul_assoc, inv_mul_cancel hkx, mul_one], end variable {f} end normed_linear_ordered_field end asymptotics
b9f12240f4af05a45017633d58d8a661f12c1630
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/number_theory/quadratic_reciprocity.lean
6588716c217f4e90351120b4e43436acfce81d5e
[ "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
24,987
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 field_theory.finite.basic import data.zmod.basic import data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_sq_eq_prime_iff_of_mod_four_eq_one`, and `exists_sq_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_sq_eq_neg_one_iff_mod_four_ne_three` and `exists_sq_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmod open_locale big_operators nat namespace zmod variables (p q : ℕ) [fact p.prime] [fact q.prime] /-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion_units (x : units (zmod p)) : (∃ y : units (zmod p), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim }, obtain ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmod p)), obtain ⟨n, hn⟩ : x ∈ submonoid.powers g, { rw mem_powers_iff_mem_gpowers, apply hg }, split, { rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, units_pow_card_sub_one_eq_one], }, { subst x, assume h, have key : 2 * (p / 2) ∣ n * (p / 2), { rw [← pow_mul] at h, rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_gpowers hg], apply order_of_dvd_of_pow_eq_one h }, have : 0 < p / 2 := nat.div_pos (fact.out (1 < p)) dec_trivial, obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key, refine ⟨g ^ m, _⟩, rw [mul_comm, pow_mul], }, end /-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : (∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)), simp only [units.ext_iff, sq, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end lemma exists_sq_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, exact dec_trivial }, haveI := fact.mk hp_odd, have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd, { rw [p_half_even, pow_zero, eq_self_iff_true, true_iff], contrapose! p_half_even with hp, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp], exact dec_trivial }, { rw [p_half_odd, pow_one, iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd, have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp hp_odd p_half_odd, generalize : p % 4 = k, dec_trivial! } end lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, revert a ha, exact dec_trivial }, rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd], exact pow_card_sub_one_eq_one ha end /-- **Wilson's Lemma**: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/ @[simp] lemma wilsons_lemma : ((p - 1)! : zmod p) = -1 := begin refine calc ((p - 1)! : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) : by rw [← finset.prod_Ico_id_eq_factorial, prod_nat_cast] ... = (∏ x : units (zmod p), x) : _ ... = -1 : by simp_rw [← units.coe_hom_apply, ← (units.coe_hom (zmod p)).map_prod, prod_univ_units_id_eq_neg_one, units.coe_hom_apply, units.coe_neg, units.coe_one], have hp : 0 < p := (fact.out p.prime).pos, symmetry, refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _, { intros a ha, rw [mem_Ico, ← nat.succ_sub hp, nat.succ_sub_one], split, { apply nat.pos_of_ne_zero, rw ← @val_zero p, assume h, apply units.ne_zero a (val_injective p h) }, { exact val_lt _ } }, { intros a ha, simp only [cast_id, nat_cast_val], }, { intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h }, { intros b hb, rw [mem_Ico, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, pos_iff_ne_zero] at hb, refine ⟨units.mk0 b _, finset.mem_univ _, _⟩, { assume h, apply hb.1, apply_fun val at h, simpa only [val_cast_of_lt hb.right, val_zero] using h }, { simp only [val_cast_of_lt hb.right, units.coe_mk0], } } end @[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 := begin conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (fact.out p.prime).pos] }, rw [← prod_nat_cast, finset.prod_Ico_id_eq_factorial, wilsons_lemma] end end zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.1.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, mem_Ico.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw nat_cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2)! : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! := calc (a ^ (p / 2) * (p / 2)! : zmod p) = (∏ x in Ico 1 (p / 2).succ, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_factorial, prod_const, card_Ico, succ_sub_one]; simp ... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp ... = (∏ x in Ico 1 (p / 2).succ, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [nat_cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : have (∏ x in Ico 1 (p / 2).succ, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = (∏ x in (Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_factorial] private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (mul_left_inj' (show ((p / 2)! : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.1.dvd_factorial, not_le]; exact nat.div_lt_self hp.1.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap private lemma eisenstein_lemma_aux₁ (p : ℕ) [fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + ∑ x in Ico 1 (p / 2).succ, x + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2.1, calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) : by simp only [val_nat_cast]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, nat.cast_sum, hp2] ... = _ : congr_arg2 (+) (calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2) = ∑ x in Ico 1 (p / 2).succ, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [nat.cast_sum] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + ((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, nat.cast_sum], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [nat.cast_sum]) rfl private lemma eisenstein_lemma_aux₂ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, nat.cast_sum, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _ $ finset.ext $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : ∑ a in Ico 1 (p / 2).succ, (a * q) / p = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext_iff] else calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ∑ a in Ico 1 (p / 2).succ, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ by finish) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : ∑ a in Ico 1 (p / 2).succ, (a * q) / p + ∑ a in Ico 1 (q / 2).succ, (a * p) / q = (p / 2) * (q / 2) := begin have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), { apply disjoint_filter.2 (λ x hx hpq hqp, _), have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp only [*, lt_succ_iff, mem_Ico, mem_product] at *; tauto) (nat.div_lt_self hp.1.pos dec_trivial), have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simpa only [this, nonpos_iff_eq_zero, mem_Ico, one_ne_zero, false_and, mem_product] using hx }, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext (λ x, by have := le_total (x.2 * p) (x.1 * q); simp only [mem_union, mem_filter, mem_Ico, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [card_Ico, nat.sub_zero, succ_sub_succ_eq_sub] end variables (p q : ℕ) [fact p.prime] [fact q.prime] namespace zmod /-- The Legendre symbol of `a` and `p` is an integer defined as * `0` if `a` is `0` modulo `p`; * `1` if `a ^ (p / 2)` is `1` modulo `p` (by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”); * `-1` otherwise. -/ def legendre_sym (a p : ℕ) : ℤ := if (a : zmod p) = 0 then 0 else if (a : zmod p) ^ (p / 2) = 1 then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] : (legendre_sym a p : zmod p) = (a ^ (p / 2)) := begin rw legendre_sym, by_cases ha : (a : zmod p) = 0, { simp only [if_pos, ha, zero_pow (nat.div_pos (hp.1.two_le) (succ_pos 1)), int.cast_zero] }, cases hp.1.eq_two_or_odd with hp2 hp_odd, { substI p, generalize : (a : (zmod 2)) = b, revert b, dec_trivial, }, { haveI := fact.mk hp_odd, rw if_neg ha, have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm, cases pow_div_two_eq_neg_one_or_one p ha with h h, { rw [if_pos h, h, int.cast_one], }, { rw [h, if_neg this, int.cast_neg, int.cast_one], } } end lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) : legendre_sym a p = -1 ∨ legendre_sym a p = 1 := by unfold legendre_sym; split_ifs; simp only [*, eq_self_iff_true, or_true, true_or] at * lemma legendre_sym_eq_zero_iff (a p : ℕ) : legendre_sym a p = 0 ↔ (a : zmod p) = 0 := begin split, { classical, contrapose, assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h, all_goals { rw h, norm_num } }, { assume ha, rw [legendre_sym, if_pos ha] } end /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} [fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a p ha0; cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) := begin rw [euler_criterion p ha0, legendre_sym, if_neg ha0], split_ifs, { simp only [h, eq_self_iff_true] }, finish -- this is quite slow. I'm actually surprised that it can close the goal at all! end lemma eisenstein_lemma [fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0] /-- **Quadratic reciprocity theorem** -/ theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) : legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm, have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq, by rw [eisenstein_lemma q hp1.1 hpq0, eisenstein_lemma p hq1.1 hqp0, ← pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm] -- move this local attribute [instance] lemma fact_prime_two : fact (nat.prime 2) := ⟨nat.prime_two⟩ lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1.1), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ by finish) dec_trivial ... < _ : by conv_rhs {rw [← div_add_mod p 2, hp1.1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin rw [gauss_lemma p (prime_ne_zero p 2 hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_sq_eq_two_iff [hp1 : fact (p % 2 = 1)] : (∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmod p) ≠ 0, from prime_ne_zero p 2 (λ h, by simpa [h] using hp1.1), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2, legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), resetI, rw fact_iff at hp1, revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, unfreezingI {clear_dependent p}, dec_trivial!, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] : (∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p := if hpq : p = q then by substI hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_one hp1⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hqp0, if_neg hpq0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_three hp3⟩, haveI hq_odd : fact (q % 2 = 1) := ⟨odd_of_mod_four_eq_three hq3⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hpq0, if_neg hqp0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction end end zmod
08bcf1dc2e7f5b83c425f5a78a9f2c349c241a31
4efff1f47634ff19e2f786deadd394270a59ecd2
/archive/sensitivity.lean
9400fb974aa0a4b67bdffbbc4feea790d3625f62
[ "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
15,496
lean
/- Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot -/ import tactic.fin_cases import tactic.apply_fun import linear_algebra.finite_dimensional import linear_algebra.dual import analysis.normed_space.basic /-! # Huang's sensitivity theorem A formalization of Hao Huang's sensitivity theorem: in the hypercube of dimension n ≥ 1, if one colors more than half the vertices then at least one vertex has at least √n colored neighbors. A fun summer collaboration by Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot, based on Don Knuth's account of the story (https://www.cs.stanford.edu/~knuth/papers/huang.pdf), using the Lean theorem prover (https://leanprover.github.io/), by Leonardo de Moura at Microsoft Research, and his collaborators (https://leanprover.github.io/people/), and using Lean's user maintained mathematics library (https://github.com/leanprover-community/mathlib). The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean -/ /-! The next two lines assert we do not want to give a constructive proof, but rather use classical logic. -/ noncomputable theory open_locale classical /-! We also want to use the notation `∑` for sums. -/ open_locale big_operators notation `|`x`|` := abs x notation `√` := real.sqrt open function bool linear_map fintype finite_dimensional dual_pair /-! ### The hypercube Notations: - `ℕ` denotes natural numbers (including zero). - `fin n` = {0, ⋯ , n - 1}. - `bool` = {`tt`, `ff`}. -/ /-- The hypercube in dimension `n`. -/ @[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool /-- The projection from `Q (n + 1)` to `Q n` forgetting the first value (ie. the image of zero). -/ def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ namespace Q /-! `n` will always denote a natural number. -/ variable (n : ℕ) /-- `Q 0` has a unique element. -/ instance : unique (Q 0) := ⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩ /-- `Q n` has 2^n elements. -/ lemma card : card (Q n) = 2^n := by simp [Q] /-! Until the end of this namespace, `n` will be an implicit argument (still a natural number). -/ variable {n} lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) := begin split, { rintro rfl, exact ⟨rfl, rfl⟩, }, { rintros ⟨h₀, h⟩, ext x, by_cases hx : x = 0, { rwa hx }, { rw ← fin.succ_pred x hx, convert congr_fun h (fin.pred x hx) } } end /-- The adjacency relation defining the graph structure on `Q n`: `p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/ def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i /-- In `Q 0`, no two vertices are adjacent. -/ lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q := by rintros ⟨v, _⟩; apply fin_zero_elim v /-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent iff their projections to `Q n` are equal. -/ lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) : p.adjacent q ↔ π p = π q := begin split, { rintros ⟨i, h_eq, h_uni⟩, ext x, by_contradiction hx, apply fin.succ_ne_zero x, rw [h_uni _ hx, h_uni _ h₀] }, { intro heq, use [0, h₀], intros y hy, contrapose! hy, rw ←fin.succ_pred _ hy, apply congr_fun heq } end /-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent iff their projections to `Q n` are adjacent. -/ lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) : p.adjacent q ↔ (π p).adjacent (π q) := begin split, { rintros ⟨i, h_eq, h_uni⟩, have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq), use [i.pred h_i, show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)), by rwa fin.succ_pred], intros y hy, simp [eq.symm (h_uni _ hy)] }, { rintros ⟨i, h_eq, h_uni⟩, use [i.succ, h_eq], intros y hy, rw [←fin.pred_inj, fin.pred_succ], { apply h_uni, change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ, simp [hy] }, { contrapose! hy, rw [hy, h₀] }, { apply fin.succ_ne_zero } } end @[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p := by simp only [adjacent, ne_comm] end Q /-! ### The vector space -/ /-- The free vector space on vertices of a hypercube, defined inductively. -/ def V : ℕ → Type | 0 := ℝ | (n+1) := V n × V n namespace V variables (n : ℕ) /-! `V n` is a real vector space whose equality relation is computable. -/ instance : decidable_eq (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : add_comm_group (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : vector_space ℝ (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } end V /-- The basis of `V` indexed by the hypercube, defined inductively. -/ noncomputable def e : Π {n}, Q n → V n | 0 := λ _, (1:ℝ) | (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x)) @[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl /-- The dual basis to `e`, defined inductively. -/ noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ | 0 _ := linear_map.id | (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _) ((ε $ π p).comp $ linear_map.snd _ _ _) variable {n : ℕ} lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 := begin induction n with n IH, { rw (show p = q, from subsingleton.elim p q), dsimp [ε, e], simp }, { dsimp [ε, e], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH], try { congr' 1, rw Q.succ_n_eq, finish }, try { erw (ε _).map_zero, have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish }, simp [this] } } } end /-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/ lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 := begin induction n with n ih, { dsimp [ε] at h, exact h (λ _, tt) }, { cases v with v₁ v₂, ext ; change _ = (0 : V n) ; simp only ; apply ih ; intro p ; [ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h), let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)], all_goals { specialize h q, rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|> rw [ε, show q 0 = ff, from rfl, cond_ff] at h, rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } } end /-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis and `ε` computes coefficients of decompositions of vectors on that basis. -/ def dual_pair_e_ε (n : ℕ) : dual_pair (@e n) (@ε n) := { eval := duality, total := @epsilon_total _ } /-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and, since this cardinal is finite, as a natural number in `findim_V` -/ lemma dim_V : vector_space.dim ℝ (V n) = 2^n := have vector_space.dim ℝ (V n) = (2^n : ℕ), by { rw [dim_eq_card_basis (dual_pair_e_ε _).is_basis, Q.card]; apply_instance }, by assumption_mod_cast instance : finite_dimensional ℝ (V n) := finite_dimensional.of_finite_basis (dual_pair_e_ε _).is_basis lemma findim_V : findim ℝ (V n) = 2^n := have _ := @dim_V n, by rw ←findim_eq_dim at this; assumption_mod_cast /-! ### The linear map -/ /-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$, defined inductively as a ℝ-linear map from `V n` to `V n`. -/ noncomputable def f : Π n, V n →ₗ[ℝ] V n | 0 := 0 | (n+1) := linear_map.prod (linear_map.coprod (f n) linear_map.id) (linear_map.coprod linear_map.id (-f n)) /-! The preceding definition uses linear map constructions to automatically get that `f` is linear, but its values are somewhat buried as a side-effect. The next two lemmas unbury them. -/ @[simp] lemma f_zero : f 0 = 0 := rfl lemma f_succ_apply (v : V (n+1)) : f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) := begin cases v, rw f, simp only [linear_map.id_apply, linear_map.prod_apply, prod.mk.inj_iff, linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply], exact ⟨rfl, rfl⟩ end /-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number is necessary since otherwise `n • v` refers to the multiplication defined using only the addition of `V`. -/ lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v := begin induction n with n IH; intro, { simpa only [nat.cast_zero, zero_smul] }, { cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel } end /-! We now compute the matrix of `f` in the `e` basis (`p` is the line index, `q` the column index). -/ lemma f_matrix : ∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 := begin induction n with n IH, { intros p q, dsimp [f], simp [Q.not_adjacent_zero] }, { intros p q, have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0, { split_ifs ; norm_num }, have f_map_zero := (show linear_map ℝ (V (n+0)) (V n), from f n).map_zero, dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq, Q.adj_iff_proj_adj] } } end /-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/ noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) := linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id /-! In the following lemmas, `m` will denote a natural number. -/ variables {m : ℕ} /-! Again we unpack what are the values of `g`. -/ lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) := by delta g; simp lemma g_injective : injective (g m) := begin rw g, intros x₁ x₂ h, simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff] at h, exact h.right end lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) : f (m + 1) w = √(m + 1) • w := begin rcases hv with ⟨v, rfl⟩, have : √(m+1) * √(m+1) = m+1 := real.mul_self_sqrt (by exact_mod_cast zero_le _), simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul], abel end /-! ### The main proof In this section, in order to enforce that `n` is positive, we write it as `m + 1` for some natural number `m`. -/ /-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/ notation `dim` X:70 := vector_space.dim ℝ ↥X /-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/ notation `fdim` := findim ℝ /-! `Span S` will denote the ℝ-subspace spanned by `S`. -/ notation `Span` := submodule.span ℝ /-! `Card X` will denote the cardinal of a subset of a finite type, as a natural number. -/ notation `Card` X:70 := X.to_finset.card /-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces, equipped with their subspace structures. The notations come from the general theory of lattices, with inf and sup (also known as meet and join). -/ /-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially intersects the range of `g m`. -/ lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) := begin let W := Span (e '' H), let img := (g m).range, suffices : 0 < dim (W ⊓ img), { simp only [exists_prop], exact_mod_cast exists_mem_ne_zero_of_dim_pos this }, have dim_le : dim (W ⊔ img) ≤ 2^(m + 1), { convert ← dim_submodule_le (W ⊔ img), apply dim_V }, have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m, { convert ← dim_sup_add_dim_inf_eq W img, rw ← dim_eq_of_injective (g m) g_injective, apply dim_V }, have dimW : dim W = card H, { have li : linear_independent ℝ (set.restrict e H) := linear_independent.comp (dual_pair_e_ε _).is_basis.1 _ subtype.val_injective, have hdW := dim_span li, rw set.range_restrict at hdW, convert hdW, rw [cardinal.mk_image_eq (dual_pair_e_ε _).is_basis.injective, cardinal.fintype_card] }, rw ← findim_eq_dim ℝ at ⊢ dim_le dim_add dimW, rw [← findim_eq_dim ℝ, ← findim_eq_dim ℝ] at dim_add, norm_cast at ⊢ dim_le dim_add dimW, rw nat.pow_succ at dim_le, rw set.to_finset_card at hH, linarith end theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) := begin rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩, have coeffs_support : ((dual_pair_e_ε (m+1)).coeffs y).support ⊆ H.to_finset, { intros p p_in, rw finsupp.mem_support_iff at p_in, rw set.mem_to_finset, exact (dual_pair_e_ε _).mem_of_mem_span y_mem_H p p_in }, obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|, from fintype.exists_max _, have H_q_pos : 0 < |ε q y|, { contrapose! y_ne, exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) }, refine ⟨q, (dual_pair_e_ε _).mem_of_mem_span y_mem_H q (abs_pos_iff.mp H_q_pos), _⟩, let s := √(m+1), suffices : s * |ε q y| ≤ ↑(_) * |ε q y|, from (mul_le_mul_right H_q_pos).mp ‹_›, let coeffs := (dual_pair_e_ε (m+1)).coeffs, calc s * (abs (ε q y)) = abs (ε q (s • y)) : by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)] ... = abs (ε q (f (m+1) y)) : by rw [← f_image_g y (by simpa using y_mem_g)] ... = abs (ε q (f (m+1) (lc _ (coeffs y)))) : by rw (dual_pair_e_ε _).decomposition y ... = abs ((coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘ λ (i : Q (m + 1)), e i) i)): by { erw [(f $ m+1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply] ; apply_instance } ... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| : norm_sum_le _ $ λ p, coeffs y p * _ ... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 : by simp only [abs_mul, f_matrix] ... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| : by simp [finset.sum_filter] ... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| : finset.sum_le_sum (λ p _, H_max p) ... = (finset.card ((coeffs y).support.filter (Q.adjacent q)): ℝ) * |coeffs y q| : by rw [finset.sum_const, nsmul_eq_mul] ... = (finset.card ((coeffs y).support ∩ (Q.adjacent q).to_finset): ℝ) * |coeffs y q| : by { congr' with x, simp, refl } ... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| : (mul_le_mul_right H_q_pos).mpr (by { norm_cast, exact finset.card_le_of_subset (by rw set.to_finset_inter; convert finset.inter_subset_inter_right coeffs_support) }) end
c91b8715f215fc56d486cc2b91dd76046315cb93
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/omega/find_scalars.lean
f43ce544aba72d6d92ce1a0cf5d1f89b3689819c
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
3,034
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Tactic for performing Fourier–Motzkin elimination to find a contradictory linear combination of input constraints. -/ import tactic.omega.term data.list.min_max open list.func namespace omega /-- Divide linear combinations into three groups by the coefficient of the `m`th variable in their resultant terms: negative, zero, or positive. -/ meta def trisect (m : nat) : list (list nat × term) → (list (list nat × term) × list (list nat × term) × list (list nat × term)) | [] := ([],[],[]) | ((p,t)::pts) := let (neg,zero,pos) := trisect pts in if get m t.snd < 0 then ((p,t)::neg,zero,pos) else if get m t.snd = 0 then (neg,(p,t)::zero,pos) else (neg,zero,(p,t)::pos) /-- Use two linear combinations to obtain a third linear combination whose resultant term does not include the `m`th variable. -/ meta def elim_var_aux (m : nat) : ((list nat × term) × (list nat × term)) → tactic (list nat × term) | ((p1,t1), (p2,t2)) := let n := int.nat_abs (get m t1.snd) in let o := int.nat_abs (get m t2.snd) in let lcm := (nat.lcm n o) in let n' := lcm / n in let o' := lcm / o in return (add (p1.map ((*) n')) (p2.map ((*) o')), term.add (t1.mul n') (t2.mul o')) /-- Use two lists of linear combinations (one in which the resultant terms include occurrences of the `m`th variable with positive coefficients, and one with negative coefficients) and linearly combine them in every possible way that eliminates the `m`th variable. -/ meta def elim_var (m : nat) (neg pos : list (list nat × term)) : tactic (list (list nat × term)) := let pairs := list.product neg pos in monad.mapm (elim_var_aux m) pairs /-- Search through a list of (linear combination × resultant term) pairs, find the first pair whose resultant term has a negative constant term, and return its linear combination -/ meta def find_neg_const : list (list nat × term) → tactic (list nat) | [] := tactic.failed | ((π,⟨c,_⟩)::l) := if c < 0 then return π else find_neg_const l /-- First, eliminate all variables by Fourier–Motzkin elimination. When all variables have been eliminated, find and return the linear combination which produces a constraint of the form `0 < k + t` such that `k` is the constant term of the RHS and `k < 0`. -/ meta def find_scalars_core : nat → list (list nat × term) → tactic (list nat) | 0 pts := find_neg_const pts | (m+1) pts := let (neg,zero,pos) := trisect m pts in do new ← elim_var m neg pos, find_scalars_core m (new ++ zero) /-- Perform Fourier–Motzkin elimination to find a contradictory linear combination of input constraints. -/ meta def find_scalars (ts : list term) : tactic (list nat) := find_scalars_core (ts.map (λ t : term, t.snd.length)).maximum.iget (ts.map_with_index (λ m t, (list.func.set 1 [] m, t))) end omega
b7a1f99cb24befa425d84081acd6751a553447c6
4727251e0cd73359b15b664c3170e5d754078599
/src/representation_theory/basic.lean
1ed9a589137760a9b1e9874dc25c36d9dbd72df0
[ "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,657
lean
/- Copyright (c) 2022 Antoine Labelle. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Labelle -/ import algebra.module.basic import algebra.module.linear_map import algebra.monoid_algebra.basic import linear_algebra.trace import linear_algebra.dual import linear_algebra.free_module.basic /-! # Monoid representations This file introduces monoid representations and their characters and defines a few ways to construct representations. ## Main definitions * representation.representation * representation.character * representation.tprod * representation.lin_hom * represensation.dual ## Implementation notes Representations of a monoid `G` on a `k`-module `V` are implemented as homomorphisms `G →* (V →ₗ[k] V)`. -/ open monoid_algebra (lift) (of) open linear_map section variables (k G V : Type*) [comm_semiring k] [monoid G] [add_comm_monoid V] [module k V] /-- A representation of `G` on the `k`-module `V` is an homomorphism `G →* (V →ₗ[k] V)`. -/ abbreviation representation := G →* (V →ₗ[k] V) end namespace representation section trivial variables {k G V : Type*} [comm_semiring k] [monoid G] [add_comm_monoid V] [module k V] /-- The trivial representation of `G` on the one-dimensional module `k`. -/ def trivial : representation k G k := 1 @[simp] lemma trivial_def (g : G) (v : k) : trivial g v = v := rfl end trivial section monoid_algebra variables {k G V : Type*} [comm_semiring k] [monoid G] [add_comm_monoid V] [module k V] variables (ρ : representation k G V) /-- A `k`-linear representation of `G` on `V` can be thought of as an algebra map from `monoid_algebra k G` into the `k`-linear endomorphisms of `V`. -/ noncomputable def as_algebra_hom : monoid_algebra k G →ₐ[k] (module.End k V) := (lift k G _) ρ lemma as_algebra_hom_def : as_algebra_hom ρ = (lift k G _) ρ := rfl @[simp] lemma as_algebra_hom_single (g : G): (as_algebra_hom ρ (finsupp.single g 1)) = ρ g := by simp only [as_algebra_hom_def, monoid_algebra.lift_single, one_smul] lemma as_algebra_hom_of (g : G): (as_algebra_hom ρ (of k G g)) = ρ g := by simp only [monoid_algebra.of_apply, as_algebra_hom_single] /-- A `k`-linear representation of `G` on `V` can be thought of as a module over `monoid_algebra k G`. -/ noncomputable def as_module : module (monoid_algebra k G) V := module.comp_hom V (as_algebra_hom ρ).to_ring_hom end monoid_algebra section group variables {k G V : Type*} [comm_semiring k] [group G] [add_comm_monoid V] [module k V] variables (ρ : representation k G V) /-- When `G` is a group, a `k`-linear representation of `G` on `V` can be thought of as a group homomorphism from `G` into the invertible `k`-linear endomorphisms of `V`. -/ def as_group_hom : G →* units (V →ₗ[k] V) := monoid_hom.to_hom_units ρ lemma as_group_hom_apply (g : G) : ↑(as_group_hom ρ g) = ρ g := by simp only [as_group_hom, monoid_hom.coe_to_hom_units] end group section character variables {k G V : Type*} [comm_ring k] [group G] [add_comm_group V] [module k V] variables (ρ : representation k G V) /-- The character associated to a representation of `G`, which as a map `G → k` sends each element to the trace of the corresponding linear map. -/ @[simp] noncomputable def character (g : G) : k := trace k V (ρ g) theorem char_mul_comm (g : G) (h : G) : character ρ (h * g) = character ρ (g * h) := by simp only [trace_mul_comm, character, map_mul] /-- The character of a representation is constant on conjugacy classes. -/ theorem char_conj (g : G) (h : G) : (character ρ) (h * g * h⁻¹) = (character ρ) g := by simp only [character, ←as_group_hom_apply, map_mul, map_inv, trace_conj] variables [nontrivial k] [module.free k V] [module.finite k V] /-- The evaluation of the character at the identity is the dimension of the representation. -/ theorem char_one : character ρ 1 = finite_dimensional.finrank k V := by simp only [character, map_one, trace_one] end character section tensor_product variables {k G V W : Type*} [comm_semiring k] [monoid G] variables [add_comm_monoid V] [module k V] [add_comm_monoid W] [module k W] variables (ρV : representation k G V) (ρW : representation k G W) open_locale tensor_product /-- Given representations of `G` on `V` and `W`, there is a natural representation of `G` on their tensor product `V ⊗[k] W`. -/ def tprod : representation k G (V ⊗[k] W) := { to_fun := λ g, tensor_product.map (ρV g) (ρW g), map_one' := by simp only [map_one, tensor_product.map_one], map_mul' := λ g h, by simp only [map_mul, tensor_product.map_mul] } notation ρV ` ⊗ ` ρW := tprod ρV ρW @[simp] lemma tprod_apply (g : G) : (ρV ⊗ ρW) g = tensor_product.map (ρV g) (ρW g) := rfl end tensor_product section linear_hom variables {k G V W : Type*} [comm_semiring k] [group G] variables [add_comm_monoid V] [module k V] [add_comm_monoid W] [module k W] variables (ρV : representation k G V) (ρW : representation k G W) /-- Given representations of `G` on `V` and `W`, there is a natural representation of `G` on the module `V →ₗ[k] W`, where `G` acts by conjugation. -/ def lin_hom : representation k G (V →ₗ[k] W) := { to_fun := λ g, { to_fun := λ f, (ρW g) ∘ₗ f ∘ₗ (ρV g⁻¹), map_add' := λ f₁ f₂, by simp_rw [add_comp, comp_add], map_smul' := λ r f, by simp_rw [ring_hom.id_apply, smul_comp, comp_smul]}, map_one' := linear_map.ext $ λ x, by simp_rw [coe_mk, inv_one, map_one, one_apply, one_eq_id, comp_id, id_comp], map_mul' := λ g h, linear_map.ext $ λ x, by simp_rw [coe_mul, coe_mk, function.comp_apply, mul_inv_rev, map_mul, mul_eq_comp, comp_assoc ]} @[simp] lemma lin_hom_apply (g : G) (f : V →ₗ[k] W) : (lin_hom ρV ρW) g f = (ρW g) ∘ₗ f ∘ₗ (ρV g⁻¹) := rfl /-- The dual of a representation `ρ` of `G` on a module `V`, given by `(dual ρ) g f = f ∘ₗ (ρ g⁻¹)`, where `f : module.dual k V`. -/ def dual : representation k G (module.dual k V) := { to_fun := λ g, { to_fun := λ f, f ∘ₗ (ρV g⁻¹), map_add' := λ f₁ f₂, by simp only [add_comp], map_smul' := λ r f, by {ext, simp only [coe_comp, function.comp_app, smul_apply, ring_hom.id_apply]} }, map_one' := by {ext, simp only [coe_comp, function.comp_app, map_one, inv_one, coe_mk, one_apply]}, map_mul' := λ g h, by {ext, simp only [coe_comp, function.comp_app, mul_inv_rev, map_mul, coe_mk, mul_apply]}} @[simp] lemma dual_apply (g : G) (f : module.dual k V) : (dual ρV) g f = f ∘ₗ (ρV g⁻¹) := rfl end linear_hom end representation
d352a56c70c26c6ef47c244b0a1955d58d60cfaf
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.7.lean
8e1be1f0954d159322ca724e1e17575422bd23eb
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
266
lean
/- page 102 -/ import standard namespace hide inductive nat : Type := | zero : nat | succ : nat → nat namespace nat notation 0 := zero -- BEGIN definition add (m : nat) : nat → nat | add 0 := m | add (succ n) := succ (add n) -- END end nat end hide
d8efce8cf7756d6c075093c9d2ae7ae2f6a37481
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/sig1.lean
6be66eca79897cfc9d8ca86ee4ae0dcbf14a5db1
[ "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
249
lean
check sig (x y : Nat) (z : Bool), x > y ∧ z check sig a : Nat, Nat check Nat ⨯ Bool ⨯ Nat check Nat # Bool # Nat check Nat # Type # Nat set_option pp::unicode false check sig x : Nat, Nat check Nat ⨯ Bool ⨯ Nat set_option pp::unicode true
705d35385f8b90c35ff8924e15714cb7fdb9134b
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/PrettyPrinter/Formatter.lean
ad0ae82ce626bb883eb889169887e328aca20a02
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,084
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! The formatter turns a `Syntax` tree into a `Format` object, inserting both mandatory whitespace (to separate adjacent tokens) as well as "pretty" optional whitespace. The basic approach works much like the parenthesizer: A right-to-left traversal over the syntax tree, driven by parser-specific handlers registered via attributes. The traversal is right-to-left so that when emitting a token, we already know the text following it and can decide whether or not whitespace between the two is necessary. -/ import Lean.CoreM import Lean.Parser.Extension import Lean.KeyedDeclsAttribute import Lean.ParserCompiler.Attribute import Lean.PrettyPrinter.Basic namespace Lean namespace PrettyPrinter namespace Formatter structure Context where options : Options table : Parser.TokenTable structure State where stxTrav : Syntax.Traverser -- Textual content of `stack` up to the first whitespace (not enclosed in an escaped ident). We assume that the textual -- content of `stack` is modified only by `pushText` and `pushLine`, so `leadWord` is adjusted there accordingly. leadWord : String := "" -- Stack of generated Format objects, analogous to the Syntax stack in the parser. -- Note, however, that the stack is reversed because of the right-to-left traversal. stack : Array Format := #[] end Formatter abbrev FormatterM := ReaderT Formatter.Context $ StateRefT Formatter.State CoreM @[inline] def FormatterM.orelse {α} (p₁ p₂ : FormatterM α) : FormatterM α := do let s ← get catchInternalId backtrackExceptionId p₁ (fun _ => do set s; p₂) instance {α} : OrElse (FormatterM α) := ⟨FormatterM.orelse⟩ abbrev Formatter := FormatterM Unit unsafe def mkFormatterAttribute : IO (KeyedDeclsAttribute Formatter) := KeyedDeclsAttribute.init { builtinName := `builtinFormatter, name := `formatter, descr := "Register a formatter for a parser. [formatter k] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `SyntaxNodeKind` `k`.", valueTypeName := `Lean.PrettyPrinter.Formatter, evalKey := fun builtin stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx -- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to -- synthesize a formatter for it immediately, so we just check for a declaration in this case if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id else throwError "invalid [formatter] argument, unknown syntax kind '{id}'" } `Lean.PrettyPrinter.formatterAttribute @[builtinInit mkFormatterAttribute] constant formatterAttribute : KeyedDeclsAttribute Formatter unsafe def mkCombinatorFormatterAttribute : IO ParserCompiler.CombinatorAttribute := ParserCompiler.registerCombinatorAttribute `combinatorFormatter "Register a formatter for a parser combinator. [combinatorFormatter c] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `Parser` declaration `c`. Note that, unlike with [formatter], this is not a node kind since combinators usually do not introduce their own node kinds. The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced with `Formatter` in the parameter types." @[builtinInit mkCombinatorFormatterAttribute] constant combinatorFormatterAttribute : ParserCompiler.CombinatorAttribute namespace Formatter open Lean.Core open Lean.Parser def throwBacktrack {α} : FormatterM α := throw $ Exception.internal backtrackExceptionId instance : Syntax.MonadTraverser FormatterM := ⟨{ get := State.stxTrav <$> get, set := fun t => modify (fun st => { st with stxTrav := t }), modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t })) }⟩ open Syntax.MonadTraverser def getStack : FormatterM (Array Format) := do let st ← get pure st.stack def getStackSize : FormatterM Nat := do let stack ← getStack; pure stack.size def setStack (stack : Array Format) : FormatterM Unit := modify fun st => { st with stack := stack } def push (f : Format) : FormatterM Unit := modify fun st => { st with stack := st.stack.push f } def pushLine : FormatterM Unit := do push Format.line; modify fun st => { st with leadWord := "" } /-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/ def visitArgs (x : FormatterM Unit) : FormatterM Unit := do let stx ← getCur if stx.getArgs.size > 0 then goDown (stx.getArgs.size - 1) *> x <* goUp goLeft /-- Execute `x`, pass array of generated Format objects to `fn`, and push result. -/ def fold (fn : Array Format → Format) (x : FormatterM Unit) : FormatterM Unit := do let sp ← getStackSize x let stack ← getStack let f := fn $ stack.extract sp stack.size setStack $ (stack.shrink sp).push f /-- Execute `x` and concatenate generated Format objects. -/ def concat (x : FormatterM Unit) : FormatterM Unit := do fold (Array.foldl (fun acc f => if acc.isNil then f else f ++ acc) Format.nil) x def indent (x : Formatter) (indent : Option Int := none) : Formatter := do concat x let ctx ← read let indent := indent.getD $ Std.Format.getIndent ctx.options modify fun st => { st with stack := st.stack.pop.push (Format.nest indent st.stack.back) } def group (x : Formatter) : Formatter := do concat x modify fun st => { st with stack := st.stack.pop.push (Format.fill st.stack.back) } /-- Tags the top of the stack with `stx`'s position, if it has one. -/ def tagTop (stx : Syntax) : Formatter := do if let some p := stx.getPos? then modify fun st => { st with stack := st.stack.pop.push (Format.tag p st.stack.back) } @[combinatorFormatter Lean.Parser.orelse] def orelse.formatter (p1 p2 : Formatter) : Formatter := -- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try -- them in turn. Uses the syntax traverser non-linearly! p1 <|> p2 -- `mkAntiquot` is quite complex, so we'd rather have its formatter synthesized below the actual parser definition. -- Note that there is a mutual recursion -- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere -- anyway. @[extern "lean_mk_antiquot_formatter"] constant mkAntiquot.formatter' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter -- break up big mutual recursion @[extern "lean_pretty_printer_formatter_interpret_parser_descr"] constant interpretParserDescr' : ParserDescr → CoreM Formatter unsafe def formatterForKindUnsafe (k : SyntaxNodeKind) : Formatter := do if k == `missing then push "<missing>" goLeft else let f ← runForNodeKind formatterAttribute k interpretParserDescr' let stx ← getCur concat f tagTop stx @[implementedBy formatterForKindUnsafe] constant formatterForKind (k : SyntaxNodeKind) : Formatter @[combinatorFormatter Lean.Parser.withAntiquot] def withAntiquot.formatter (antiP p : Formatter) : Formatter := -- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather -- fix the backtracking hack outright. orelse.formatter antiP p @[combinatorFormatter Lean.Parser.withAntiquotSuffixSplice] def withAntiquotSuffixSplice.formatter (k : SyntaxNodeKind) (p suffix : Formatter) : Formatter := do if (← getCur).isAntiquotSuffixSplice then visitArgs <| suffix *> p else p @[combinatorFormatter Lean.Parser.tokenWithAntiquot] def tokenWithAntiquot.formatter (p : Formatter) : Formatter := do if (← getCur).isTokenAntiquot then visitArgs p else p @[combinatorFormatter Lean.Parser.categoryParser] def categoryParser.formatter (cat : Name) : Formatter := group $ indent do let stx ← getCur trace[PrettyPrinter.format] "formatting {indentD (format stx)}" if stx.getKind == `choice then visitArgs do -- format only last choice -- TODO: We could use elaborator data here to format the chosen child when available formatterForKind (← getCur).getKind else withAntiquot.formatter (mkAntiquot.formatter' cat.toString none) (formatterForKind stx.getKind) @[combinatorFormatter Lean.Parser.categoryParserOfStack] def categoryParserOfStack.formatter (offset : Nat) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) categoryParser.formatter stx.getId @[combinatorFormatter Lean.Parser.parserOfStack] def parserOfStack.formatter (offset : Nat) (prec : Nat := 0) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) formatterForKind stx.getKind @[combinatorFormatter Lean.Parser.error] def error.formatter (msg : String) : Formatter := pure () @[combinatorFormatter Lean.Parser.errorAtSavedPos] def errorAtSavedPos.formatter (msg : String) (delta : Bool) : Formatter := pure () @[combinatorFormatter Lean.Parser.atomic] def atomic.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.lookahead] def lookahead.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedBy] def notFollowedBy.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.andthen] def andthen.formatter (p1 p2 : Formatter) : Formatter := p2 *> p1 def checkKind (k : SyntaxNodeKind) : FormatterM Unit := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.format.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" throwBacktrack @[combinatorFormatter Lean.Parser.node] def node.formatter (k : SyntaxNodeKind) (p : Formatter) : Formatter := do checkKind k; visitArgs p @[combinatorFormatter Lean.Parser.trailingNode] def trailingNode.formatter (k : SyntaxNodeKind) (_ _ : Nat) (p : Formatter) : Formatter := do checkKind k visitArgs do p; -- leading term, not actually produced by `p` categoryParser.formatter `foo def parseToken (s : String) : FormatterM ParserState := do Parser.tokenFn [] { input := s, fileName := "", fileMap := FileMap.ofString "", prec := 0, env := ← getEnv, options := ← getOptions, tokens := (← read).table } (Parser.mkParserState s) def pushTokenCore (tk : String) : FormatterM Unit := do if tk.toSubstring.dropRightWhile (fun s => s == ' ') == tk.toSubstring then push tk else pushLine push tk.trimRight def pushToken (info : SourceInfo) (tk : String) : FormatterM Unit := do match info with | SourceInfo.original _ _ ss _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then push s!"\n{ss'}" else push s!" {ss'}" modify fun st => { st with leadWord := "" } | _ => pure () let st ← get -- If there is no space between `tk` and the next word, see if we would parse more than `tk` as a single token if st.leadWord != "" && tk.trimRight == tk then let tk' := tk.trimLeft let t ← parseToken $ tk' ++ st.leadWord if t.pos <= tk'.bsize then -- stopped within `tk` => use it as is, extend `leadWord` if not prefixed by whitespace pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk ++ st.leadWord else "" } else -- stopped after `tk` => add space pushTokenCore $ tk ++ " " modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } else -- already separated => use `tk` as is pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } match info with | SourceInfo.original ss _ _ _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then do -- Indentation is automatically increased when entering a category, but comments should be aligned -- with the actual token, so dedent indent (push s!"{ss'}\n") (some ((0:Int) - Std.Format.getIndent (← getOptions))) else push s!"{ss'} " modify fun st => { st with leadWord := "" } | _ => pure () @[combinatorFormatter Lean.Parser.symbolNoAntiquot] def symbolNoAntiquot.formatter (sym : String) : Formatter := do let stx ← getCur if stx.isToken sym then do let (Syntax.atom info _) ← pure stx | unreachable! pushToken info sym goLeft else do trace[PrettyPrinter.format.backtrack] "unexpected syntax '{format stx}', expected symbol '{sym}'" throwBacktrack @[combinatorFormatter Lean.Parser.nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.formatter := symbolNoAntiquot.formatter @[combinatorFormatter Lean.Parser.rawCh] def rawCh.formatter (ch : Char) := symbolNoAntiquot.formatter ch.toString @[combinatorFormatter Lean.Parser.unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.formatter (sym asciiSym : String) : Formatter := do let Syntax.atom info val ← getCur | throwError m!"not an atom: {← getCur}" if val == sym.trim then pushToken info sym else pushToken info asciiSym; goLeft @[combinatorFormatter Lean.Parser.identNoAntiquot] def identNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" let id := id.simpMacroScopes pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.rawIdentNoAntiquot] def rawIdentNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.identEq] def identEq.formatter (id : Name) := rawIdentNoAntiquot.formatter def visitAtom (k : SyntaxNodeKind) : Formatter := do let stx ← getCur if k != Name.anonymous then checkKind k let Syntax.atom info val ← pure $ stx.ifNode (fun n => n.getArg 0) (fun _ => stx) | throwError m!"not an atom: {stx}" pushToken info val goLeft @[combinatorFormatter Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.formatter := visitAtom charLitKind @[combinatorFormatter Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.formatter := visitAtom strLitKind @[combinatorFormatter Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.formatter := visitAtom nameLitKind @[combinatorFormatter Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.formatter := visitAtom numLitKind @[combinatorFormatter Lean.Parser.scientificLitNoAntiquot] def scientificLitNoAntiquot.formatter := visitAtom scientificLitKind @[combinatorFormatter Lean.Parser.fieldIdx] def fieldIdx.formatter := visitAtom fieldIdxKind @[combinatorFormatter Lean.Parser.manyNoAntiquot] def manyNoAntiquot.formatter (p : Formatter) : Formatter := do let stx ← getCur visitArgs $ stx.getArgs.size.forM fun _ => p @[combinatorFormatter Lean.Parser.many1NoAntiquot] def many1NoAntiquot.formatter (p : Formatter) : Formatter := manyNoAntiquot.formatter p @[combinatorFormatter Lean.Parser.optionalNoAntiquot] def optionalNoAntiquot.formatter (p : Formatter) : Formatter := visitArgs p @[combinatorFormatter Lean.Parser.many1Unbox] def many1Unbox.formatter (p : Formatter) : Formatter := do let stx ← getCur if stx.getKind == nullKind then do manyNoAntiquot.formatter p else p @[combinatorFormatter Lean.Parser.sepByNoAntiquot] def sepByNoAntiquot.formatter (p pSep : Formatter) : Formatter := do let stx ← getCur visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep @[combinatorFormatter Lean.Parser.sepBy1NoAntiquot] def sepBy1NoAntiquot.formatter := sepByNoAntiquot.formatter @[combinatorFormatter Lean.Parser.withPosition] def withPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutPosition] def withoutPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withForbidden] def withForbidden.formatter (tk : Token) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutForbidden] def withoutForbidden.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutInfo] def withoutInfo.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.setExpected] def setExpected.formatter (expected : List String) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.incQuotDepth] def incQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.decQuotDepth] def decQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.suppressInsideQuot] def suppressInsideQuot.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.evalInsideQuot] def evalInsideQuot.formatter (declName : Name) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.checkWsBefore] def checkWsBefore.formatter : Formatter := do let st ← get if st.leadWord != "" then pushLine @[combinatorFormatter Lean.Parser.checkPrec] def checkPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLhsPrec] def checkLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.setLhsPrec] def setLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkStackTop] def checkStackTop.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoWsBefore] def checkNoWsBefore.formatter : Formatter := -- prevent automatic whitespace insertion modify fun st => { st with leadWord := "" } @[combinatorFormatter Lean.Parser.checkLinebreakBefore] def checkLinebreakBefore.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkTailWs] def checkTailWs.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGe] def checkColGe.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGt] def checkColGt.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLineEq] def checkLineEq.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.eoi] def eoi.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkInsideQuot] def checkInsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkOutsideQuot] def checkOutsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.skip] def skip.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.pushNone] def pushNone.formatter : Formatter := goLeft @[combinatorFormatter Lean.Parser.interpolatedStr] def interpolatedStr.formatter (p : Formatter) : Formatter := do visitArgs $ (← getCur).getArgs.reverse.forM fun chunk => match chunk.isLit? interpolatedStrLitKind with | some str => push str *> goLeft | none => p @[combinatorFormatter Lean.Parser.dbgTraceState] def dbgTraceState.formatter (label : String) (p : Formatter) : Formatter := p @[combinatorFormatter ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Formatter) : Formatter := if c then t else e abbrev FormatterAliasValue := AliasValue Formatter builtin_initialize formatterAliasesRef : IO.Ref (NameMap FormatterAliasValue) ← IO.mkRef {} def registerAlias (aliasName : Name) (v : FormatterAliasValue) : IO Unit := do Parser.registerAliasCore formatterAliasesRef aliasName v instance : Coe Formatter FormatterAliasValue := { coe := AliasValue.const } instance : Coe (Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.unary } instance : Coe (Formatter → Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.binary } end Formatter open Formatter def format (formatter : Formatter) (stx : Syntax) : CoreM Format := do trace[PrettyPrinter.format.input] "{Std.format stx}" let options ← getOptions let table ← Parser.builtinTokenTable.get catchInternalId backtrackExceptionId (do let (_, st) ← (concat formatter { table := table, options := options }).run { stxTrav := Syntax.Traverser.fromSyntax stx }; pure $ Format.fill $ st.stack.get! 0) (fun _ => throwError "format: uncaught backtrack exception") def formatTerm := format $ categoryParser.formatter `term def formatCommand := format $ categoryParser.formatter `command builtin_initialize registerTraceClass `PrettyPrinter.format; end PrettyPrinter end Lean
353d984afd36cc33830fb9897cd8f7ad70f514bd
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/ring_theory/localization.lean
7c4a7d3db71c6841d58c146cfb9fdf71a390fdb4
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
69,363
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston -/ import data.equiv.ring import group_theory.monoid_localization import ring_theory.ideal.operations import ring_theory.algebraic import ring_theory.integral_closure import ring_theory.non_zero_divisors /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. Given such a localization map `f : R →+* S`, we can define the surjection `localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. Similarly, given commutative rings `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `S` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We show the localization as a quotient type, defined in `group_theory.monoid_localization` as `submonoid.localization`, is a `comm_ring` and that the natural ring hom `of : R →+* localization M` is a localization map. We show that a localization at the complement of a prime ideal is a local ring. We prove some lemmas about the `R`-algebra structure of `S`. When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for `localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions. We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is a field. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a `submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a `localization_map` `f` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `f.to_localization_map`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `of : localization_map M (localization M)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] {P : Type*} [comm_ring P] open function set_option old_structure_cmd true /-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S` satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`. We later define an instance coercing a localization map `f` to its codomain `S` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. -/ @[nolint has_inhabited_instance] structure localization_map extends ring_hom R S, submonoid.localization_map M S /-- The ring hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_ring_hom /-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`. See `group_theory.monoid_localization` for its definition. -/ add_decl_doc localization_map.to_localization_map variables {M S} namespace ring_hom /-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/ def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y)) (H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) : localization_map M S := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end ring_hom /-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of `comm_ring`s. -/ def submonoid.localization_map.to_ring_localization (f : submonoid.localization_map M S) (h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) : localization_map M S := { ..ring_hom.mk' f.to_monoid_hom h, ..f } namespace localization_map variables (f : localization_map M S) /-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know` the map needed to induce the instance. -/ @[nolint unused_arguments has_inhabited_instance] def codomain (f : localization_map M S) := S instance : comm_ring f.codomain := by assumption instance {K : Type*} [field K] (f : localization_map M K) : field f.codomain := by assumption /-- Short for `to_ring_hom`; used for applying a localization map as a function. -/ abbreviation to_map := f.to_ring_hom lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y @[ext] lemma ext {f g : localization_map M S} (h : ∀ x, f.to_map x = g.to_map x) : f = g := begin cases f, cases g, simp only at *, exact funext h end lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) := λ _ _ h, ext $ ring_hom.ext_iff.1 h /-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ set.range f.to_map -- TODO: define a subalgebra of `is_integer`s lemma is_integer_zero : f.is_integer 0 := ⟨0, f.to_map.map_zero⟩ lemma is_integer_one : f.is_integer 1 := ⟨1, f.to_map.map_one⟩ variables {f} lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [f.to_map.map_add, ha, hb] end lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [f.to_map.map_mul, ha, hb] end lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) : f.is_integer (f.to_map a * b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, f.to_map.map_mul] end variables (f) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer f (a * f.to_map b) := let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer f (f.to_map b * a) := by { simp_rw mul_comm _ a, apply exists_integer_multiple' } /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec {f : localization_map M S} (z : S) : z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 := classical.some_spec $ f.surj z /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' {f : localization_map M S} (z : S) : f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z := by rw [mul_comm, sec_spec] open_locale big_operators /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer f (f.to_map b * a) := begin haveI := classical.prop_decidable, use ∏ a in s, (f.to_localization_map.sec a).2, intros a ha, use (∏ x in s.erase a, (f.to_localization_map.sec x).2) * (f.to_localization_map.sec a).1, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←f.to_map.map_mul], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha], refl, end lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := f.to_localization_map.map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.to_localization_map.map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 := by rw [hx, f.to_map.map_zero] at h; exact (f.map_units y).mul_left_eq_zero.1 h /-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S := f.to_localization_map.mk' x y @[simp] lemma mk'_sec (z : S) : f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z := f.to_localization_map.mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := f.to_localization_map.mk'_mul _ _ _ _ lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x := f.to_localization_map.mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : f.mk' x y * f.to_map y = f.to_map x := f.to_localization_map.mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : f.to_map y * f.mk' x y = f.to_map x := f.to_localization_map.mk'_spec' _ _ theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := f.to_localization_map.eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := f.to_localization_map.mk'_eq_iff_eq_mul lemma mk'_surjective (z : S) : ∃ x (y : M), f.mk' x y = z := let ⟨r, hr⟩ := f.surj z in ⟨r.1, r.2, (f.eq_mk'_iff_mul_eq.2 hr).symm⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := f.to_localization_map.mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : f.mk' x y ∈ I ↔ f.to_map x ∈ I := begin split; intro h, { rw [← mk'_spec f x y, mul_comm], exact I.smul_mem (f.to_map y) h }, { rw ← mk'_spec f x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units f y), have := I.smul_mem b h, rwa [smul_eq_mul, mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := f.to_localization_map.eq lemma eq_iff_eq (g : localization_map M P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.to_localization_map.eq_iff_eq g.to_localization_map lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.to_localization_map.mk'_eq_of_eq H @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : f.mk' x ⟨x, hx⟩ = 1 := f.to_localization_map.mk'_self _ hx @[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 := f.to_localization_map.mk'_self' _ lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 := f.mk'_self' lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : f.to_map x * f.mk' y z = f.mk' (x * y) z := f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : f.mk' x y = f.to_map x * f.mk' 1 y := (f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : f.mk' (y * x) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : f.mk' (x * y) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : f.mk' x y * f.mk' y x = 1 := by rw [←f.mk'_mul, mul_comm]; exact f.mk'_self _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : f.mk' x y * f.mk' y ⟨x, h⟩ = 1 := f.mk'_mul_mk'_eq_one ⟨x, h⟩ _ lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp f.to_map y) := f.to_localization_map.is_unit_comp j.to_monoid_hom _ /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ := f.mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg) $ begin intros x y, rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), repeat {rw ←g.map_mul}, rw [←g.map_sub, ←g.map_mul], apply f.eq_of_eq hg, erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub], simp only [f.to_map.map_mul, sec_spec'], ring_exp, end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := f.to_localization_map.lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := f.to_localization_map.lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : f.lift hg (f.to_map x) = g x := f.to_localization_map.lift_eq _ _ lemma lift_eq_iff {x y : R × M} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := f.to_localization_map.lift_eq_iff _ @[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : f.lift (f.is_unit_comp j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom lemma epic_of_localization_map {j k : S →+* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h lemma lift_unique {j : S →+* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : f.lift f.map_units x = x := f.to_localization_map.lift_id _ /-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`, the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P` induced by `k`. -/ @[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) : k.lift f.map_units (f.lift k.map_units z) = z := f.to_localization_map.lift_left_inverse _ lemma lift_surjective_iff : surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := f.to_localization_map.lift_surjective_iff hg lemma lift_injective_iff : injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := f.to_localization_map.lift_injective_iff hg variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) /-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have `g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M` and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map : S →+* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ lemma map_mk' (x) (y : M) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ @[simp] lemma map_id (z : S) : f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z := f.lift_id _ /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ _ _ _ j.to_localization_map l.to_monoid_hom hl /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl /-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := (f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $ (@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom) (λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add @[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H x = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (f.ring_equiv_of_ring_equiv k j H).to_monoid_hom = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) := f.to_localization_map.mul_equiv_of_mul_equiv_eq H _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) : f.ring_equiv_of_ring_equiv k j H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _ section away_map variables (x : R) /-- Given `x : R`, the type of homomorphisms `f : R →* S` such that `S` is isomorphic to the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away_map (S' : Type*) [comm_ring S'] := localization_map (submonoid.powers x) S' variables (F : away_map x S) /-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def away_map.inv_self : S := F.mk' 1 ⟨x, submonoid.mem_powers _⟩ /-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_ring`s `g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending `z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def away_map.lift (hg : is_unit (g x)) : S →+* P := localization_map.lift F $ λ y, show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : R` and localization maps `F : R →+* S, G : R →+* P` away from `x` and `x * y` respectively, the homomorphism induced from `S` to `P`. -/ noncomputable def away_to_away_right (y : R) (G : away_map (x * y) P) : S →* P := F.lift x $ show is_unit (G.to_map x), from is_unit_of_mul_eq_one (G.to_map x) (G.mk' y ⟨x * y, submonoid.mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] end away_map end localization_map namespace localization variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, add_left_neg := λ y, quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } variables (M) /-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of `(x, 1)` in the localization of `R` at a submonoid. -/ def of : localization_map M (localization M) := (localization.monoid_of M).to_ring_localization $ λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm] variables {M} lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : mk = (of M).mk' := mk_eq_monoid_of_mk' variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def ring_equiv_of_quotient : localization M ≃+* S := (mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $ ((of M).lift f.map_units).map_add variables {f} @[simp] lemma ring_equiv_of_quotient_apply (x) : ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl @[simp] lemma ring_equiv_of_quotient_mk' (x y) : ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y := mul_equiv_of_quotient_mk' _ _ lemma ring_equiv_of_quotient_mk (x y) : ring_equiv_of_quotient f (mk x y) = f.mk' x y := mul_equiv_of_quotient_mk _ _ @[simp] lemma ring_equiv_of_quotient_of (x) : ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x := mul_equiv_of_quotient_monoid_of _ @[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y := mul_equiv_of_quotient_symm_mk' _ _ lemma ring_equiv_of_quotient_symm_mk (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y := mul_equiv_of_quotient_symm_mk _ _ @[simp] lemma ring_equiv_of_quotient_symm_of (x) : (ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x := mul_equiv_of_quotient_symm_monoid_of _ section away variables (x : R) /-- Given `x : R`, the natural hom sending `y : R`, `R` a `comm_ring`, to the equivalence class of `(y, 1)` in the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away.of : localization_map.away_map x (away x) := of (submonoid.powers x) @[simp] lemma away.mk_eq_mk' : mk = (away.of x).mk' := mk_eq_mk' /-- Given `x : R` and a localization map `f : R →+* S` away from `x`, we get an isomorphism between the localization of `R` at the submonoid generated by `x` as a quotient type and `S`. -/ noncomputable def away.ring_equiv_of_quotient (f : localization_map.away_map x S) : away x ≃+* S := ring_equiv_of_quotient f end away end localization variables {M} section at_prime variables (I : ideal R) [hp : I.is_prime] include hp namespace ideal /-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/ def prime_compl : submonoid R := { carrier := (Iᶜ : set R), one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl, mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } end ideal namespace localization_map variables (S) /-- A localization map from `R` to `S` where the submonoid is the complement of a prime ideal of `R`. -/ @[reducible] def at_prime := localization_map I.prime_compl S end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal, as a quotient type. -/ @[reducible] def at_prime := localization I.prime_compl end localization namespace localization_map variables {I} /-- When `f` is a localization map from `R` at the complement of a prime ideal `I`, we use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `local_ring` instance on `S` can 'know' the map needed to induce the instance. -/ instance at_prime.local_ring (f : at_prime S I) : local_ring f.codomain := local_of_nonunits_ideal (λ hze, begin rw [←f.to_map.map_one, ←f.to_map.map_zero] at hze, obtain ⟨t, ht⟩ := f.eq_iff_exists.1 hze, exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm, htz.symm ▸ I.zero_mem)) end) (begin intros x y hx hy hu, cases is_unit_iff_exists_inv.1 hu with z hxyz, have : ∀ {r s}, f.mk' r s ∈ nonunits S → r ∈ I, from λ r s, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨f.mk' s ⟨r, nr⟩, f.mk'_mul_mk'_eq_one' _ _ nr⟩), rcases f.mk'_surjective x with ⟨rx, sx, hrx⟩, rcases f.mk'_surjective y with ⟨ry, sy, hry⟩, rcases f.mk'_surjective z with ⟨rz, sz, hrz⟩, rw [←hrx, ←hry, ←hrz, ←f.mk'_add, ←f.mk'_mul, ←f.mk'_self I.prime_compl.one_mem] at hxyz, rw ←hrx at hx, rw ←hry at hy, cases f.eq.1 hxyz with t ht, simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht, rw [←sub_eq_zero, ←sub_mul] at ht, have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2, rw sub_eq_add_neg at hr, have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr), { exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)}, { exact I.mul_mem_right (I.add_mem (I.mul_mem_right (this hx)) (I.mul_mem_right (this hy)))} end) end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal is a local ring. -/ instance at_prime.local_ring : local_ring (localization I.prime_compl) := localization_map.at_prime.local_ring (of I.prime_compl) end localization end at_prime namespace localization_map variables (f : localization_map M S) section ideals /-- Explicit characterization of the ideal given by `ideal.map f.to_map I`. In practice, this ideal differs only in that the carrier set is defined explicitly. This definition is only meant to be used in proving `mem_map_to_map_iff`, and any proof that needs to refer to the explicit carrier set should use that theorem. -/ private def to_map_ideal (I : ideal R) : ideal S := { carrier := { z : S | ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1}, zero_mem' := ⟨⟨0, 1⟩, by simp⟩, add_mem' := begin rintros a b ⟨a', ha⟩ ⟨b', hb⟩, use ⟨a'.2 * b'.1 + b'.2 * a'.1, I.add_mem (I.smul_mem _ b'.1.2) (I.smul_mem _ a'.1.2)⟩, use a'.2 * b'.2, simp only [ring_hom.map_add, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], rw [add_mul, ← mul_assoc a, ha, mul_comm (f.to_map a'.2) (f.to_map b'.2), ← mul_assoc b, hb], ring end, smul_mem' := begin rintros c x ⟨x', hx⟩, obtain ⟨c', hc⟩ := localization_map.surj f c, use ⟨c'.1 * x'.1, I.smul_mem c'.1 x'.1.2⟩, use c'.2 * x'.2, simp only [←hx, ←hc, smul_eq_mul, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], ring end } theorem mem_map_to_map_iff {I : ideal R} {z} : z ∈ ideal.map f.to_map I ↔ ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1 := begin split, { show _ → z ∈ to_map_ideal f I, refine λ h, ideal.mem_Inf.1 h (λ z hz, _), obtain ⟨y, hy⟩ := hz, use ⟨⟨⟨y, hy.left⟩, 1⟩, by simp [hy.right]⟩ }, { rintros ⟨⟨a, s⟩, h⟩, rw [← ideal.unit_mul_mem_iff_mem _ (map_units f s), mul_comm], exact h.symm ▸ ideal.mem_map_of_mem a.2 } end theorem map_comap (J : ideal S) : ideal.map f.to_map (ideal.comap f.to_map J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ, begin obtain ⟨r, s, hx⟩ := f.mk'_surjective x, rw ←hx at ⊢ hJ, exact ideal.mul_mem_right _ (ideal.mem_map_of_mem (show f.to_map r ∈ J, from f.mk'_spec r s ▸ @ideal.mul_mem_right _ _ J (f.mk' r s) (f.to_map s) hJ)), end theorem comap_map_of_is_prime_disjoint (I : ideal R) (hI : I.is_prime) (hM : disjoint (M : set R) I) : ideal.comap f.to_map (ideal.map f.to_map I) = I := begin refine le_antisymm (λ a ha, _) ideal.le_comap_map, rw [ideal.mem_comap, mem_map_to_map_iff] at ha, obtain ⟨⟨b, s⟩, h⟩ := ha, have : f.to_map (a * ↑s - b) = 0 := by simpa [sub_eq_zero] using h, rw [← f.to_map.map_zero, eq_iff_exists] at this, obtain ⟨c, hc⟩ := this, have : a * s ∈ I, { rw zero_mul at hc, let this : (a * ↑s - ↑b) * ↑c ∈ I := hc.symm ▸ I.zero_mem, cases hI.right this with h1 h2, { simpa using I.add_mem h1 b.2 }, { exfalso, refine hM ⟨c.2, h2⟩ } }, cases hI.right this with h1 h2, { exact h1 }, { exfalso, refine hM ⟨s.2, h2⟩ } end /-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is embedded in the ordering of ideals of `R`. -/ def order_embedding : ideal S ↪o ideal R := { to_fun := λ J, ideal.comap f.to_map J, inj' := function.left_inverse.injective f.map_comap, map_rel_iff' := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, f.map_comap J₁ ▸ f.map_comap J₂ ▸ ideal.map_mono hJ⟩ } /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its comap, see `le_rel_iso_of_prime` for the more general relation isomorphism -/ lemma is_prime_iff_is_prime_disjoint (J : ideal S) : J.is_prime ↔ (ideal.comap f.to_map J).is_prime ∧ disjoint (M : set R) ↑(ideal.comap f.to_map J) := begin split, { refine λ h, ⟨⟨_, _⟩, λ m hm, h.1 (ideal.eq_top_of_is_unit_mem _ hm.2 (map_units f ⟨m, hm.left⟩))⟩, { refine λ hJ, h.left _, rw [eq_top_iff, (order_embedding f).map_rel_iff], exact le_of_eq hJ.symm }, { intros x y hxy, rw [ideal.mem_comap, ring_hom.map_mul] at hxy, exact h.right hxy } }, { refine λ h, ⟨λ hJ, h.left.left (eq_top_iff.2 _), _⟩, { rwa [eq_top_iff, (order_embedding f).map_rel_iff] at hJ }, { intros x y hxy, obtain ⟨a, s, ha⟩ := mk'_surjective f x, obtain ⟨b, t, hb⟩ := mk'_surjective f y, have : f.mk' (a * b) (s * t) ∈ J := by rwa [mk'_mul, ha, hb], rw [mk'_mem_iff, ← ideal.mem_comap] at this, replace this := h.left.right this, rw [ideal.mem_comap, ideal.mem_comap] at this, rwa [← ha, ← hb, mk'_mem_iff, mk'_mem_iff] } } end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its map, see `le_rel_iso_of_prime` for the more general relation isomorphism, and the reverse implication -/ lemma is_prime_of_is_prime_disjoint (I : ideal R) (hp : I.is_prime) (hd : disjoint (M : set R) ↑I) : (ideal.map f.to_map I).is_prime := begin rw [is_prime_iff_is_prime_disjoint f, comap_map_of_is_prime_disjoint f I hp hd], exact ⟨hp, hd⟩ end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M` -/ def order_iso_of_prime (f : localization_map M S) : {p : ideal S // p.is_prime} ≃o {p : ideal R // p.is_prime ∧ disjoint (M : set R) ↑p} := { to_fun := λ p, ⟨ideal.comap f.to_map p.1, (is_prime_iff_is_prime_disjoint f p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map f.to_map p.1, is_prime_of_is_prime_disjoint f p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap f J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint f I.1 I.2.1 I.2.2), map_rel_iff' := λ I I', ⟨λ h x hx, h hx, λ h, (show I.val ≤ I'.val, from (map_comap f I.val) ▸ (map_comap f I'.val) ▸ (ideal.map_mono h))⟩ } /-- `quotient_map` applied to maximal ideals of a localization is `surjective`. The quotient by a maximal ideal is a field, so inverses to elements already exist, and the localization necessarily maps the equivalence class of the inverse in the localization -/ lemma surjective_quotient_map_of_maximal_of_localization {f : localization_map M S} {I : ideal S} [I.is_prime] {J : ideal R} {H : J ≤ I.comap f.to_map} (hI : (I.comap f.to_map).is_maximal) : function.surjective (I.quotient_map f.to_map H) := begin intro s, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective s, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := f.mk'_surjective s, by_cases hM : (ideal.quotient.mk (I.comap f.to_map)) m = 0, { have : I = ⊤, { rw ideal.eq_top_iff_one, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_comap] at hM, convert I.smul_mem (f.mk' 1 ⟨m, hm⟩) hM, rw [smul_eq_mul, mul_comm, ← f.mk'_eq_mul_mk'_one, f.mk'_self] }, exact ⟨0, eq_comm.1 (by simp [ideal.quotient.eq_zero_iff_mem, this])⟩ }, { rw ideal.quotient.maximal_ideal_iff_is_field_quotient at hI, obtain ⟨n, hn⟩ := hI.3 hM, obtain ⟨rn, rfl⟩ := ideal.quotient.mk_surjective n, refine ⟨(ideal.quotient.mk J) (r * rn), _⟩, -- The rest of the proof is essentially just algebraic manipulations to prove the equality rw ← ring_hom.map_mul at hn, replace hn := congr_arg (ideal.quotient_map I f.to_map le_rfl) hn, simp only [ring_hom.map_one, ideal.quotient_map_mk, ring_hom.map_mul] at hn, rw [ideal.quotient_map_mk, ← sub_eq_zero_iff_eq, ← ring_hom.map_sub, ideal.quotient.eq_zero_iff_mem, ← ideal.quotient.eq_zero_iff_mem, ring_hom.map_sub, sub_eq_zero_iff_eq, localization_map.mk'_eq_mul_mk'_one], simp only [mul_eq_mul_left_iff, ring_hom.map_mul], exact or.inl (mul_left_cancel' (λ hn, hM (ideal.quotient.eq_zero_iff_mem.2 (ideal.mem_comap.2 (ideal.quotient.eq_zero_iff_mem.1 hn)))) (trans hn (by rw [← ring_hom.map_mul, ← f.mk'_eq_mul_mk'_one, f.mk'_self, ring_hom.map_one]))) } end end ideals /-! ### `algebra` section Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map `f` needed to induce the `R`-algebra structure. -/ /-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ instance algebra : algebra R f.codomain := f.to_map.to_algebra end localization_map namespace localization instance : algebra R (localization M) := localization_map.algebra (of M) end localization namespace localization_map variables (f : localization_map M S) @[simp] lemma of_id (a : R) : (algebra.of_id R f.codomain) a = f.to_map a := rfl @[simp] lemma algebra_map_eq : algebra_map R f.codomain = f.to_map := rfl variables (f) /-- Localization map `f` from `R` to `S` as an `R`-linear map. -/ def lin_coe : R →ₗ[R] f.codomain := { to_fun := f.to_map, map_add' := f.to_map.map_add, map_smul' := f.to_map.map_mul } /-- Map from ideals of `R` to submodules of `S` induced by `f`. -/ -- This was previously a `has_coe` instance, but if `f.codomain = R` then this will loop. -- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down -- the rest of the library. def coe_submodule (I : ideal R) : submodule R f.codomain := submodule.map f.lin_coe I variables {f} lemma mem_coe_submodule (I : ideal R) {x : S} : x ∈ f.coe_submodule I ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x := iff.rfl @[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl variables {g : R →+* P} variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) lemma map_smul (x : f.codomain) (z : R) : f.map hy k (z • x : f.codomain) = @has_scalar.smul P k.codomain _ (g z) (f.map hy k x) := show f.map hy k (f.to_map z * x) = k.to_map (g z) * f.map hy k x, by rw [ring_hom.map_mul, map_eq] lemma is_noetherian_ring (h : is_noetherian_ring R) : is_noetherian_ring f.codomain := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at h ⊢, exact order_embedding.well_founded (f.order_embedding.dual) h end end localization_map namespace localization variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an `R`-preserving isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def alg_equiv_of_quotient : localization M ≃ₐ[R] f.codomain := { commutes' := ring_equiv_of_quotient_of, ..ring_equiv_of_quotient f } lemma alg_equiv_of_quotient_apply (x : localization M) : alg_equiv_of_quotient f x = ring_equiv_of_quotient f x := rfl lemma alg_equiv_of_quotient_symm_apply (x : f.codomain) : (alg_equiv_of_quotient f).symm x = (ring_equiv_of_quotient f).symm x := rfl end localization namespace localization_map section integer_normalization variables {f : localization_map M S} open finsupp polynomial open_locale classical /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : polynomial f.codomain) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_mem_support (p : polynomial f.codomain) (i : ℕ) (h : coeff_integer_normalization p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization (f : localization_map M S) : polynomial f.codomain → polynomial R := λ p, on_finset p.support (coeff_integer_normalization p) (coeff_integer_normalization_mem_support p) @[simp] lemma integer_normalization_coeff (p : polynomial f.codomain) (i : ℕ) : (f.integer_normalization p).coeff i = coeff_integer_normalization p i := rfl lemma integer_normalization_spec (p : polynomial f.codomain) : ∃ (b : M), ∀ i, f.to_map ((f.integer_normalization p).coeff i) = f.to_map b * p.coeff i := begin use classical.some (f.exist_integer_multiples_of_finset (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (_root_.mul_zero (f.to_map _)).symm, { exact f.to_ring_hom.map_zero }, { exact finsupp.not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : polynomial f.codomain) : ∃ (b : M), (f.integer_normalization p).map f.to_map = f.to_map b • p := let ⟨b, hb⟩ := integer_normalization_spec p in ⟨b, polynomial.ext (λ i, by { rw coeff_map, exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : f.codomain →+* R') (p : polynomial f.codomain) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp f.to_map) x (f.integer_normalization p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map p in trans (eval₂_map f.to_map g x).symm (by rw [hb, eval₂_smul, hx, smul_zero]) lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra f.codomain R'] [is_scalar_tower R f.codomain R'] (p : polynomial f.codomain) {x : R'} (hx : aeval x p = 0) : aeval x (f.integer_normalization p) = 0 := by rw [aeval_def, is_scalar_tower.algebra_map_eq R f.codomain R', algebra_map_eq, integer_normalization_eval₂_eq_zero _ _ hx] end integer_normalization variables {R} {A K : Type*} [integral_domain A] lemma to_map_eq_zero_iff (f : localization_map M S) {x : R} (hM : M ≤ non_zero_divisors R) : f.to_map x = 0 ↔ x = 0 := begin rw ← f.to_map.map_zero, split; intro h, { cases f.eq_iff_exists.mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end lemma injective (f : localization_map M S) (hM : M ≤ non_zero_divisors R) : injective f.to_map := begin rw ring_hom.injective_iff f.to_map, intros a ha, rw [← f.to_map.map_zero, f.eq_iff_exists] at ha, cases ha with c hc, rw zero_mul at hc, exact hM c.2 a hc, end protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] (f : localization_map M S) (hM : M ≤ non_zero_divisors R) (x : non_zero_divisors R) : f.to_map x ≠ 0 := map_ne_zero_of_mem_non_zero_divisors (f.injective hM) /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. -/ def integral_domain_of_le_non_zero_divisors {M : submonoid A} (f : localization_map M S) (hM : M ≤ non_zero_divisors A) : integral_domain S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases f.surj z with x hx, cases f.surj w with y hy, have : z * w * f.to_map y.2 * f.to_map x.2 = f.to_map x.1 * f.to_map y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, rw [h, zero_mul, zero_mul, ← f.to_map.map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff f hM).mp this.symm) with H H, { exact or.inl (f.eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (f.eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨f.to_map 0, f.to_map 1, λ h, zero_ne_one (f.injective hM h)⟩, ..(infer_instance : comm_ring S) } /-- The localization at of an integral domain to a set of non-zero elements is an integral domain -/ def integral_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : integral_domain (localization M) := (localization.of M).integral_domain_of_le_non_zero_divisors hM /-- The localization of an integral domain at the complement of a prime ideal is an integral domain. -/ instance integral_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) : integral_domain (localization.at_prime P) := integral_domain_localization (le_non_zero_divisors_of_domain (by simpa only [] using P.zero_mem)) end localization_map section at_prime namespace localization local attribute [instance] classical.prop_decidable /-- The image of `P` in the localization at `P.prime_compl` is a maximal ideal, and in particular it is the unique maximal ideal given by the local ring structure `at_prime.local_ring` -/ lemma at_prime.map_eq_maximal_ideal {P : ideal R} [hP : ideal.is_prime P] : ideal.map (localization.of P.prime_compl).to_map P = (local_ring.maximal_ideal (localization P.prime_compl)) := begin let f := localization.of P.prime_compl, ext x, split; simp only [local_ring.mem_maximal_ideal, mem_nonunits_iff]; intro hx, { exact λ h, (localization_map.is_prime_of_is_prime_disjoint f P hP disjoint_compl_left).1 (ideal.eq_top_of_is_unit_mem _ hx h) }, { obtain ⟨⟨a, b⟩, hab⟩ := localization_map.surj f x, contrapose! hx, rw is_unit_iff_exists_inv, rw localization_map.mem_map_to_map_iff at hx, obtain ⟨a', ha'⟩ := is_unit_iff_exists_inv.1 (localization_map.map_units f ⟨a, λ ha, hx ⟨⟨⟨a, ha⟩, b⟩, hab⟩⟩), exact ⟨f.to_map b * a', by rwa [← mul_assoc, hab]⟩ } end /-- The unique maximal ideal of the localization at `P.prime_compl` lies over the ideal `P`. -/ lemma at_prime.comap_maximal_ideal {P : ideal R} [ideal.is_prime P] : ideal.comap (localization.of P.prime_compl).to_map (local_ring.maximal_ideal (localization P.prime_compl)) = P := begin let Pₚ := local_ring.maximal_ideal (localization P.prime_compl), refine le_antisymm (λ x hx, _) (le_trans ideal.le_comap_map (ideal.comap_mono (le_of_eq at_prime.map_eq_maximal_ideal))), by_cases h0 : x = 0, { exact h0.symm ▸ P.zero_mem }, { have : Pₚ.is_prime := ideal.is_maximal.is_prime (local_ring.maximal_ideal.is_maximal _), rw localization_map.is_prime_iff_is_prime_disjoint (localization.of P.prime_compl) at this, contrapose! h0 with hx', simpa using this.2 ⟨hx', hx⟩ } end end localization end at_prime /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma localization_map_bijective_of_field {R Rₘ : Type*} [integral_domain R] [comm_ring Rₘ] {M : submonoid R} (hM : (0 : R) ∉ M) (hR : is_field R) (f : localization_map M Rₘ) : function.bijective f.to_map := begin refine ⟨f.injective (le_non_zero_divisors_of_domain hM), λ x, _⟩, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := f.mk'_surjective x, obtain ⟨n, hn⟩ := hR.mul_inv_cancel (λ hm0, hM (hm0 ▸ hm) : m ≠ 0), exact ⟨r * n, by erw [f.eq_mk'_iff_mul_eq, ← f.to_map.map_mul, mul_assoc, mul_comm n, hn, mul_one]⟩ end variables (R) {A : Type*} [integral_domain A] variables (K : Type*) /-- Localization map from an integral domain `R` to its field of fractions. -/ @[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K namespace fraction_map open localization_map variables {R K} lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} : φ.to_map x = 0 ↔ x = 0 := φ.to_map_eq_zero_iff (le_of_eq rfl) protected theorem injective [comm_ring K] (φ : fraction_map R K) : function.injective φ.to_map := φ.injective (le_of_eq rfl) protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] [comm_ring K] (φ : fraction_map R K) (x : non_zero_divisors R) : φ.to_map x ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (le_of_eq rfl) x /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K := φ.integral_domain_of_le_non_zero_divisors (le_of_eq rfl) local attribute [instance] classical.dec_eq /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K := if h : z = 0 then 0 else φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩ protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) : x * φ.inv x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K := { inv := φ.inv, mul_inv_cancel := φ.mul_inv_cancel, inv_zero := dif_pos rfl, ..φ.to_integral_domain } variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] (f : fraction_map A K) {g : A →+* L} lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s := f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _ (f.to_map_ne_zero_of_mem_non_zero_divisors _)).symm lemma is_unit_map_of_injective (hg : function.injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := f.lift $ is_unit_map_of_injective hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x y) : f.lift hg (f.mk' x y) = g x / g y := begin erw f.lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm, end /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) : K →+* L := f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $ map_ne_zero_of_mem_non_zero_divisors hj) g /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) : K ≃+* L := f.ring_equiv_of_ring_equiv g h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end /-- The cast from `int` to `rat` as a `fraction_map`. -/ def int.fraction_map : fraction_map ℤ ℚ := { to_fun := coe, map_units' := begin rintro ⟨x, hx⟩, rw mem_non_zero_divisors_iff_ne_zero at hx, simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj' := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists' := begin intros x y, rw [int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa mem_non_zero_divisors_iff_ne_zero at hc, end, ..int.cast_ring_hom ℚ } lemma integer_normalization_eq_zero_iff {p : polynomial f.codomain} : f.integer_normalization p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec p, split; intros h i, { apply f.to_map_eq_zero_iff.mp, rw [hb i, h i], exact _root_.mul_zero _ }, { have hi := h i, rw [polynomial.coeff_zero, ← f.to_map_eq_zero_iff, hb i] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact f.to_map_eq_zero_iff.mp h } end /-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] : algebra.is_algebraic A L ↔ algebra.is_algebraic f.codomain L := begin split; intros h x; obtain ⟨p, hp, px⟩ := h x, { refine ⟨p.map f.to_map, λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : f.to_map (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact f.to_map_eq_zero_iff.mp this }, { rwa [is_scalar_tower.aeval_apply _ f.codomain, algebra_map_eq] at px } }, { exact ⟨f.integer_normalization p, mt f.integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero p px⟩ }, end section num_denom variables [unique_factorization_monoid A] (φ : fraction_map A K) lemma exists_reduced_fraction (x : φ.codomain) : ∃ (a : A) (b : non_zero_divisors A), (∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ φ.mk' a b = x := begin obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := φ.exists_integer_multiple x, obtain ⟨a', b', c', no_factor, rfl, rfl⟩ := unique_factorization_monoid.exists_reduced_factors' a b (mem_non_zero_divisors_iff_ne_zero.mp b_nonzero), obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero, refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩, apply mul_left_cancel' (φ.to_map_ne_zero_of_mem_non_zero_divisors ⟨c' * b', b_nonzero⟩), simp only [subtype.coe_mk, φ.to_map.map_mul] at *, erw [←hab, mul_assoc, φ.mk'_spec' a' ⟨b', b'_nonzero⟩], end /-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/ noncomputable def num (x : φ.codomain) : A := classical.some (φ.exists_reduced_fraction x) /-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/ noncomputable def denom (x : φ.codomain) : non_zero_divisors A := classical.some (classical.some_spec (φ.exists_reduced_fraction x)) lemma num_denom_reduced (x : φ.codomain) : ∀ {d}, d ∣ φ.num x → d ∣ φ.denom x → is_unit d := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).1 @[simp] lemma mk'_num_denom (x : φ.codomain) : φ.mk' (φ.num x) (φ.denom x) = x := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).2 lemma num_mul_denom_eq_num_iff_eq {x y : φ.codomain} : x * φ.to_map (φ.denom y) = φ.to_map (φ.num y) ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_iff_eq' {x y : φ.codomain} : y * φ.to_map (φ.denom x) = φ.to_map (φ.num x) ↔ x = y := ⟨ λ h, by simpa only [eq_comm, mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : φ.codomain} : φ.num y * φ.denom x = φ.num x * φ.denom y ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.mk'_eq_of_eq h, λ h, by rw h ⟩ lemma eq_zero_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : x = 0 := φ.num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero]) lemma is_integer_of_is_unit_denom {x : φ.codomain} (h : is_unit (φ.denom x : A)) : φ.is_integer x := begin cases h with d hd, have d_ne_zero : φ.to_map (φ.denom x) ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (φ.denom x), use ↑d⁻¹ * φ.num x, refine trans _ (φ.mk'_num_denom x), rw [φ.to_map.map_mul, φ.to_map.map_units_inv, hd], apply mul_left_cancel' d_ne_zero, rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, φ.mk'_spec'] end lemma is_unit_denom_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : is_unit (φ.denom x : A) := φ.num_denom_reduced x (h.symm ▸ dvd_zero _) (dvd_refl _) end num_denom end fraction_map section algebra section is_integral variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] [algebra R S] /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps -/ noncomputable def localization_algebra (M : submonoid R) (f : localization_map M Rₘ) (g : localization_map (algebra.algebra_map_submonoid S M) Sₘ) : algebra Rₘ Sₘ := (f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).to_algebra variables (f : localization_map M Rₘ) variables (g : localization_map (algebra.algebra_map_submonoid S M) Sₘ) lemma algebra_map_mk' (r : R) (m : M) : (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) (f.mk' r m) = g.mk' (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ := localization_map.map_mk' f _ r m /-- Injectivity of a map descends to the map induced on localizations. -/ lemma map_injective_of_injective {R S : Type*} [comm_ring R] [comm_ring S] (ϕ : R →+* S) (hϕ : function.injective ϕ) (M : submonoid R) (f : localization_map M Rₘ) (g : localization_map (M.map ϕ : submonoid S) Sₘ) (hM : (M.map ϕ : submonoid S) ≤ non_zero_divisors S) : function.injective (f.map (M.mem_map_of_mem (ϕ : R →* S)) g) := begin rintros x y hxy, obtain ⟨a, b, rfl⟩ := localization_map.mk'_surjective f x, obtain ⟨c, d, rfl⟩ := localization_map.mk'_surjective f y, rw [localization_map.map_mk' f _ a b, localization_map.map_mk' f _ c d, localization_map.mk'_eq_iff_eq] at hxy, refine (localization_map.mk'_eq_iff_eq f).2 (congr_arg f.to_map (hϕ _)), convert g.injective hM hxy; simp, end /-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization. -/ lemma localization_algebra_injective (hRS : function.injective (algebra_map R S)) (hM : algebra.algebra_map_submonoid S M ≤ non_zero_divisors S) : function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) := map_injective_of_injective (algebra_map R S) hRS M f g hM open polynomial lemma ring_hom.is_integral_elem_localization_at_leading_coeff {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (x : S) (p : polynomial R) (hf : p.eval₂ f x = 0) (M : submonoid R) (hM : p.leading_coeff ∈ M) {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] (ϕ : localization_map M Rₘ) (ϕ' : localization_map (M.map ↑f : submonoid S) Sₘ) : (ϕ.map (M.mem_map_of_mem (f : R →* S)) ϕ').is_integral_elem (ϕ'.to_map x) := begin by_cases triv : (1 : Rₘ) = 0, { exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ }, haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp (localization_map.map_units ϕ ⟨p.leading_coeff, hM⟩), refine ⟨(p.map ϕ.to_map) * C b, ⟨_, _⟩⟩, { refine monic_mul_C_of_leading_coeff_mul_eq_one _, rwa leading_coeff_map_of_leading_coeff_ne_zero ϕ.to_map, refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) }, { refine eval₂_mul_eq_zero_of_left _ _ _ _, erw [eval₂_map, localization_map.map_comp, ← hom_eval₂ _ f ϕ'.to_map x], exact trans (congr_arg ϕ'.to_map hf) ϕ'.to_map.map_zero } end /-- Given a particular witness to an element being algebraic over an algebra `R → S`, We can localize to a submonoid containing the leading coefficient to make it integral. Explicitly, the map between the localizations will be an integral ring morphism -/ theorem is_integral_localization_at_leading_coeff {x : S} (p : polynomial R) (hp : aeval x p = 0) (hM : p.leading_coeff ∈ M) : (f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).is_integral_elem (g.to_map x) := (algebra_map R S).is_integral_elem_localization_at_leading_coeff x p hp M hM f g /-- If `R → S` is an integral extension, `M` is a submonoid of `R`, `Rₘ` is the localization of `R` at `M`, and `Sₘ` is the localization of `S` at the image of `M` under the extension map, then the induced map `Rₘ → Sₘ` is also an integral extension -/ theorem is_integral_localization (H : algebra.is_integral R S) : (f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).is_integral := begin intro x, by_cases triv : (1 : R) = 0, { have : (1 : Rₘ) = 0 := by convert congr_arg f.to_map triv; simp, exact ⟨0, ⟨trans leading_coeff_zero this.symm, eval₂_zero _ _⟩⟩ }, { haveI : nontrivial R := nontrivial_of_ne 1 0 triv, obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := g.surj x, obtain ⟨v, hv⟩ := hu, obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (f.map_units ⟨v, hv.1⟩), refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _ (localization_algebra M f g) x (g.to_map u) v' _ _, { replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) hv', rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ f.to_map] at hv', erw localization_map.map_comp at hv', exact hv.2 ▸ hv' }, { obtain ⟨p, hp⟩ := H s, exact hx.symm ▸ is_integral_localization_at_leading_coeff f g p hp.2 (hp.1.symm ▸ M.one_mem) } } end lemma is_integral_localization' {R S : Type*} [comm_ring R] [comm_ring S] {f : R →+* S} (hf : f.is_integral) (M : submonoid R) : ((localization.of M).map (M.mem_map_of_mem (f : R →* S)) (localization.of (M.map ↑f))).is_integral := @is_integral_localization R _ M S _ _ _ _ _ f.to_algebra _ _ hf end is_integral namespace integral_closure variables {L : Type*} [field K] [field L] (f : fraction_map A K) open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : fraction_map (integral_closure A L) L := (algebra_map (integral_closure A L) L).to_localization_map (λ ⟨⟨y, integral⟩, nonzero⟩, have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h), show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩) (λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩) (λ x y, ⟨ λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc) ⟩) variables {K} (L) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_finite_extension [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] [finite_dimensional f.codomain L] : fraction_map (integral_closure A L) L := fraction_map_of_algebraic (f.comap_is_algebraic_iff.mpr is_algebraic_of_finite) (λ x hx, f.to_map_eq_zero_iff.mp ((algebra_map f.codomain L).map_eq_zero.mp $ (is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx)) end integral_closure end algebra variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) namespace fraction_ring /-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of `(x, 1)` in the field of fractions of `A`. -/ def of : fraction_map A (localization (non_zero_divisors A)) := localization.of (non_zero_divisors A) variables {A} noncomputable instance : field (fraction_ring A) := (of A).to_field @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = ((of A).to_map r / (of A).to_map s : fraction_ring A) := by erw [localization.mk_eq_mk', (of A).mk'_eq_div] /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an `A`-isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def alg_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) : fraction_ring A ≃ₐ[A] f.codomain := localization.alg_equiv_of_quotient f instance : algebra A (fraction_ring A) := (of A).to_map.to_algebra end fraction_ring
3d827110f2979462e51a349c8adb7ee62d4392bb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/localization/basic.lean
06c272a17bd50b077a1299ac689e481caf752aa1
[ "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
48,543
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import algebra.algebra.tower import algebra.ring.equiv import group_theory.monoid_localization import ring_theory.ideal.basic import ring_theory.non_zero_divisors import tactic.ring_exp /-! # Localizations of commutative rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. In the following, let `R, P` be commutative rings, `S, Q` be `R`- and `P`-algebras and `M, T` be submonoids of `R` and `P` respectively, e.g.: ``` variables (R S P Q : Type*) [comm_ring R] [comm_ring S] [comm_ring P] [comm_ring Q] variables [algebra R S] [algebra P Q] (M : submonoid R) (T : submonoid P) ``` ## Main definitions * `is_localization (M : submonoid R) (S : Type*)` is a typeclass expressing that `S` is a localization of `R` at `M`, i.e. the canonical map `algebra_map R S : R →+* S` is a localization map (satisfying the above properties). * `is_localization.mk' S` is a surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹` * `is_localization.lift` is the ring homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. * `is_localization.map S Q` is the ring homomorphism from `S` to `Q` which maps elements of `M` to elements of `T` * `is_localization.ring_equiv_of_ring_equiv`: if `R` and `P` are isomorphic by an isomorphism sending `M` to `T`, then `S` and `Q` are isomorphic * `is_localization.alg_equiv`: if `Q` is another localization of `R` at `M`, then `S` and `Q` are isomorphic as `R`-algebras ## Main results * `localization M S`, a construction of the localization as a quotient type, defined in `group_theory.monoid_localization`, has `comm_ring`, `algebra R` and `is_localization M` instances if `R` is a ring. `localization.away`, `localization.at_prime` and `fraction_ring` are abbreviations for `localization`s and have their corresponding `is_localization` instances ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A previous version of this file used a fully bundled type of ring localization maps, then used a type synonym `f.codomain` for `f : localization_map M S` to instantiate the `R`-algebra structure on `S`. This results in defining ad-hoc copies for everything already defined on `S`. By making `is_localization` a predicate on the `algebra_map R S`, we can ensure the localization map commutes nicely with other `algebra_map`s. To prove most lemmas about a localization map `algebra_map R S` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `is_localization.to_localization_map M S`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `algebra_map : R →+* localization M`. The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ open function open_locale big_operators section comm_semiring variables {R : Type*} [comm_semiring R] (M : submonoid R) (S : Type*) [comm_semiring S] variables [algebra R S] {P : Type*} [comm_semiring P] /-- The typeclass `is_localization (M : submodule R) S` where `S` is an `R`-algebra expresses that `S` is isomorphic to the localization of `R` at `M`. -/ class is_localization : Prop := (map_units [] : ∀ y : M, is_unit (algebra_map R S y)) (surj [] : ∀ z : S, ∃ x : R × M, z * algebra_map R S x.2 = algebra_map R S x.1) (eq_iff_exists [] : ∀ {x y}, algebra_map R S x = algebra_map R S y ↔ ∃ c : M, ↑c * x = ↑c * y) variables {M S} namespace is_localization section is_localization variables [is_localization M S] section variables (M) lemma of_le (N : submonoid R) (h₁ : M ≤ N) (h₂ : ∀ r ∈ N, is_unit (algebra_map R S r)) : is_localization N S := { map_units := λ r, h₂ r r.2, surj := λ s, by { obtain ⟨⟨x, y, hy⟩, H⟩ := is_localization.surj M s, exact ⟨⟨x, y, h₁ hy⟩, H⟩ }, eq_iff_exists := λ x y, begin split, { rw is_localization.eq_iff_exists M, rintro ⟨c, hc⟩, exact ⟨⟨c, h₁ c.2⟩, hc⟩ }, { rintro ⟨c, h⟩, simpa only [set_like.coe_mk, map_mul, (h₂ c c.2).mul_right_inj] using congr_arg (algebra_map R S) h } end } variables (S) /-- `is_localization.to_localization_with_zero_map M S` shows `S` is the monoid localization of `R` at `M`. -/ @[simps] def to_localization_with_zero_map : submonoid.localization_with_zero_map M S := { to_fun := algebra_map R S, map_units' := is_localization.map_units _, surj' := is_localization.surj _, eq_iff_exists' := λ _ _, is_localization.eq_iff_exists _ _, .. algebra_map R S } /-- `is_localization.to_localization_map M S` shows `S` is the monoid localization of `R` at `M`. -/ abbreviation to_localization_map : submonoid.localization_map M S := (to_localization_with_zero_map M S).to_localization_map @[simp] lemma to_localization_map_to_map : (to_localization_map M S).to_map = (algebra_map R S : R →*₀ S) := rfl lemma to_localization_map_to_map_apply (x) : (to_localization_map M S).to_map x = algebra_map R S x := rfl end variables (M) /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ noncomputable def sec (z : S) : R × M := classical.some $ is_localization.surj _ z @[simp] lemma to_localization_map_sec : (to_localization_map M S).sec = sec M := rfl /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec (z : S) : z * algebra_map R S (is_localization.sec M z).2 = algebra_map R S (is_localization.sec M z).1 := classical.some_spec $ is_localization.surj _ z /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' (z : S) : algebra_map R S (is_localization.sec M z).1 = algebra_map R S (is_localization.sec M z).2 * z := by rw [mul_comm, sec_spec] variables {R M} lemma map_right_cancel {x y} {c : M} (h : algebra_map R S (c * x) = algebra_map R S (c * y)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : algebra_map R S (x * c) = algebra_map R S (y * c)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * algebra_map R S y = algebra_map R S x) (hx : x = 0) : z = 0 := by { rw [hx, (algebra_map R S).map_zero] at h, exact (is_unit.mul_left_eq_zero (is_localization.map_units S y)).1 h} variables (M S) lemma map_eq_zero_iff (r : R) : algebra_map R S r = 0 ↔ ∃ m : M, ↑m * r = 0 := begin split, intro h, { obtain ⟨m, hm⟩ := (is_localization.eq_iff_exists M S).mp ((algebra_map R S).map_zero.trans h.symm), exact ⟨m, by simpa using hm.symm⟩ }, { rintro ⟨m, hm⟩, rw [← (is_localization.map_units S m).mul_right_inj, mul_zero, ← ring_hom.map_mul, hm, ring_hom.map_zero] } end variables {M} /-- `is_localization.mk' S` is the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (x : R) (y : M) : S := (to_localization_map M S).mk' x y @[simp] lemma mk'_sec (z : S) : mk' S (is_localization.sec M z).1 (is_localization.sec M z).2 = z := (to_localization_map M S).mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * x₂) (y₁ * y₂) = mk' S x₁ y₁ * mk' S x₂ y₂ := (to_localization_map M S).mk'_mul _ _ _ _ lemma mk'_one (x) : mk' S x (1 : M) = algebra_map R S x := (to_localization_map M S).mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : mk' S x y * algebra_map R S y = algebra_map R S x := (to_localization_map M S).mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : algebra_map R S y * mk' S x y = algebra_map R S x := (to_localization_map M S).mk'_spec' _ _ @[simp] lemma mk'_spec_mk (x) (y : R) (hy : y ∈ M) : mk' S x ⟨y, hy⟩ * algebra_map R S y = algebra_map R S x := mk'_spec S x ⟨y, hy⟩ @[simp] lemma mk'_spec'_mk (x) (y : R) (hy : y ∈ M) : algebra_map R S y * mk' S x ⟨y, hy⟩ = algebra_map R S x := mk'_spec' S x ⟨y, hy⟩ variables {S} theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = mk' S x y ↔ z * algebra_map R S y = algebra_map R S x := (to_localization_map M S).eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : mk' S x y = z ↔ algebra_map R S x = z * algebra_map R S y := (to_localization_map M S).mk'_eq_iff_eq_mul theorem mk'_add_eq_iff_add_mul_eq_mul {x} {y : M} {z₁ z₂} : mk' S x y + z₁ = z₂ ↔ algebra_map R S x + z₁ * algebra_map R S y = z₂ * algebra_map R S y := by rw [←mk'_spec S x y, ←is_unit.mul_left_inj (is_localization.map_units S y), right_distrib] variables (M) lemma mk'_surjective (z : S) : ∃ x (y : M), mk' S x y = z := let ⟨r, hr⟩ := is_localization.surj _ z in ⟨r.1, r.2, (eq_mk'_iff_mul_eq.2 hr).symm⟩ variables (S) include M /-- The localization of a `fintype` is a `fintype`. Cannot be an instance. -/ noncomputable def fintype' [fintype R] : fintype S := have _ := classical.prop_decidable, by exactI fintype.of_surjective (function.uncurry $ is_localization.mk' S) (λ a, prod.exists'.mpr $ is_localization.mk'_surjective M a) omit M variables {M S} /-- Localizing at a submonoid with 0 inside it leads to the trivial ring. -/ def unique_of_zero_mem (h : (0 : R) ∈ M) : unique S := unique_of_zero_eq_one $ by simpa using is_localization.map_units S ⟨0, h⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ algebra_map R S (y₂ * x₁) = algebra_map R S (y₁ * x₂) := (to_localization_map M S).mk'_eq_iff_eq lemma mk'_eq_iff_eq' {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ algebra_map R S (x₁ * y₂) = algebra_map R S (x₂ * y₁) := (to_localization_map M S).mk'_eq_iff_eq' lemma mk'_mem_iff {x} {y : M} {I : ideal S} : mk' S x y ∈ I ↔ algebra_map R S x ∈ I := begin split; intro h, { rw [← mk'_spec S x y, mul_comm], exact I.mul_mem_left ((algebra_map R S) y) h }, { rw ← mk'_spec S x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units S y), have := I.mul_mem_left b h, rwa [mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : mk' S a₁ a₂ = mk' S b₁ b₂ ↔ ∃ c : M, ↑c * (↑b₂ * a₁) = c * (a₂ * b₁) := (to_localization_map M S).eq lemma mk'_eq_zero_iff (x : R) (s : M) : mk' S x s = 0 ↔ ∃ (m : M), ↑m * x = 0 := by rw [← (map_units S s).mul_left_inj, mk'_spec, zero_mul, map_eq_zero_iff M] @[simp] lemma mk'_zero (s : M) : is_localization.mk' S 0 s = 0 := by rw [eq_comm, is_localization.eq_mk'_iff_mul_eq, zero_mul, map_zero] lemma ne_zero_of_mk'_ne_zero {x : R} {y : M} (hxy : is_localization.mk' S x y ≠ 0) : x ≠ 0 := begin rintro rfl, exact hxy (is_localization.mk'_zero _) end section ext variables [algebra R P] [is_localization M P] lemma eq_iff_eq {x y} : algebra_map R S x = algebra_map R S y ↔ algebra_map R P x = algebra_map R P y := (to_localization_map M S).eq_iff_eq (to_localization_map M P) lemma mk'_eq_iff_mk'_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ mk' P x₁ y₁ = mk' P x₂ y₂ := (to_localization_map M S).mk'_eq_iff_mk'_eq (to_localization_map M P) lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : ↑a₂ * b₁ = ↑b₂ * a₁) : mk' S a₁ a₂ = mk' S b₁ b₂ := (to_localization_map M S).mk'_eq_of_eq H lemma mk'_eq_of_eq' {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * ↑a₂ = a₁ * ↑b₂) : mk' S a₁ a₂ = mk' S b₁ b₂ := (to_localization_map M S).mk'_eq_of_eq' H variables (S) @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : mk' S x ⟨x, hx⟩ = 1 := (to_localization_map M S).mk'_self _ hx @[simp] lemma mk'_self' {x : M} : mk' S (x : R) x = 1 := (to_localization_map M S).mk'_self' _ lemma mk'_self'' {x : M} : mk' S x.1 x = 1 := mk'_self' _ end ext lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : (algebra_map R S) x * mk' S y z = mk' S (x * y) z := (to_localization_map M S).mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : mk' S x y = (algebra_map R S) x * mk' S 1 y := ((to_localization_map M S).mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : mk' S (y * x : R) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : mk' S (x * y) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : mk' S (x : R) y * mk' S (y : R) x = 1 := by rw [←mk'_mul, mul_comm]; exact mk'_self _ _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : mk' S x y * mk' S (y : R) ⟨x, h⟩ = 1 := mk'_mul_mk'_eq_one ⟨x, h⟩ _ section variables (M) lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp (algebra_map R S) y) := (to_localization_map M S).is_unit_comp j.to_monoid_hom _ end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : (algebra_map R S) x = (algebra_map R S) y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = mk' S x₁ y₁ + mk' S x₂ y₂ := mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul, mul_comm (_ * _), ←mul_assoc, add_comm, ←map_mul, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul], simp only [map_add, submonoid.coe_mul, map_mul], ring end lemma mul_add_inv_left {g : R →+* P} (h : ∀ y : M, is_unit (g y)) (y : M) (w z₁ z₂ : P) : w * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) h y)⁻¹ + z₁ = z₂ ↔ w + g y * z₁ = g y * z₂ := begin rw [mul_comm, ←one_mul z₁, ←units.inv_mul (is_unit.lift_right (g.to_monoid_hom.restrict M) h y), mul_assoc, ←mul_add, units.inv_mul_eq_iff_eq_mul, units.inv_mul_cancel_left, is_unit.coe_lift_right], simp only [ring_hom.to_monoid_hom_eq_coe, monoid_hom.restrict_apply, ring_hom.coe_monoid_hom] end lemma lift_spec_mul_add {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) (z w w' v) : ((to_localization_with_zero_map M S).lift g.to_monoid_with_zero_hom hg) z * w + w' = v ↔ g ((to_localization_map M S).sec z).1 * w + g ((to_localization_map M S).sec z).2 * w' = g ((to_localization_map M S).sec z).2 * v := begin show (_ * _) * _ + _ = _ ↔ _ = _, erw [mul_comm, ←mul_assoc, mul_add_inv_left hg, mul_comm], refl end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := { map_add' := begin intros x y, erw [(to_localization_map M S).lift_spec, mul_add, mul_comm, eq_comm, lift_spec_mul_add, add_comm, mul_comm,mul_assoc,mul_comm,mul_assoc, lift_spec_mul_add], simp_rw ←mul_assoc, show g _ * g _ * g _ + g _ * g _ * g _ = g _ * g _ * g _, simp_rw [←map_mul g, ←map_add g], apply @eq_of_eq _ _ _ S _ _ _ _ _ g hg, simp only [sec_spec', to_localization_map_sec, map_add, map_mul], ring end, .. @submonoid.localization_with_zero_map.lift _ _ _ _ _ _ _ (to_localization_with_zero_map M S) g.to_monoid_with_zero_hom hg } variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : lift hg (mk' S x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) hg y)⁻¹ := (to_localization_map M S).lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : lift hg (mk' S x y) = v ↔ g x = g y * v := (to_localization_map M S).lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : lift hg ((algebra_map R S) x) = g x := (to_localization_map M S).lift_eq _ _ lemma lift_eq_iff {x y : R × M} : lift hg (mk' S x.1 x.2) = lift hg (mk' S y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := (to_localization_map M S).lift_eq_iff _ @[simp] lemma lift_comp : (lift hg).comp (algebra_map R S) = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : lift (is_unit_comp M j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_of_comp j.to_monoid_hom variables (M) /-- See note [partially-applied ext lemmas] -/ lemma monoid_hom_ext ⦃j k : S →* P⦄ (h : j.comp (algebra_map R S : R →* S) = k.comp (algebra_map R S)) : j = k := submonoid.localization_map.epic_of_localization_map (to_localization_map M S) $ monoid_hom.congr_fun h /-- See note [partially-applied ext lemmas] -/ lemma ring_hom_ext ⦃j k : S →+* P⦄ (h : j.comp (algebra_map R S) = k.comp (algebra_map R S)) : j = k := ring_hom.coe_monoid_hom_injective $ monoid_hom_ext M $ monoid_hom.ext $ ring_hom.congr_fun h /- This is not an instance because the submonoid `M` would become a metavariable in typeclass search. -/ lemma alg_hom_subsingleton [algebra R P] : subsingleton (S →ₐ[R] P) := ⟨λ f g, alg_hom.coe_ring_hom_injective $ is_localization.ring_hom_ext M $ by rw [f.comp_algebra_map, g.comp_algebra_map]⟩ /-- To show `j` and `k` agree on the whole localization, it suffices to show they agree on the image of the base ring, if they preserve `1` and `*`. -/ protected lemma ext (j k : S → P) (hj1 : j 1 = 1) (hk1 : k 1 = 1) (hjm : ∀ a b, j (a * b) = j a * j b) (hkm : ∀ a b, k (a * b) = k a * k b) (h : ∀ a, j (algebra_map R S a) = k (algebra_map R S a)) : j = k := monoid_hom.mk.inj (monoid_hom_ext M $ monoid_hom.ext h : (⟨j, hj1, hjm⟩ : S →* P) = ⟨k, hk1, hkm⟩) variables {M} lemma lift_unique {j : S →+* P} (hj : ∀ x, j ((algebra_map R S) x) = g x) : lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : lift (map_units S : ∀ y : M, is_unit _) x = x := (to_localization_map M S).lift_id _ lemma lift_surjective_iff : surjective (lift hg : S → P) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := (to_localization_map M S).lift_surjective_iff hg lemma lift_injective_iff : injective (lift hg : S → P) ↔ ∀ x y, algebra_map R S x = algebra_map R S y ↔ g x = g y := (to_localization_map M S).lift_injective_iff hg section map variables {T : submonoid P} {Q : Type*} [comm_semiring Q] (hy : M ≤ T.comap g) variables [algebra P Q] [is_localization T Q] section variables (Q) /-- Map a homomorphism `g : R →+* P` to `S →+* Q`, where `S` and `Q` are localizations of `R` and `P` at `M` and `T` respectively, such that `g(M) ⊆ T`. We send `z : S` to `algebra_map P Q (g x) * (algebra_map P Q (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : R →+* P) (hy : M ≤ T.comap g) : S →+* Q := @lift R _ M _ _ _ _ _ _ ((algebra_map P Q).comp g) (λ y, map_units _ ⟨g y, hy y.2⟩) end lemma map_eq (x) : map Q g hy ((algebra_map R S) x) = algebra_map P Q (g x) := lift_eq (λ y, map_units _ ⟨g y, hy y.2⟩) x @[simp] lemma map_comp : (map Q g hy).comp (algebra_map R S) = (algebra_map P Q).comp g := lift_comp $ λ y, map_units _ ⟨g y, hy y.2⟩ lemma map_mk' (x) (y : M) : map Q g hy (mk' S x y) = mk' Q (g x) ⟨g y, hy y.2⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom _ (λ y, hy y.2) _ _ (to_localization_map T Q) _ _ @[simp] lemma map_id (z : S) (h : M ≤ M.comap (ring_hom.id R) := le_refl M) : map S (ring_hom.id _) h z = z := lift_id _ lemma map_unique (j : S →+* Q) (hj : ∀ x : R, j (algebra_map R S x) = algebra_map P Q (g x)) : map Q g hy = j := lift_unique (λ y, map_units _ ⟨g y, hy y.2⟩) hj /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) : (map W l hl).comp (map Q g hy : S →+* _) = map W (l.comp g) (λ x hx, hl (hy hx)) := ring_hom.ext $ λ x, @submonoid.localization_map.map_map _ _ _ _ _ P _ (to_localization_map M S) g _ _ _ _ _ _ _ _ _ _ (to_localization_map U W) l _ x /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) (x : S) : map W l hl (map Q g hy x) = map W (l.comp g) (λ x hx, hl (hy hx)) x := by rw ←map_comp_map hy hl; refl lemma map_smul (x : S) (z : R) : map Q g hy (z • x : S) = g z • map Q g hy x := by rw [algebra.smul_def, algebra.smul_def, ring_hom.map_mul, map_eq] section variables (S Q) /-- If `S`, `Q` are localizations of `R` and `P` at submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ @[simps] noncomputable def ring_equiv_of_ring_equiv (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := have H' : T.map h.symm.to_monoid_hom = M, by { rw [← M.map_id, ← H, submonoid.map_map], congr, ext, apply h.symm_apply_apply }, { to_fun := map Q (h : R →+* P) (M.le_comap_of_map_le (le_of_eq H)), inv_fun := map S (h.symm : P →+* R) (T.le_comap_of_map_le (le_of_eq H')), left_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map R S) (h.symm_apply_apply x).symm }, right_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map P Q) (h.apply_symm_apply x).symm }, .. map Q (h : R →+* P) _ } end lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (ring_equiv_of_ring_equiv S Q j H : S →+* Q) = map Q (j : R →+* P) (M.le_comap_of_map_le (le_of_eq H)) := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : ring_equiv_of_ring_equiv S Q j H ((algebra_map R S) x) = algebra_map P Q (j x) := map_eq _ _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x : R) (y : M) : ring_equiv_of_ring_equiv S Q j H (mk' S x y) = mk' Q (j x) ⟨j y, show j y ∈ T, from H ▸ set.mem_image_of_mem j y.2⟩ := map_mk' _ _ _ end map section alg_equiv variables {Q : Type*} [comm_semiring Q] [algebra R Q] [is_localization M Q] section variables (M S Q) /-- If `S`, `Q` are localizations of `R` at the submonoid `M` respectively, there is an isomorphism of localizations `S ≃ₐ[R] Q`. -/ @[simps] noncomputable def alg_equiv : S ≃ₐ[R] Q := { commutes' := ring_equiv_of_ring_equiv_eq _, .. ring_equiv_of_ring_equiv S Q (ring_equiv.refl R) M.map_id } end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S Q (mk' S x y) = mk' Q x y:= map_mk' _ _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S Q).symm (mk' Q x y) = mk' S x y:= map_mk' _ _ _ end alg_equiv end is_localization section variables (M) lemma is_localization_of_alg_equiv [algebra R P] [is_localization M S] (h : S ≃ₐ[R] P) : is_localization M P := begin constructor, { intro y, convert (is_localization.map_units S y).map h.to_alg_hom.to_ring_hom.to_monoid_hom, exact (h.commutes y).symm }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M (h.symm y), apply_fun h at e, simp only [h.map_mul, h.apply_symm_apply, h.commutes] at e, exact ⟨⟨x, s⟩, e⟩ }, { intros x y, rw [← h.symm.to_equiv.injective.eq_iff, ← is_localization.eq_iff_exists M S, ← h.symm.commutes, ← h.symm.commutes], refl } end lemma is_localization_iff_of_alg_equiv [algebra R P] (h : S ≃ₐ[R] P) : is_localization M S ↔ is_localization M P := ⟨λ _, by exactI is_localization_of_alg_equiv M h, λ _, by exactI is_localization_of_alg_equiv M h.symm⟩ lemma is_localization_iff_of_ring_equiv (h : S ≃+* P) : is_localization M S ↔ @@is_localization _ M P _ (h.to_ring_hom.comp $ algebra_map R S).to_algebra := begin letI := (h.to_ring_hom.comp $ algebra_map R S).to_algebra, exact is_localization_iff_of_alg_equiv M { commutes' := λ _, rfl, ..h }, end variable (S) lemma is_localization_of_base_ring_equiv [is_localization M S] (h : R ≃+* P) : @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin constructor, { rintros ⟨_, ⟨y, hy, rfl⟩⟩, convert is_localization.map_units S ⟨y, hy⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply], exact congr_arg _ (h.symm_apply_apply _) }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M y, refine ⟨⟨h x, _, _, s.prop, rfl⟩, _⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply] at ⊢ e, convert e; exact h.symm_apply_apply _ }, { intros x y, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply, ring_hom.comp_apply, is_localization.eq_iff_exists M S], simp_rw ← h.to_equiv.apply_eq_iff_eq, change (∃ (c : M), h (c * h.symm x) = h (c * h.symm y)) ↔ _, simp only [ring_equiv.apply_symm_apply, ring_equiv.map_mul], exact ⟨λ ⟨c, e⟩, ⟨⟨_, _, c.prop, rfl⟩, e⟩, λ ⟨⟨_, c, h, e₁⟩, e₂⟩, ⟨⟨_, h⟩, e₁.symm ▸ e₂⟩⟩ } end lemma is_localization_iff_of_base_ring_equiv (h : R ≃+* P) : is_localization M S ↔ @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin refine ⟨λ _, by exactI is_localization_of_base_ring_equiv _ _ h, _⟩, letI := ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra, intro H, convert @@is_localization_of_base_ring_equiv _ _ _ _ _ _ H h.symm, { erw [submonoid.map_equiv_eq_comap_symm, submonoid.comap_map_eq_of_injective], exact h.to_equiv.injective }, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_assoc], simp only [ring_hom.comp_id, ring_equiv.symm_symm, ring_equiv.symm_to_ring_hom_comp_to_ring_hom], apply algebra.algebra_ext, intro r, rw ring_hom.algebra_map_to_algebra end end variables (M S) include M lemma non_zero_divisors_le_comap [is_localization M S] : non_zero_divisors R ≤ (non_zero_divisors S).comap (algebra_map R S) := begin rintros a ha b (e : b * algebra_map R S a = 0), obtain ⟨x, s, rfl⟩ := mk'_surjective M b, rw [← @mk'_one R _ M, ← mk'_mul, ← (algebra_map R S).map_zero, ← @mk'_one R _ M, is_localization.eq] at e, obtain ⟨c, e⟩ := e, rw [mul_zero, mul_zero, submonoid.coe_one, one_mul, ←mul_assoc] at e, rw mk'_eq_zero_iff, exact ⟨c, ha _ e⟩ end lemma map_non_zero_divisors_le [is_localization M S] : (non_zero_divisors R).map (algebra_map R S) ≤ non_zero_divisors S := submonoid.map_le_iff_le_comap.mpr (non_zero_divisors_le_comap M S) end is_localization namespace localization open is_localization /-! ### Constructing a localization at a given submonoid -/ variables {M} section instance [subsingleton R] : unique (localization M) := ⟨⟨1⟩, begin intro a, induction a, induction default, congr, refl, refl end⟩ /-- Addition in a ring localization is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨b * c + d * a, b * d⟩`. Should not be confused with `add_localization.add`, which is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨a + c, b + d⟩`. -/ @[irreducible] protected def add (z w : localization M) : localization M := localization.lift_on₂ z w (λ a b c d, mk ((b : R) * c + d * a) (b * d)) $ λ a a' b b' c c' d d' h1 h2, mk_eq_mk_iff.2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₅ * t₆, dsimp only, calc (↑t₅ * ↑t₆) * ((↑b' * ↑d') * ((b : R) * c + d * a)) = (t₆ * (d' * c)) * (t₅ * (b' * b)) + (t₅ * (b' * a)) * (t₆ * (d' * d)) : by ring ... = (t₅ * t₆) * ((b * d) * (b' * c' + d' * a')) : by rw [ht₆, ht₅]; ring end instance : has_add (localization M) := ⟨localization.add⟩ lemma add_mk (a b c d) : (mk a b : localization M) + mk c d = mk (b * c + d * a) (b * d) := by { unfold has_add.add localization.add, apply lift_on₂_mk } lemma add_mk_self (a b c) : (mk a b : localization M) + mk c b = mk (a + c) b := begin rw [add_mk, mk_eq_mk_iff, r_eq_r'], refine (r' M).symm ⟨1, _⟩, simp only [submonoid.coe_one, submonoid.coe_mul], ring end private meta def tac := `[ { intros, simp only [add_mk, localization.mk_mul, ← localization.mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring }] instance : comm_semiring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), npow := localization.npow _, nsmul := (•), nsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_nsmul, mk_zero]), nsmul_succ' := λ n x, localization.induction_on x (λ x, by simp only [smul_mk, succ_nsmul, add_mk_self]), add_assoc := λ m n k, localization.induction_on₃ m n k (by tac), zero_add := λ y, localization.induction_on y (by tac), add_zero := λ y, localization.induction_on y (by tac), add_comm := λ y z, localization.induction_on₂ z y (by tac), left_distrib := λ m n k, localization.induction_on₃ m n k (by tac), right_distrib := λ m n k, localization.induction_on₃ m n k (by tac), .. localization.comm_monoid_with_zero M } /--For any given denominator `b : M`, the map `a ↦ a / b` is an `add_monoid_hom` from `R` to `localization M`-/ @[simps] def mk_add_monoid_hom (b : M) : R →+ localization M := { to_fun := λ a, mk a b, map_zero' := mk_zero _, map_add' := λ x y, (add_mk_self _ _ _).symm } lemma mk_sum {ι : Type*} (f : ι → R) (s : finset ι) (b : M) : mk (∑ i in s, f i) b = ∑ i in s, mk (f i) b := (mk_add_monoid_hom b).map_sum f s lemma mk_list_sum (l : list R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_list_sum l lemma mk_multiset_sum (l : multiset R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_multiset_sum l instance {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] : distrib_mul_action S (localization M) := { smul_zero := λ s, by simp only [←localization.mk_zero 1, localization.smul_mk, smul_zero], smul_add := λ s x y, localization.induction_on₂ x y $ prod.rec $ by exact λ r₁ x₁, prod.rec $ by exact λ r₂ x₂, by simp only [localization.smul_mk, localization.add_mk, smul_add, mul_comm _ (s • _), mul_comm _ r₁, mul_comm _ r₂, smul_mul_assoc] } instance {S : Type*} [semiring S] [mul_semiring_action S R] [is_scalar_tower S R R] : mul_semiring_action S (localization M) := { ..localization.mul_distrib_mul_action } instance {S : Type*} [semiring S] [module S R] [is_scalar_tower S R R] : module S (localization M) := { zero_smul := localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, zero_smul, mk_zero] }, add_smul := λ s₁ s₂, localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, add_smul, add_mk_self] }, ..localization.distrib_mul_action } instance {S : Type*} [comm_semiring S] [algebra S R] : algebra S (localization M) := { to_ring_hom := ring_hom.comp { to_fun := (monoid_of M).to_map, map_zero' := by rw [← mk_zero (1 : M), mk_one_eq_monoid_of_mk], map_add' := λ x y, by simp only [← mk_one_eq_monoid_of_mk, add_mk, submonoid.coe_one, one_mul, add_comm], .. localization.monoid_of M } (algebra_map S R), smul_def' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, algebra.smul_def], end, commutes' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, mul_one, algebra.commutes], end } instance : is_localization M (localization M) := { map_units := (localization.monoid_of M).map_units, surj := (localization.monoid_of M).surj, eq_iff_exists := λ _ _, (localization.monoid_of M).eq_iff_exists } end @[simp] lemma to_localization_map_eq_monoid_of : to_localization_map M (localization M) = monoid_of M := rfl lemma monoid_of_eq_algebra_map (x) : (monoid_of M).to_map x = algebra_map R (localization M) x := rfl lemma mk_one_eq_algebra_map (x) : mk x 1 = algebra_map R (localization M) x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = is_localization.mk' (localization M) x y := by rw [mk_eq_monoid_of_mk'_apply, mk', to_localization_map_eq_monoid_of] @[simp] lemma mk_eq_mk' : (mk : R → M → localization M) = is_localization.mk' (localization M) := mk_eq_monoid_of_mk' lemma mk_algebra_map {A : Type*} [comm_semiring A] [algebra A R] (m : A) : mk (algebra_map A R m) 1 = algebra_map A (localization M) m := by rw [mk_eq_mk', mk'_eq_iff_eq_mul, submonoid.coe_one, map_one, mul_one]; refl lemma mk_nat_cast (m : ℕ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℕ _ _ m variables [is_localization M S] section variables (M S) /-- The localization of `R` at `M` as a quotient type is isomorphic to any other localization. -/ @[simps] noncomputable def alg_equiv : localization M ≃ₐ[R] S := is_localization.alg_equiv M _ _ /-- The localization of a singleton is a singleton. Cannot be an instance due to metavariables. -/ noncomputable def _root_.is_localization.unique (R Rₘ) [comm_semiring R] [comm_semiring Rₘ] (M : submonoid R) [subsingleton R] [algebra R Rₘ] [is_localization M Rₘ] : unique Rₘ := have inhabited Rₘ := ⟨1⟩, by exactI (alg_equiv M Rₘ).symm.injective.unique end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S (mk' (localization M) x y) = mk' S x y := alg_equiv_mk' _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk' (localization M) x y := alg_equiv_symm_mk' _ _ lemma alg_equiv_mk (x y) : alg_equiv M S (mk x y) = mk' S x y := by rw [mk_eq_mk', alg_equiv_mk'] lemma alg_equiv_symm_mk (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk x y := by rw [mk_eq_mk', alg_equiv_symm_mk'] end localization end comm_semiring section comm_ring variables {R : Type*} [comm_ring R] {M : submonoid R} (S : Type*) [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] namespace localization /-- Negation in a ring localization is defined as `-⟨a, b⟩ = ⟨-a, b⟩`. -/ @[irreducible] protected def neg (z : localization M) : localization M := localization.lift_on z (λ a b, mk (-a) b) $ λ a b c d h, mk_eq_mk_iff.2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [mul_neg, mul_neg, ht], ring_nf, end instance : has_neg (localization M) := ⟨localization.neg⟩ lemma neg_mk (a b) : -(mk a b : localization M) = mk (-a) b := by { unfold has_neg.neg localization.neg, apply lift_on_mk } instance : comm_ring (localization M) := { zsmul := (•), zsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_zsmul, mk_zero]), zsmul_succ' := λ n x, localization.induction_on x (λ x, by simp [smul_mk, add_mk_self, -mk_eq_monoid_of_mk', add_comm (n : ℤ) 1, add_smul]), zsmul_neg' := λ n x, localization.induction_on x (λ x, by { rw [smul_mk, smul_mk, neg_mk, ← neg_smul], refl }), neg := has_neg.neg, sub := λ x y, x + -y, sub_eq_add_neg := λ x y, rfl, add_left_neg := λ y, by exact localization.induction_on y begin intros, simp only [add_mk, localization.mk_mul, neg_mk, ← mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring end, .. localization.comm_semiring } lemma sub_mk (a c) (b d) : (mk a b : localization M) - mk c d = mk (d * a - b * c) (b * d) := calc mk a b - mk c d = mk a b + (- mk c d) : sub_eq_add_neg _ _ ... = mk a b + (mk (-c) d) : by rw neg_mk ... = mk (b * (-c) + d * a) (b * d) : add_mk _ _ _ _ ... = mk (d * a - b * c) (b * d) : by congr'; ring lemma mk_int_cast (m : ℤ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℤ _ _ m end localization namespace is_localization variables {R M} (S) {K : Type*} [is_localization M S] lemma to_map_eq_zero_iff {x : R} (hM : M ≤ non_zero_divisors R) : algebra_map R S x = 0 ↔ x = 0 := begin rw ← (algebra_map R S).map_zero, split; intro h, { cases (eq_iff_exists M S).mp h with c hc, rw [mul_zero, mul_comm] at hc, exact hM c.2 x hc }, { rw h }, end protected lemma injective (hM : M ≤ non_zero_divisors R) : injective (algebra_map R S) := begin rw injective_iff_map_eq_zero (algebra_map R S), intros a ha, rwa to_map_eq_zero_iff S hM at ha end protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] (hM : M ≤ non_zero_divisors R) {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R S x ≠ 0 := show (algebra_map R S).to_monoid_with_zero_hom x ≠ 0, from map_ne_zero_of_mem_non_zero_divisors (algebra_map R S) (is_localization.injective S hM) hx variables {S} lemma sec_snd_ne_zero [nontrivial R] (hM : M ≤ non_zero_divisors R) (x : S) : ((sec M x).snd : R) ≠ 0 := non_zero_divisors.coe_ne_zero ⟨(sec M x).snd.val, hM (sec M x).snd.property⟩ lemma sec_fst_ne_zero [nontrivial R] [no_zero_divisors S] (hM : M ≤ non_zero_divisors R) {x : S} (hx : x ≠ 0) : (sec M x).fst ≠ 0 := begin have hsec := sec_spec M x, intro hfst, rw [hfst, map_zero, mul_eq_zero, _root_.map_eq_zero_iff] at hsec, { exact or.elim hsec hx (sec_snd_ne_zero hM x) }, { exact is_localization.injective S hM } end variables (S M) (Q : Type*) [comm_ring Q] {g : R →+* P} [algebra P Q] /-- Injectivity of a map descends to the map induced on localizations. -/ lemma map_injective_of_injective (hg : function.injective g) [is_localization (M.map g : submonoid P) Q] : function.injective (map Q g M.le_comap_map : S → Q) := begin rw injective_iff_map_eq_zero, intros z hz, obtain ⟨a, b, rfl⟩ := mk'_surjective M z, rw [map_mk', mk'_eq_zero_iff] at hz, obtain ⟨⟨m', hm'⟩, hm⟩ := hz, rw submonoid.mem_map at hm', obtain ⟨n, hn, hnm⟩ := hm', rw [subtype.coe_mk, ← hnm, ← map_mul, ← map_zero g] at hm, rw [mk'_eq_zero_iff], exact ⟨⟨n, hn⟩, hg hm⟩, end variables {S Q M} variables (A : Type*) [comm_ring A] [is_domain A] /-- A `comm_ring` `S` which is the localization of a ring `R` without zero divisors at a subset of non-zero elements does not have zero divisors. See note [reducible non-instances]. -/ @[reducible] theorem no_zero_divisors_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S] (hM : M ≤ non_zero_divisors A) : no_zero_divisors S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases surj M z with x hx, cases surj M w with y hy, have : z * w * algebra_map A S y.2 * algebra_map A S x.2 = algebra_map A S x.1 * algebra_map A S y.1, by rw [mul_assoc z, hy, ←hx]; ring, rw [h, zero_mul, zero_mul, ← (algebra_map A S).map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff S hM).mp this.symm) with H H, { exact or.inl (eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (eq_zero_of_fst_eq_zero hy H) }, end } /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S] (hM : M ≤ non_zero_divisors A) : is_domain S := begin apply no_zero_divisors.to_is_domain _, { exact ⟨⟨(algebra_map A S) 0, (algebra_map A S) 1, λ h, zero_ne_one (is_localization.injective S hM h)⟩⟩ }, { exact no_zero_divisors_of_le_non_zero_divisors _ hM } end variables {A} /-- The localization at of an integral domain to a set of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : is_domain (localization M) := is_domain_of_le_non_zero_divisors _ hM end is_localization open is_localization /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma is_field.localization_map_bijective {R Rₘ : Type*} [comm_ring R] [comm_ring Rₘ] {M : submonoid R} (hM : (0 : R) ∉ M) (hR : is_field R) [algebra R Rₘ] [is_localization M Rₘ] : function.bijective (algebra_map R Rₘ) := begin letI := hR.to_field, replace hM := le_non_zero_divisors_of_no_zero_divisors hM, refine ⟨is_localization.injective _ hM, λ x, _⟩, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M x, obtain ⟨n, hn⟩ := hR.mul_inv_cancel (non_zero_divisors.ne_zero $ hM hm), exact ⟨r * n, by erw [eq_mk'_iff_mul_eq, ←map_mul, mul_assoc, mul_comm n, hn, mul_one]⟩ end /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma field.localization_map_bijective {K Kₘ : Type*} [field K] [comm_ring Kₘ] {M : submonoid K} (hM : (0 : K) ∉ M) [algebra K Kₘ] [is_localization M Kₘ] : function.bijective (algebra_map K Kₘ) := (field.to_is_field K).localization_map_bijective hM -- this looks weird due to the `letI` inside the above lemma, but trying to do it the other -- way round causes issues with defeq of instances, so this is actually easier. section algebra variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] variables [algebra R Rₘ] [is_localization M Rₘ] variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ] section variables (S M) /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps. This instance can be helpful if you define `Sₘ := localization (algebra.algebra_map_submonoid S M)`, however we will instead use the hypotheses `[algebra Rₘ Sₘ] [is_scalar_tower R Rₘ Sₘ]` in lemmas since the algebra structure may arise in different ways. -/ noncomputable def localization_algebra : algebra Rₘ Sₘ := (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* Sₘ).to_algebra end section variables [algebra Rₘ Sₘ] [algebra R Sₘ] [is_scalar_tower R Rₘ Sₘ] [is_scalar_tower R S Sₘ] variables (S Rₘ Sₘ) include S lemma is_localization.map_units_map_submonoid (y : M) : is_unit (algebra_map R Sₘ y) := begin rw is_scalar_tower.algebra_map_apply _ S, exact is_localization.map_units Sₘ ⟨algebra_map R S y, algebra.mem_algebra_map_submonoid_of_mem y⟩ end @[simp] lemma is_localization.algebra_map_mk' (x : R) (y : M) : algebra_map Rₘ Sₘ (is_localization.mk' Rₘ x y) = is_localization.mk' Sₘ (algebra_map R S x) ⟨algebra_map R S y, algebra.mem_algebra_map_submonoid_of_mem y⟩ := begin rw [is_localization.eq_mk'_iff_mul_eq, subtype.coe_mk, ← is_scalar_tower.algebra_map_apply, ← is_scalar_tower.algebra_map_apply, is_scalar_tower.algebra_map_apply R Rₘ Sₘ, is_scalar_tower.algebra_map_apply R Rₘ Sₘ, ← _root_.map_mul, mul_comm, is_localization.mul_mk'_eq_mk'_of_mul], exact congr_arg (algebra_map Rₘ Sₘ) (is_localization.mk'_mul_cancel_left x y) end variables (M) /-- If the square below commutes, the bottom map is uniquely specified: ``` R → S ↓ ↓ Rₘ → Sₘ ``` -/ lemma is_localization.algebra_map_eq_map_map_submonoid : algebra_map Rₘ Sₘ = map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) := eq.symm $ is_localization.map_unique _ (algebra_map Rₘ Sₘ) (λ x, by rw [← is_scalar_tower.algebra_map_apply R S Sₘ, ← is_scalar_tower.algebra_map_apply R Rₘ Sₘ]) /-- If the square below commutes, the bottom map is uniquely specified: ``` R → S ↓ ↓ Rₘ → Sₘ ``` -/ lemma is_localization.algebra_map_apply_eq_map_map_submonoid (x) : algebra_map Rₘ Sₘ x = map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) x := fun_like.congr_fun (is_localization.algebra_map_eq_map_map_submonoid _ _ _ _) x variables {R} lemma is_localization.lift_algebra_map_eq_algebra_map : @is_localization.lift R _ M Rₘ _ _ Sₘ _ _ (algebra_map R Sₘ) (is_localization.map_units_map_submonoid S Sₘ) = algebra_map Rₘ Sₘ := is_localization.lift_unique _ (λ x, (is_scalar_tower.algebra_map_apply _ _ _ _).symm) end variables (Rₘ Sₘ) /-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization. -/ lemma localization_algebra_injective (hRS : function.injective (algebra_map R S)) : function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) := is_localization.map_injective_of_injective M Rₘ Sₘ hRS end algebra end comm_ring
d5aaf5ab97fbc72a4d62d3479f2612376ecf2f37
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_geometry/morphisms/open_immersion.lean
4ae87dfbdce6e331cf6c478ec3560244ee4b2177
[ "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
3,901
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import topology.local_at_target import algebraic_geometry.morphisms.basic /-! # Open immersions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A morphism is an open immersions if the underlying map of spaces is an open embedding `f : X ⟶ U ⊆ Y`, and the sheaf map `Y(V) ⟶ f _* X(V)` is an iso for each `V ⊆ U`. Most of the theories are developed in `algebraic_geometry/open_immersion`, and we provide the remaining theorems analogous to other lemmas in `algebraic_geometry/morphisms/*`. -/ noncomputable theory open category_theory category_theory.limits opposite topological_space universe u namespace algebraic_geometry variables {X Y Z : Scheme.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) lemma is_open_immersion_iff_stalk {f : X ⟶ Y} : is_open_immersion f ↔ open_embedding f.1.base ∧ ∀ x, is_iso (PresheafedSpace.stalk_map f.1 x) := begin split, { intro h, exactI ⟨h.1, infer_instance⟩ }, { rintro ⟨h₁, h₂⟩, exactI is_open_immersion.of_stalk_iso f h₁ } end lemma is_open_immersion_stable_under_composition : morphism_property.stable_under_composition @is_open_immersion := begin introsI X Y Z f g h₁ h₂, apply_instance end lemma is_open_immersion_respects_iso : morphism_property.respects_iso @is_open_immersion := begin apply is_open_immersion_stable_under_composition.respects_iso, intros _ _ _, apply_instance end lemma is_open_immersion_is_local_at_target : property_is_local_at_target @is_open_immersion := begin constructor, { exact is_open_immersion_respects_iso }, { introsI, apply_instance }, { intros X Y f 𝒰 H, rw is_open_immersion_iff_stalk, split, { apply (open_embedding_iff_open_embedding_of_supr_eq_top 𝒰.supr_opens_range f.1.base.2).mpr, intro i, have := ((is_open_immersion_respects_iso.arrow_iso_iff (morphism_restrict_opens_range f (𝒰.map i))).mpr (H i)).1, rwa [arrow.mk_hom, morphism_restrict_val_base] at this }, { intro x, have := arrow.iso_w (morphism_restrict_stalk_map f ((𝒰.map $ 𝒰.f $ f.1 x).opens_range) ⟨x, 𝒰.covers _⟩), dsimp only [arrow.mk_hom] at this, rw this, haveI : is_open_immersion (f ∣_ (𝒰.map $ 𝒰.f $ f.1 x).opens_range) := (is_open_immersion_respects_iso.arrow_iso_iff (morphism_restrict_opens_range f (𝒰.map _))).mpr (H _), apply_instance } } end lemma is_open_immersion.open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) : tfae [is_open_immersion f, ∃ (𝒰 : Scheme.open_cover.{u} Y), ∀ (i : 𝒰.J), is_open_immersion (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i), ∀ (𝒰 : Scheme.open_cover.{u} Y) (i : 𝒰.J), is_open_immersion (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i), ∀ (U : opens Y.carrier), is_open_immersion (f ∣_ U), ∀ {U : Scheme} (g : U ⟶ Y) [is_open_immersion g], is_open_immersion (pullback.snd : pullback f g ⟶ _), ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤), ∀ i, is_open_immersion (f ∣_ (U i))] := is_open_immersion_is_local_at_target.open_cover_tfae f lemma is_open_immersion.open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y) (f : X ⟶ Y) : is_open_immersion f ↔ ∀ i, is_open_immersion (pullback.snd : pullback f (𝒰.map i) ⟶ _) := is_open_immersion_is_local_at_target.open_cover_iff f 𝒰 lemma is_open_immersion_stable_under_base_change : morphism_property.stable_under_base_change @is_open_immersion := morphism_property.stable_under_base_change.mk is_open_immersion_respects_iso $ by { introsI X Y Z f g H, apply_instance } end algebraic_geometry
867e558fa63a03cc002222d6b810f2e781b6f5e2
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/dynamics/circle/rotation_number/translation_number.lean
9e3b0ddca153c4ef6ac5f2df0aad9597e74b8c34
[ "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
28,240
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import analysis.specific_limits import order.iterate import algebra.iterate_hom /-! # Translation number of a monotone real map that commutes with `x ↦ x + 1` Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit $$ \tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n} $$ exists and does not depend on `x`. This number is called the *translation number* of `f`. Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc In this file we define a structure `circle_deg1_lift` for bundled maps with these properties, define translation number of `f : circle_deg1_lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and only if `τ(f)=m/n`. Maps of this type naturally appear as lifts of orientation preserving circle homeomorphisms. More precisely, let `f` be an orientation preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and consider a real number `a` such that `⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is not formalized yet). This function is strictly monotone, continuous, and satisfies `F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`. It does not depend on the choice of `a`. We chose to define translation number for a wider class of maps `f : ℝ → ℝ` for two reasons: * non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry cells); * definition and some basic properties still work for this class. ## Notation We use a local notation `τ` for the translation number of `f : circle_deg1_lift`. ## Tags circle homeomorphism, rotation number -/ open filter set open_locale topological_space classical /-! ### Definition and monoid structure -/ /-- A lift of a monotone degree one map `S¹ → S¹`. -/ structure circle_deg1_lift : Type := (to_fun : ℝ → ℝ) (monotone' : monotone to_fun) (map_add_one' : ∀ x, to_fun (x + 1) = to_fun x + 1) namespace circle_deg1_lift instance : has_coe_to_fun circle_deg1_lift := ⟨λ _, ℝ → ℝ, circle_deg1_lift.to_fun⟩ @[simp] lemma coe_mk (f h₁ h₂) : ⇑(mk f h₁ h₂) = f := rfl variables (f g : circle_deg1_lift) protected lemma monotone : monotone f := f.monotone' @[mono] lemma mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h @[simp] lemma map_add_one : ∀ x, f (x + 1) = f x + 1 := f.map_add_one' @[simp] lemma map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm] theorem coe_inj : ∀ ⦃f g : circle_deg1_lift ⦄, (f : ℝ → ℝ) = g → f = g := assume ⟨f, fm, fd⟩ ⟨g, gm, gd⟩ h, by congr; exact h @[ext] theorem ext ⦃f g : circle_deg1_lift ⦄ (h : ∀ x, f x = g x) : f = g := coe_inj $ funext h theorem ext_iff {f g : circle_deg1_lift} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : monoid circle_deg1_lift := { mul := λ f g, { to_fun := f ∘ g, monotone' := f.monotone.comp g.monotone, map_add_one' := λ x, by simp [map_add_one] }, one := ⟨id, monotone_id, λ _, rfl⟩, mul_one := λ f, coe_inj $ function.comp.right_id f, one_mul := λ f, coe_inj $ function.comp.left_id f, mul_assoc := λ f₁ f₂ f₃, coe_inj rfl } instance : inhabited circle_deg1_lift := ⟨1⟩ @[simp] lemma coe_mul : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (x) : (f * g) x = f (g x) := rfl @[simp] lemma coe_one : ⇑(1 : circle_deg1_lift) = id := rfl instance units_has_coe_to_fun : has_coe_to_fun (units circle_deg1_lift) := ⟨λ _, ℝ → ℝ, λ f, ⇑(f : circle_deg1_lift)⟩ @[simp, norm_cast] lemma units_coe (f : units circle_deg1_lift) : ⇑(f : circle_deg1_lift) = f := rfl lemma coe_pow : ∀ n : ℕ, ⇑(f^n) = (f^[n]) | 0 := rfl | (n+1) := by {ext x, simp [coe_pow n, pow_succ'] } lemma semiconj_by_iff_semiconj {f g₁ g₂ : circle_deg1_lift} : semiconj_by f g₁ g₂ ↔ function.semiconj f g₁ g₂ := ext_iff lemma commute_iff_commute {f g : circle_deg1_lift} : commute f g ↔ function.commute f g := ext_iff /-! ### Translate by a constant -/ /-- The map `y ↦ x + y` as a `circle_deg1_lift`. More precisely, we define a homomorphism from `multiplicative ℝ` to `units circle_deg1_lift`, so the translation by `x` is `translation (multiplicative.of_add x)`. -/ def translate : multiplicative ℝ →* units circle_deg1_lift := by refine (units.map _).comp to_units.to_monoid_hom; exact { to_fun := λ x, ⟨λ y, x.to_add + y, λ y₁ y₂ h, add_le_add_left h _, λ y, (add_assoc _ _ _).symm⟩, map_one' := ext $ zero_add, map_mul' := λ x y, ext $ add_assoc _ _ } @[simp] lemma translate_apply (x y : ℝ) : translate (multiplicative.of_add x) y = x + y := rfl @[simp] lemma translate_inv_apply (x y : ℝ) : (translate $ multiplicative.of_add x)⁻¹ y = -x + y := rfl @[simp] lemma translate_gpow (x : ℝ) (n : ℤ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ n * x) := by simp only [← gsmul_eq_mul, of_add_gsmul, monoid_hom.map_gpow] @[simp] lemma translate_pow (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ n * x) := translate_gpow x n @[simp] lemma translate_iterate (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^[n] = translate (multiplicative.of_add $ n * x) := by rw [← units_coe, ← coe_pow, ← units.coe_pow, translate_pow, units_coe] /-! ### Commutativity with integer translations In this section we prove that `f` commutes with translations by an integer number. First we formulate these statements (for a natural or an integer number, addition on the left or on the right, addition or subtraction) using `function.commute`, then reformulate as `simp` lemmas `map_int_add` etc. -/ lemma commute_nat_add (n : ℕ) : function.commute f ((+) n) := by simpa only [nsmul_one, add_left_iterate] using function.commute.iterate_right f.map_one_add n lemma commute_add_nat (n : ℕ) : function.commute f (λ x, x + n) := by simp only [add_comm _ (n:ℝ), f.commute_nat_add n] lemma commute_sub_nat (n : ℕ) : function.commute f (λ x, x - n) := (f.commute_add_nat n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv lemma commute_add_int : ∀ n : ℤ, function.commute f (λ x, x + n) | (n:ℕ) := f.commute_add_nat n | -[1+n] := f.commute_sub_nat (n + 1) lemma commute_int_add (n : ℤ) : function.commute f ((+) n) := by simpa only [add_comm _ (n:ℝ)] using f.commute_add_int n lemma commute_sub_int (n : ℤ) : function.commute f (λ x, x - n) := (f.commute_add_int n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv @[simp] lemma map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x := f.commute_int_add m x @[simp] lemma map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m := f.commute_add_int m x @[simp] lemma map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n := f.commute_sub_int n x @[simp] lemma map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n := f.map_add_int x n @[simp] lemma map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x := f.map_int_add n x @[simp] lemma map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n := f.map_sub_int x n lemma map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add] @[simp] lemma map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by conv_rhs { rw [← fract_add_floor x, f.map_add_int, add_sub_comm, sub_self, add_zero] } /-! ### Pointwise order on circle maps -/ /-- Monotone circle maps form a lattice with respect to the pointwise order -/ noncomputable instance : lattice circle_deg1_lift := { sup := λ f g, { to_fun := λ x, max (f x) (g x), monotone' := λ x y h, max_le_max (f.mono h) (g.mono h), -- TODO: generalize to `monotone.max` map_add_one' := λ x, by simp [max_add_add_right] }, le := λ f g, ∀ x, f x ≤ g x, le_refl := λ f x, le_refl (f x), le_trans := λ f₁ f₂ f₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ f₁ f₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x), le_sup_left := λ f g x, le_max_left (f x) (g x), le_sup_right := λ f g x, le_max_right (f x) (g x), sup_le := λ f₁ f₂ f₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), inf := λ f g, { to_fun := λ x, min (f x) (g x), monotone' := λ x y h, min_le_min (f.mono h) (g.mono h), map_add_one' := λ x, by simp [min_add_add_right] }, inf_le_left := λ f g x, min_le_left (f x) (g x), inf_le_right := λ f g x, min_le_right (f x) (g x), le_inf := λ f₁ f₂ f₃ h₂ h₃ x, le_min (h₂ x) (h₃ x) } @[simp] lemma sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) := rfl @[simp] lemma inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) := rfl lemma iterate_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^[n]) := λ f g h, f.monotone.iterate_le_of_le h _ lemma iterate_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := iterate_monotone n h lemma pow_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^n ≤ g^n := λ x, by simp only [coe_pow, iterate_mono h n x] lemma pow_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^n) := λ f g h, pow_mono h n /-! ### Estimates on `(f * g) 0` We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed floors and ceils. We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0` is less than two. -/ lemma map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ := calc f x ≤ f ⌈x⌉ : f.monotone $ le_ceil _ ... = f 0 + ⌈x⌉ : f.map_int_of_map_zero _ lemma map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_le_of_map_zero (g 0) lemma floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ := calc ⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ : floor_mono $ f.map_map_zero_le g ... = ⌊f 0⌋ + ⌈g 0⌉ : floor_add_int _ _ lemma ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ := calc ⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ : ceil_mono $ f.map_map_zero_le g ... = ⌈f 0⌉ + ⌈g 0⌉ : ceil_add_int _ _ lemma map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 := calc f (g 0) ≤ f 0 + ⌈g 0⌉ : f.map_map_zero_le g ... < f 0 + (g 0 + 1) : add_lt_add_left (ceil_lt_add_one _) _ ... = f 0 + g 0 + 1 : (add_assoc _ _ _).symm lemma le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x := calc f 0 + ⌊x⌋ = f ⌊x⌋ : (f.map_int_of_map_zero _).symm ... ≤ f x : f.monotone $ floor_le _ lemma le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) := f.le_map_of_map_zero (g 0) lemma le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ := calc ⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ : (floor_add_int _ _).symm ... ≤ ⌊f (g 0)⌋ : floor_mono $ f.le_map_map_zero g lemma le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ := calc ⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ : (ceil_add_int _ _).symm ... ≤ ⌈f (g 0)⌉ : ceil_mono $ f.le_map_map_zero g lemma lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) := calc f 0 + g 0 - 1 = f 0 + (g 0 - 1) : add_assoc _ _ _ ... < f 0 + ⌊g 0⌋ : add_lt_add_left (sub_one_lt_floor _) _ ... ≤ f (g 0) : f.le_map_map_zero g lemma dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := begin rw [dist_comm, real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add'], exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩ end lemma dist_map_zero_lt_of_semiconj {f g₁ g₂ : circle_deg1_lift} (h : function.semiconj f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := calc dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) : dist_triangle _ _ _ ... = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) : by simp only [h.eq, real.dist_eq, sub_sub, add_comm (f 0), sub_sub_assoc_swap, abs_sub (g₂ (f 0))] ... < 2 : add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f) lemma dist_map_zero_lt_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (h : semiconj_by f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := dist_map_zero_lt_of_semiconj $ semiconj_by_iff_semiconj.1 h /-! ### Estimates on `(f^n) x` If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on `f^[n] x` and `x + n * m`. For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications work for `n = 0`. For `<` and `>` we formulate only `iff` versions. -/ lemma iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) : f^[n] x ≤ x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const m) h n lemma le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) : x + n * m ≤ (f^[n]) x := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const m) f.monotone h n lemma iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) : f^[n] x = x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h lemma iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x < x + n * m ↔ f x < x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x = x + n * m ↔ f x = x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strict_mono_id.add_const m) hn lemma le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m ≤ (f^[n]) x ↔ x + m ≤ f x := by simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn) lemma lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m < (f^[n]) x ↔ x + m < f x := by simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn) lemma mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊(f^[n] 0)⌋ := begin rw [le_floor, int.cast_mul, int.cast_coe_nat, ← zero_add ((n : ℝ) * _)], apply le_iterate_of_add_int_le_map, simp [floor_le] end /-! ### Definition of translation number -/ noncomputable theory /-- An auxiliary sequence used to define the translation number. -/ def transnum_aux_seq (n : ℕ) : ℝ := (f^(2^n)) 0 / 2^n /-- The translation number of a `circle_deg1_lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler this way. -/ def translation_number : ℝ := lim at_top f.transnum_aux_seq -- TODO: choose two different symbols for `circle_deg1_lift.translation_number` and the future -- `circle_mono_homeo.rotation_number`, then make them `localized notation`s local notation `τ` := translation_number lemma transnum_aux_seq_def : f.transnum_aux_seq = λ n : ℕ, (f^(2^n)) 0 / 2^n := rfl lemma translation_number_eq_of_tendsto_aux {τ' : ℝ} (h : tendsto f.transnum_aux_seq at_top (𝓝 τ')) : τ f = τ' := h.lim_eq lemma translation_number_eq_of_tendsto₀ {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n] 0 / n) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto_aux $ by simpa [(∘), transnum_aux_seq_def, coe_pow] using h.comp (nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two) lemma translation_number_eq_of_tendsto₀' {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n + 1] 0 / (n + 1)) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto₀ $ (tendsto_add_at_top_iff_nat 1).1 h lemma transnum_aux_seq_zero : f.transnum_aux_seq 0 = f 0 := by simp [transnum_aux_seq] lemma transnum_aux_seq_dist_lt (n : ℕ) : dist (f.transnum_aux_seq n) (f.transnum_aux_seq (n+1)) < (1 / 2) / (2^n) := begin have : 0 < (2^(n+1):ℝ) := pow_pos zero_lt_two _, rw [div_div_eq_div_mul, ← pow_succ, ← abs_of_pos this], replace := abs_pos_iff.2 (ne_of_gt this), convert (div_lt_div_right this).2 ((f^(2^n)).dist_map_map_zero_lt (f^(2^n))), simp_rw [transnum_aux_seq, real.dist_eq], rw [← abs_div, sub_div, pow_succ', pow_succ, ← two_mul, mul_div_mul_left _ _ (@two_ne_zero ℝ _), pow_mul, pow_two, mul_apply] end lemma tendsto_translation_number_aux : tendsto f.transnum_aux_seq at_top (𝓝 $ τ f) := (cauchy_seq_of_le_geometric_two 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n)).tendsto_lim lemma dist_map_zero_translation_number_le : dist (f 0) (τ f) ≤ 1 := f.transnum_aux_seq_zero ▸ dist_le_of_le_geometric_two_of_tendsto₀ 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n) f.tendsto_translation_number_aux lemma tendsto_translation_number_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) (x n) ≤ C) : tendsto (λ n : ℕ, x (2^n) / (2^n)) at_top (𝓝 $ τ f) := begin refine f.tendsto_translation_number_aux.congr_dist (squeeze_zero (λ _, dist_nonneg) _ _), { exact λ n, C / 2^n }, { intro n, have : 0 < (2^n:ℝ) := pow_pos zero_lt_two _, convert (div_le_div_right this).2 (H (2^n)), rw [transnum_aux_seq, real.dist_eq, ← sub_div, abs_div, abs_of_pos this, real.dist_eq] }, { exact mul_zero C ▸ tendsto_const_nhds.mul (tendsto_inv_at_top_zero.comp $ tendsto_pow_at_top_at_top_of_one_lt one_lt_two) } end lemma translation_number_eq_of_dist_bounded {f g : circle_deg1_lift} (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) ((g^n) 0) ≤ C) : τ f = τ g := eq.symm $ g.translation_number_eq_of_tendsto_aux $ f.tendsto_translation_number_of_dist_bounded_aux _ C H @[simp] lemma translation_number_map_id : τ 1 = 0 := translation_number_eq_of_tendsto₀ _ $ by simp [tendsto_const_nhds] lemma translation_number_eq_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (H : semiconj_by f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_dist_bounded 2 $ λ n, le_of_lt $ dist_map_zero_lt_of_semiconj_by $ H.pow_right n lemma translation_number_eq_of_semiconj {f g₁ g₂ : circle_deg1_lift} (H : function.semiconj f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_semiconj_by $ semiconj_by_iff_semiconj.2 H lemma translation_number_mul_of_commute {f g : circle_deg1_lift} (h : commute f g) : τ (f * g) = τ f + τ g := begin have : tendsto (λ n : ℕ, ((λ k, (f^k) 0 + (g^k) 0) (2^n)) / (2^n)) at_top (𝓝 $ τ f + τ g) := ((f.tendsto_translation_number_aux.add g.tendsto_translation_number_aux).congr $ λ n, (add_div ((f^(2^n)) 0) ((g^(2^n)) 0) ((2:ℝ)^n)).symm), refine tendsto_nhds_unique ((f * g).tendsto_translation_number_of_dist_bounded_aux _ 1 (λ n, _)) this, rw [h.mul_pow, dist_comm], exact le_of_lt ((f^n).dist_map_map_zero_lt (g^n)) end @[simp] lemma translation_number_pow : ∀ n : ℕ, τ (f^n) = n * τ f | 0 := by simp | (n+1) := by rw [pow_succ', translation_number_mul_of_commute (commute.pow_self f n), translation_number_pow n, nat.cast_add_one, add_mul, one_mul] @[simp] lemma translation_number_conj_eq (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑f * g * ↑(f⁻¹)) = τ g := (translation_number_eq_of_semiconj_by (f.mk_semiconj_by g)).symm @[simp] lemma translation_number_conj_eq' (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑(f⁻¹) * g * f) = τ g := translation_number_conj_eq f⁻¹ g lemma dist_pow_map_zero_mul_translation_number_le (n:ℕ) : dist ((f^n) 0) (n * f.translation_number) ≤ 1 := f.translation_number_pow n ▸ (f^n).dist_map_zero_translation_number_le lemma tendsto_translation_number₀' : tendsto (λ n:ℕ, (f^(n+1)) 0 / (n+1)) at_top (𝓝 $ τ f) := begin refine (tendsto_iff_dist_tendsto_zero.2 $ squeeze_zero (λ _, dist_nonneg) (λ n, _) ((tendsto_const_div_at_top_nhds_0_nat 1).comp (tendsto_add_at_top_nat 1))), dsimp, have : (0:ℝ) < n + 1 := n.cast_add_one_pos, rw [real.dist_eq, div_sub' _ _ _ (ne_of_gt this), abs_div, ← real.dist_eq, abs_of_pos this, div_le_div_right this, ← nat.cast_add_one], apply dist_pow_map_zero_mul_translation_number_le end lemma tendsto_translation_number₀ : tendsto (λ n:ℕ, ((f^n) 0) / n) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).1 f.tendsto_translation_number₀' /-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`. In particular, this limit does not depend on `x`. -/ lemma tendsto_translation_number (x : ℝ) : tendsto (λ n:ℕ, ((f^n) x - x) / n) at_top (𝓝 $ τ f) := begin rw [← translation_number_conj_eq' (translate $ multiplicative.of_add x)], convert tendsto_translation_number₀ _, ext n, simp [sub_eq_neg_add, units.conj_pow'] end lemma tendsto_translation_number' (x : ℝ) : tendsto (λ n:ℕ, ((f^(n+1)) x - x) / (n+1)) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).2 (f.tendsto_translation_number x) lemma translation_number_mono : monotone τ := λ f g h, le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ $ λ n, div_le_div_of_le_of_nonneg (pow_mono h n 0) n.cast_nonneg lemma translation_number_translate (x : ℝ) : τ (translate $ multiplicative.of_add x) = x := translation_number_eq_of_tendsto₀' _ $ by simp [nat.cast_add_one_ne_zero, mul_div_cancel_left, tendsto_const_nhds] lemma translation_number_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_left _ (hz x) (add_comm _ _)) lemma le_translation_number_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_right _ (add_comm _ _) (hz x)) lemma translation_number_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m := le_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (div_le_iff' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ sub_le_iff_le_add'.2 $ (coe_pow f (n + 1)).symm ▸ f.iterate_le_of_map_le_add_int h (n + 1) lemma translation_number_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m := @translation_number_le_of_le_add_int f x m h lemma le_translation_number_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f := ge_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (le_div_iff (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ le_sub_iff_add_le'.2 $ by simp only [coe_pow, mul_comm (m:ℝ), ← nat.cast_add_one, f.le_iterate_of_add_int_le_map h] lemma le_translation_number_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f := @le_translation_number_of_add_int_le f x m h /-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`. On the circle this means that a map with a fixed point has rotation number zero. -/ lemma translation_number_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m := le_antisymm (translation_number_le_of_le_add_int f $ le_of_eq h) (le_translation_number_of_add_int_le f $ le_of_eq h.symm) lemma floor_sub_le_translation_number (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f := le_translation_number_of_add_int_le f $ le_sub_iff_add_le'.1 (floor_le $ f x - x) lemma translation_number_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ := translation_number_le_of_le_add_int f $ sub_le_iff_le_add'.1 (le_ceil $ f x - x) lemma map_lt_of_translation_number_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n := not_le.1 $ mt f.le_translation_number_of_add_int_le $ not_le.2 h lemma map_lt_of_translation_number_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n := @map_lt_of_translation_number_lt_int f n h x lemma lt_map_of_int_lt_translation_number {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := not_le.1 $ mt f.translation_number_le_of_le_add_int $ not_le.2 h lemma lt_map_of_nat_lt_translation_number {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := @lt_map_of_int_lt_translation_number f n h x /-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then `τ f = m / n`. On the circle this means that a map with a periodic orbit has a rational rotation number. -/ lemma translation_number_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f^n) x = x + m) (hn : 0 < n) : τ f = m / n := begin have := (f^n).translation_number_of_eq_add_int h, rwa [translation_number_pow, mul_comm, ← eq_div_iff] at this, exact nat.cast_ne_zero.2 (ne_of_gt hn) end /-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`, then it holds for all `x`. -/ lemma forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0:ℝ) 1, P (f x - x)) (x : ℝ) : P (f x - x) := f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩ lemma translation_number_lt_of_forall_lt_add (hf : continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) : τ f < z := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f y - y ≤ f x - x, from compact_Icc.exists_forall_ge (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_le_of_lt _ (sub_lt_iff_lt_add'.2 $ hz x), apply translation_number_le_of_le_add, simp only [← sub_le_iff_le_add'], exact f.forall_map_sub_of_Icc (λ a, a ≤ f x - x) hx end lemma lt_translation_number_of_forall_add_lt (hf : continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) : z < τ f := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f x - x ≤ f y - y, from compact_Icc.exists_forall_le (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 $ hz x) _, apply le_translation_number_of_add_le, simp only [← le_sub_iff_add_le'], exact f.forall_map_sub_of_Icc _ hx end /-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x` such that `f x = x + τ f`. -/ lemma exists_eq_add_translation_number (hf : continuous f) : ∃ x, f x = x + τ f := begin obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + f.translation_number, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.lt_translation_number_of_forall_add_lt hf H) }, obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.translation_number_lt_of_forall_lt_add hf H) }, exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb end lemma translation_number_eq_int_iff (hf : continuous f) {m : ℤ} : τ f = m ↔ ∃ x, f x = x + m := begin refine ⟨λ h, h ▸ f.exists_eq_add_translation_number hf, _⟩, rintros ⟨x, hx⟩, exact f.translation_number_of_eq_add_int hx end lemma continuous_pow (hf : continuous f) (n : ℕ) : continuous ⇑(f^n : circle_deg1_lift) := by { rw coe_pow, exact hf.iterate n } lemma translation_number_eq_rat_iff (hf : continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) : τ f = m / n ↔ ∃ x, (f^n) x = x + m := begin rw [eq_div_iff, mul_comm, ← translation_number_pow]; [skip, exact ne_of_gt (nat.cast_pos.2 hn)], exact (f^n).translation_number_eq_int_iff (f.continuous_pow hf n) end end circle_deg1_lift
2d25a263cf4efa219fcebe4edfc435f42765a7b6
7571914d3f4d9677288f35ab1a53a2ad70a62bd7
/tests/lean/run/mk_byte.lean
ca5db36563ab8ee582424bf2cfbc9bc02207e066
[ "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
1,281
lean
namespace Ex universe u -- def vector (α : Type u) (n : ℕ) := { l : list α // l.length = n } namespace vector variables {α : Type u} {n : ℕ} @[pattern] def cons : α → vector α n → vector α (nat.succ n) | a ⟨ v, h ⟩ := ⟨ a::v, congr_arg nat.succ h ⟩ def to_list' (v : vector α n) : list α := v.1 def drop (i : ℕ) : vector α n → vector α (n - i) | ⟨l, p⟩ := ⟨ list.drop i l, by simp * ⟩ protected axiom eq {n : ℕ} : ∀ (a1 a2 : vector α n), to_list' a1 = to_list' a2 → a1 = a2 @[simp] axiom to_list'_cons (a : α) (v : vector α n) : to_list' (cons a v) = list.cons a (to_list' v) @[simp] axiom to_list'_drop {n m : ℕ} (v : vector α m) : to_list' (drop n v) = list.drop n (to_list' v) end vector open Ex.vector @[reducible] def bitvec (n : ℕ) := vector bool n def byte_type := bitvec 8 -- A byte is formed from concatenating two bits and a 6-bit field. def mk_byte (a b : bool) (l : bitvec 6) : byte_type := cons a (cons b l) -- Get the third component def get_data (byte : byte_type) : bitvec 6 := vector.drop 2 byte lemma get_data_mk_byte {a b : bool} {l : bitvec 6} : get_data (mk_byte a b l) = l := begin apply vector.eq, unfold mk_byte, unfold get_data, simp [to_list'_drop], simp [to_list'_cons] end end Ex
f017079b5a19ea4c069053dfdf18ef1d9a11b904
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/enat.lean
7f53e7b035da8e85f08cd0f9ff49f2da8e8abf62
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,030
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.pfun import tactic.norm_num import data.equiv.mul_add /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊤`. ## Main definitions The following instances are defined: * `ordered_add_comm_monoid enat` * `canonically_ordered_add_monoid enat` There is no additive analogue of `monoid_with_zero`; if there were then `enat` could be an `add_monoid_with_top`. * `to_with_top` : the map from `enat` to `with_top ℕ`, with theorems that it plays well with `+` and `≤`. * `with_top_add_equiv : enat ≃+ with_top ℕ` * `with_top_order_iso : enat ≃o with_top ℕ` ## Implementation details `enat` is defined to be `part ℕ`. `+` and `≤` are defined on `enat`, but there is an issue with `*` because it's not clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous so there is no `-` defined on `enat`. Before the `open_locale classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`, followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`. ## Tags enat, with_top ℕ -/ open part (hiding some) /-- Type of natural numbers with infinity (`⊤`) -/ def enat : Type := part ℕ namespace enat /-- The computable embedding `ℕ → enat`. This coincides with the coercion `coe : ℕ → enat`, see `enat.some_eq_coe`. However, `coe` is noncomputable so `some` is preferable when computability is a concern. -/ def some : ℕ → enat := part.some instance : has_zero enat := ⟨some 0⟩ instance : inhabited enat := ⟨0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance (n : ℕ) : decidable (some n).dom := is_true trivial lemma some_eq_coe (n : ℕ) : some n = n := begin induction n with n ih, { refl }, apply part.ext', { show true ↔ ((n : enat).dom ∧ true), rw [← ih, and_true], exact iff.rfl }, { intros h H, show n.succ = (n : enat).get H.1 + 1, rw [nat.cast_succ] at H, revert H, simp only [← ih], intro, refl }, end @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := by simpa only [← some_eq_coe] using part.some_inj @[simp] lemma dom_some (x : ℕ) : (some x).dom := trivial @[simp] lemma dom_coe (x : ℕ) : (x : enat).dom := by rw [← some_eq_coe]; trivial instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, part.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, part.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, part.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, part.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ lemma le_def (x y : enat) : x ≤ y ↔ ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy := iff.rfl @[elab_as_eliminator] protected lemma cases_on' {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P (some n)) → P a := part.induction_on @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := by { simp only [← some_eq_coe], exact enat.cases_on' } @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := part.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := by { rw [← some_eq_coe], exact part.ext' (iff_of_true trivial h) (λ _ _, rfl) } @[simp, norm_cast] lemma get_coe' (x : ℕ) (h : (x : enat).dom) : get (x : enat) h = x := by rw [← coe_inj, coe_get] lemma get_coe {x : ℕ} : get (x : enat) (dom_coe x) = x := get_coe' _ _ lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := by { simp only [← some_eq_coe] at h ⊢, refl } @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma get_eq_iff_eq_some {a : enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some lemma get_eq_iff_eq_coe {a : enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some, some_eq_coe] lemma dom_of_le_of_dom {x y : enat} : x ≤ y → y.dom → x.dom := λ ⟨h, _⟩, h lemma dom_of_le_some {x : enat} {y : ℕ} (h : x ≤ some y) : x.dom := dom_of_le_of_dom h trivial lemma dom_of_le_coe {x : enat} {y : ℕ} (h : x ≤ y) : x.dom := by { rw [← some_eq_coe] at h, exact dom_of_le_some h } instance decidable_le (x y : enat) [decidable x.dom] [decidable y.dom] : decidable (x ≤ y) := if hx : x.dom then decidable_of_decidable_of_iff (show decidable (∀ (hy : (y : enat).dom), x.get hx ≤ (y : enat).get hy), from forall_prop_decidable _) $ by { dsimp [(≤)], simp only [hx, exists_prop_of_true, forall_true_iff] } else if hy : y.dom then is_false $ λ h, hx $ dom_of_le_of_dom h hy else is_true ⟨λ h, (hy h).elim, λ h, (hy h).elim⟩ /-- The coercion `ℕ → enat` preserves `0` and addition. -/ def coe_hom : ℕ →+ enat := ⟨coe, nat.cast_zero, nat.cast_add⟩ @[simp] lemma coe_coe_hom : ⇑coe_hom = coe := rfl instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_refl _⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, part.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } lemma lt_def (x y : enat) : x < y ↔ ∃ (hx : x.dom), ∀ (hy : y.dom), x.get hx < y.get hy := begin rw [lt_iff_le_not_le, le_def, le_def, not_exists], split, { rintro ⟨⟨hyx, H⟩, h⟩, by_cases hx : x.dom, { use hx, intro hy, specialize H hy, specialize h (λ _, hy), rw not_forall at h, cases h with hx' h, rw not_le at h, exact h }, { specialize h (λ hx', (hx hx').elim), rw not_forall at h, cases h with hx' h, exact (hx hx').elim } }, { rintro ⟨hx, H⟩, exact ⟨⟨λ _, hx, λ hy, (H hy).le⟩, λ hxy h, not_lt_of_le (h _) (H _)⟩ } end @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := by { rw [← some_eq_coe, ← some_eq_coe], exact ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ } @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] @[simp] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} lemma le_coe_iff (x : enat) (n : ℕ) : x ≤ n ↔ ∃ h : x.dom, x.get h ≤ n := begin rw [← some_eq_coe], show (∃ (h : true → x.dom), _) ↔ ∃ h : x.dom, x.get h ≤ n, simp only [forall_prop_of_true, some_eq_coe, dom_coe, get_coe'], split; rintro ⟨_, _⟩; refine ⟨_, _⟩; intros; try { assumption } end lemma lt_coe_iff (x : enat) (n : ℕ) : x < n ↔ ∃ h : x.dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_coe', dom_coe] lemma coe_le_iff (n : ℕ) (x : enat) : (n : enat) ≤ x ↔ ∀ h : x.dom, n ≤ x.get h := begin rw [← some_eq_coe], simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end lemma coe_lt_iff (n : ℕ) (x : enat) : (n : enat) < x ↔ ∀ h : x.dom, n < x.get h := begin rw [← some_eq_coe], simp only [lt_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end protected lemma zero_lt_one : (0 : enat) < 1 := by { norm_cast, norm_num } instance semilattice_sup_bot : semilattice_sup_bot enat := { sup := (⊔), bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩, le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩, ..enat.semilattice_sup_bot } lemma dom_of_lt {x y : enat} : x < y → x.dom := enat.cases_on x not_top_lt $ λ _ _, dom_coe _ lemma top_eq_none : (⊤ : enat) = none := rfl @[simp] lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := ne.lt_top (λ h, absurd (congr_arg dom h) $ by simpa only [dom_coe] using true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃ (n : ℕ), x = n := by simpa only [← some_eq_coe] using part.ne_none_iff lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 part.eq_none_iff'.symm lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma eq_top_iff_forall_lt (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) < x := begin split, { rintro rfl n, exact coe_lt_top _ }, { contrapose!, rw ne_top_iff, rintro ⟨n, rfl⟩, exact ⟨n, irrefl _⟩ } end lemma eq_top_iff_forall_le (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) ≤ x := (eq_top_iff_forall_lt x).trans ⟨λ h n, (h n).le, λ h n, lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x (by simp only [iff_true, le_top, coe_lt_top, ← @nat.cast_zero enat]) $ λ n, by { rw [← nat.cast_zero, ← nat.cast_one, enat.coe_lt_coe, enat.coe_le_coe], refl } noncomputable instance : linear_order enat := { le_total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))), decidable_le := classical.dec_rel _, ..enat.partial_order } noncomputable instance : bounded_lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.order_top, ..enat.semilattice_sup_bot } lemma sup_eq_max {a b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _)) (max_le le_sup_left le_sup_right) lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl instance : ordered_add_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro (dom_coe _) (h₁ h.2), λ h, by simpa only [coe_add_get] using add_le_add_left (h₂ _) c⟩), ..enat.linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_add_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← nat.cast_add, coe_inj, add_comm, nat.sub_add_cancel (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← nat.cast_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)), ..enat.semilattice_sup_bot, ..enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, λ h, enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply enat.cases_on a; apply enat.cases_on b; simp; simp only [(nat.cast_add _ _).symm, enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply enat.cases_on a; apply enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)]; simp only [(nat.cast_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [decidable x.dom] : with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom} : to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_some (n : ℕ) : to_with_top (some n) = n := rfl lemma to_with_top_coe (n : ℕ) {_ : decidable (n : enat).dom} : to_with_top n = n := by { simp only [← some_eq_coe, ← to_with_top_some], congr } @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := lt_iff_lt_of_le_iff_le to_with_top_le end with_top section with_top_equiv open_locale classical @[simp] lemma to_with_top_add {x y : enat} : to_with_top (x + y) = to_with_top x + to_with_top y := begin apply enat.cases_on y; apply enat.cases_on x, { simp }, { simp }, { simp }, -- not sure why `simp` can't do this { intros, rw [to_with_top_coe', to_with_top_coe'], norm_cast, exact to_with_top_coe' _ } end /-- `equiv` between `enat` and `with_top ℕ` (for the order isomorphism see `with_top_order_iso`). -/ noncomputable def with_top_equiv : enat ≃ with_top ℕ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (option.some n) := coe n | none := ⊤ end, left_inv := λ x, by apply enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := by simpa only [nat.cast_zero] using with_top_equiv_coe 0 @[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt /-- `to_with_top` induces an order isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_order_iso : enat ≃o with_top ℕ := { map_rel_iff' := λ _ _, with_top_equiv_le, .. with_top_equiv} @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp /-- `to_with_top` induces an additive monoid isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_add_equiv : enat ≃+ with_top ℕ := { map_add' := λ x y, by simp only [with_top_equiv]; convert to_with_top_add, ..with_top_equiv} end with_top_equiv lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ section find variables (P : ℕ → Prop) [decidable_pred P] /-- The smallest `enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find : enat := ⟨∃ n, P n, nat.find⟩ @[simp] lemma find_get (h : (find P).dom) : (find P).get h = nat.find h := rfl lemma find_dom (h : ∃ n, P n) : (find P).dom := h lemma lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : enat) < find P := begin rw coe_lt_iff, intro h', rw find_get, have := @nat.find_spec P _ h', contrapose! this, exact h _ this end lemma lt_find_iff (n : ℕ) : (n : enat) < find P ↔ (∀ m ≤ n, ¬P m) := begin refine ⟨_, lt_find P n⟩, intros h m hm, by_cases H : (find P).dom, { apply nat.find_min H, rw coe_lt_iff at h, specialize h H, exact lt_of_le_of_lt hm h }, { exact not_exists.mp H m } end lemma find_le (n : ℕ) (h : P n) : find P ≤ n := by { rw le_coe_iff, refine ⟨⟨_, h⟩, @nat.find_min' P _ _ _ h⟩ } lemma find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n := (eq_top_iff_forall_lt _).trans ⟨λ h n, (lt_find_iff P n).mp (h n) _ le_rfl, λ h n, lt_find P n $ λ _ _, h _⟩ end find noncomputable instance : linear_ordered_add_comm_monoid_with_top enat := { top_add' := top_add, .. enat.linear_order, .. enat.ordered_add_comm_monoid, .. enat.order_top } end enat
8e66229b512fcbd3ad7136109458a216b0391f6e
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/ring/basic.lean
63876d521f26c45998b0bef2777fccd61334ccb8
[ "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
42,530
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.divisibility import data.set.basic /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option old_structure_cmd true open function /-! ### `distrib` class -/ /-- A typeclass stating that multiplication is left and right distributive over addition. -/ @[protect_proj, ancestor has_mul has_add] class distrib (R : Type*) extends has_mul R, has_add R := (left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul /-- Pullback a `distrib` instance along an injective function. -/ protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. -/ protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } /-! ### Semirings -/ /-- A semiring is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero` instead of `monoid` and `mul_zero_class`. -/ @[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib] class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α section semiring variables [semiring α] /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pushforward a `semiring` instance along a surjective function. -/ protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `∑ x in s, (f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = ite P a 0 * b := by { by_cases h : P; simp [h], } lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = a * ite P b 0 := by { by_cases h : P; simp [h], } /-- An element `a` of a semiring is even if there exists `k` such `a = 2*k`. -/ def even (a : α) : Prop := ∃ k, a = 2*k lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := iff.rfl @[simp] lemma range_two_mul (α : Type*) [semiring α] : set.range (λ x : α, 2 * x) = {a | even a} := by { ext x, simp [even, eq_comm] } /-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/ def odd (a : α) : Prop := ∃ k, a = 2*k + 1 @[simp] lemma range_two_mul_add_one (α : Type*) [semiring α] : set.range (λ x : α, 2 * x + 1) = {a | odd a} := by { ext x, simp [odd, eq_comm] } theorem dvd_add {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma coe_mul_right {R : Type*} [semiring R] (r : R) : ⇑(mul_right r) = (* r) := rfl lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : mul_right r a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. This extends from both `monoid_hom` and `monoid_with_zero_hom` in order to put the fields in a sensible order, even though `monoid_with_zero_hom` already extends `monoid_hom`. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β, monoid_with_zero_hom α β infixr ` →+* `:25 := ring_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a `monoid_with_zero_hom R S`. The `simp`-normal form is `(f : monoid_with_zero_hom R S)`. -/ add_decl_doc ring_hom.to_monoid_with_zero_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a monoid homomorphism `R →* S`. The `simp`-normal form is `(f : R →* S)`. -/ add_decl_doc ring_hom.to_monoid_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as an additive monoid homomorphism `R →+ S`. The `simp`-normal form is `(f : R →+ S)`. -/ add_decl_doc ring_hom.to_add_monoid_hom namespace ring_hom section coe /-! Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ variables {rα : semiring α} {rβ : semiring β} include rα rβ instance : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ initialize_simps_projections ring_hom (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl instance has_coe_monoid_hom : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp] lemma to_monoid_hom_eq_coe (f : α →+* β) : f.to_monoid_hom = f := rfl @[simp] lemma coe_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →* β) = ⟨f, h₁, h₂⟩ := rfl instance has_coe_add_monoid_hom : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_add_monoid_hom (f : α →+* β) : ⇑(f : α →+ β) = f := rfl @[simp] lemma to_add_monoid_hom_eq_coe (f : α →+* β) : f.to_add_monoid_hom = f := rfl @[simp] lemma coe_add_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →+ β) = ⟨f, h₃, h₄⟩ := rfl end coe variables [rα : semiring α] [rβ : semiring β] section include rα rβ variables (f : α →+* β) {x y : α} {rα rβ} theorem congr_fun {f g : α →+* β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →+* β, h x) h theorem congr_arg (f : α →+* β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma mk_coe (f : α →+* β) (h₁ h₂ h₃ h₄) : ring_hom.mk f h₁ h₂ h₃ h₄ = f := ext $ λ _, rfl theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, ext (λ x, add_monoid_hom.congr_fun h x) theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, ext (λ x, monoid_hom.congr_fun h x) /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b /-- Ring homomorphisms preserve `bit0`. -/ @[simp] lemma map_bit0 (f : α →+* β) (a : α) : f (bit0 a) = bit0 (f a) := map_add _ _ _ /-- Ring homomorphisms preserve `bit1`. -/ @[simp] lemma map_bit1 (f : α →+* β) (a : α) : f (bit1 a) = bit1 (f a) := by simp [bit1] /-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/ lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 := by rw [map_one, eq_comm] /-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/ lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) := f.codomain_trivial_iff_map_one_eq_zero.trans ⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩ /-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/ lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} := f.codomain_trivial_iff_range_trivial.trans ⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩), λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩ /-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/ lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 := mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one /-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/ lemma domain_nontrivial [nontrivial β] : nontrivial α := ⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩ lemma is_unit_map (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) := h.map (f.to_monoid_hom) end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα instance : inhabited (α →+* α) := ⟨id α⟩ @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom /-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). -/ @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α := { .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α } section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := by simp only [two_mul, add_mul, mul_add, add_assoc, mul_comm b] @[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩ lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ /-- A ring is a type with the following structures: additive commutative group (`add_comm_group`), multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a `semiring` with a negation operation making it an additive group. -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ @[priority 200] instance ring.to_semiring : semiring α := { zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0, by rw [← add_mul, zero_add, add_zero], mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0, by rw [← mul_add, add_zero, add_zero], ..‹ring α› } /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.injective.ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.surjective.ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := by simpa only [sub_eq_add_neg, neg_mul_eq_mul_neg] using mul_add a b (-c) alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := by simpa only [sub_eq_add_neg, neg_mul_eq_neg_mul] using add_mul a (-b) c alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl @[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [semiring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom /-- A commutative ring is a `ring` with commutative multiplication. -/ @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α @[priority 100] -- see Note [lower instance priority] instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `comm_ring` instance along an injective function. -/ protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.injective.comm_ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function. -/ protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.surjective.comm_ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul } local attribute [simp] add_assoc add_comm add_left_comm mul_comm theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) } theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] lemma mul_self_sub_one (a : α) : a * a - 1 = (a + 1) * (a - 1) := by rw [← mul_self_sub_mul_self, mul_one] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by simpa [sub_eq_add_neg] using h))) /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α, nontrivial α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) section domain variable [domain α] @[priority 100] -- see Note [lower instance priority] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] }, mul_right_cancel_of_ne_zero := λ a b c hb, by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] }, .. (infer_instance : semiring α) } /-- Pullback a `domain` instance along an injective function. -/ protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : domain β := { .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one, .. hf.no_zero_divisors f zero mul } end domain /-! ### Integral domains -/ /-- An integral domain is a commutative ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, an integral domain is a domain with commutative multiplication. -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} @[priority 100] -- see Note [lower instance priority] instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α := { ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero } /-- Pullback an `integral_domain` instance along an injective function. -/ protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : integral_domain β := { .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg } lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b := by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 := by rw [← mul_self_eq_mul_self_iff, one_mul] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff } /-- Makes a ring homomorphism from an additive group homomorphism from a commutative ring to an integral domain that commutes with self multiplication, assumes that two is nonzero and one is sent to one. -/ def add_monoid_hom.mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h : ∀ x, f (x * x) = f x * f x) (h_two : (2 : α) ≠ 0) (h_one : f 1 = 1) : β →+* α := { map_one' := h_one, map_mul' := begin intros x y, have hxy := h (x + y), rw [mul_add, add_mul, add_mul, f.map_add, f.map_add, f.map_add, f.map_add, h x, h y, add_mul, mul_add, mul_add, ← sub_eq_zero_iff_eq, add_comm, ← sub_sub, ← sub_sub, ← sub_sub, mul_comm y x, mul_comm (f y) (f x)] at hxy, simp only [add_assoc, add_sub_assoc, add_sub_cancel'_right] at hxy, rw [sub_sub, ← two_mul, ← add_sub_assoc, ← two_mul, ← mul_sub, mul_eq_zero, sub_eq_zero_iff_eq, or_iff_not_imp_left] at hxy, exact hxy h_two, end, ..f } @[simp] lemma add_monoid_hom.coe_fn_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h h_two h_one) : (f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β → α) = f := rfl @[simp] lemma add_monoid_hom.coe_add_monoid_hom_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h h_two h_one) : (f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β →+ α) = f := by {ext, simp} end integral_domain namespace ring variables {M₀ : Type*} [monoid_with_zero M₀] open_locale classical /-- Introduce a function `inverse` on a monoid with zero `M₀`, which sends `x` to `x⁻¹` if `x` is invertible and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. Note that while this is in the `ring` namespace for brevity, it requires the weaker assumption `monoid_with_zero M₀` instead of `ring M₀`. -/ noncomputable def inverse : M₀ → M₀ := λ x, if h : is_unit x then (((classical.some h)⁻¹ : units M₀) : M₀) else 0 /-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/ @[simp] lemma inverse_unit (u : units M₀) : inverse (u : M₀) = (u⁻¹ : units M₀) := begin simp only [is_unit_unit, inverse, dif_pos], exact units.inv_unique (classical.some_spec (is_unit_unit u)) end /-- By definition, if `x` is not invertible then `inverse x = 0`. -/ @[simp] lemma inverse_non_unit (x : M₀) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h end ring /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) -- The linter does not recognize that is_integral_domain.to_nontrivial is a structure -- projection, disable it attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
0ce2676f69921956180ccdaa6aad34039e0582bb
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/02_Dependent_Type_Theory.org.8.lean
9b1869539b13f0fb794cc8e35d55bf1a928797f3
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
785
lean
/- page 15 -/ import standard constants A B : Type check A -- A : Type check B -- B : Type check Type -- Type : Type check Type → Type -- Type → Type : Type set_option pp.universes true -- display universe information check A -- A.{l_1} : Type.{l_1} check B -- B.{l_1} : Type.{l_1} check Type -- Type.{l_1} : Type.{l_1 + 1} check Type → Type -- Type.{l_1} → Type.{l_2} : Type.{imax (l_1+1) (l_2+1)} universe u constant C : Type.{u} check C -- C : Type.{u} check A → C -- A.{l_1} → C : Type.{imax l_1 u} universe variable v constants D E : Type check D → E -- D.{l_1} → E.{l_2} : Type.{imax l_1 l_2} check D.{v} → E.{v} -- D.{v} → E.{v} : Type.{v}
eec88da4af77d6c1d42b0d3a41d3b29f61c1fa99
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/category/applicative.lean
812b58f0d1c68ff3146278b597dd3db51e91d982
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
4,929
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Instances for identity and composition functors -/ import category.functor universe variables u v w section lemmas open function variables {F : Type u → Type v} variables [applicative F] [is_lawful_applicative F] variables {α β γ σ : Type u} attribute [functor_norm] seq_assoc pure_seq_eq_map map_pure seq_map_assoc map_seq lemma applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) : (f <$> x) <*> (g <$> y) = (flip (∘) g ∘ f) <$> x <*> y := by simp [flip] with functor_norm lemma applicative.pure_seq_eq_map' (f : α → β) : (<*>) (pure f : F (α → β)) = (<$>) f := by ext; simp with functor_norm theorem applicative.ext {F} : ∀ {A1 : applicative F} {A2 : applicative F} [@is_lawful_applicative F A1] [@is_lawful_applicative F A2] (H1 : ∀ {α : Type u} (x : α), @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x) (H2 : ∀ {α β : Type u} (f : F (α → β)) (x : F α), @has_seq.seq _ A1.to_has_seq _ _ f x = @has_seq.seq _ A2.to_has_seq _ _ f x), A1 = A2 | {to_functor := F1, seq := s1, pure := p1, seq_left := sl1, seq_right := sr1} {to_functor := F2, seq := s2, pure := p2, seq_left := sl2, seq_right := sr2} L1 L2 H1 H2 := begin have : @p1 = @p2, {funext α x, apply H1}, subst this, have : @s1 = @s2, {funext α β f x, apply H2}, subst this, cases L1, cases L2, have : F1 = F2, { resetI, apply functor.ext, intros, exact (L1_pure_seq_eq_map _ _).symm.trans (L2_pure_seq_eq_map _ _) }, subst this, congr; funext α β x y, { exact (L1_seq_left_eq _ _).trans (L2_seq_left_eq _ _).symm }, { exact (L1_seq_right_eq _ _).trans (L2_seq_right_eq _ _).symm } end end lemmas instance : is_comm_applicative id := by refine { .. }; intros; refl namespace comp open function (hiding comp) open functor variables {F : Type u → Type w} {G : Type v → Type u} variables [applicative F] [applicative G] protected def seq {α β : Type v} : comp F G (α → β) → comp F G α → comp F G β | (comp.mk f) (comp.mk x) := comp.mk $ (<*>) <$> f <*> x instance : has_pure (comp F G) := ⟨λ _ x, comp.mk $ pure $ pure x⟩ instance : has_seq (comp F G) := ⟨λ _ _ f x, comp.seq f x⟩ @[simp] protected lemma run_pure {α : Type v} : ∀ x : α, (pure x : comp F G α).run = pure (pure x) | _ := rfl @[simp] protected lemma run_seq {α β : Type v} (f : comp F G (α → β)) (x : comp F G α) : (f <*> x).run = (<*>) <$> f.run <*> x.run := rfl instance : applicative (comp F G) := { map := @comp.map F G _ _, seq := @comp.seq F G _ _, ..comp.has_pure } variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type v} lemma map_pure (f : α → β) (x : α) : (f <$> pure x : comp F G β) = pure (f x) := comp.ext $ by simp lemma seq_pure (f : comp F G (α → β)) (x : α) : f <*> pure x = (λ g : α → β, g x) <$> f := comp.ext $ by simp [(∘)] with functor_norm lemma seq_assoc (x : comp F G α) (f : comp F G (α → β)) (g : comp F G (β → γ)) : g <*> (f <*> x) = (@function.comp α β γ <$> g) <*> f <*> x := comp.ext $ by simp [(∘)] with functor_norm lemma pure_seq_eq_map (f : α → β) (x : comp F G α) : pure f <*> x = f <$> x := comp.ext $ by simp [applicative.pure_seq_eq_map'] with functor_norm instance : is_lawful_applicative (comp F G) := { pure_seq_eq_map := @comp.pure_seq_eq_map F G _ _ _ _, map_pure := @comp.map_pure F G _ _ _ _, seq_pure := @comp.seq_pure F G _ _ _ _, seq_assoc := @comp.seq_assoc F G _ _ _ _ } theorem applicative_id_comp {F} [AF : applicative F] [LF : is_lawful_applicative F] : @comp.applicative id F _ _ = AF := @applicative.ext F _ _ (@comp.is_lawful_applicative id F _ _ _ _) _ (λ α x, rfl) (λ α β f x, rfl) theorem applicative_comp_id {F} [AF : applicative F] [LF : is_lawful_applicative F] : @comp.applicative F id _ _ = AF := @applicative.ext F _ _ (@comp.is_lawful_applicative F id _ _ _ _) _ (λ α x, rfl) (λ α β f x, show id <$> f <*> x = f <*> x, by rw id_map) open is_comm_applicative instance {f : Type u → Type w} {g : Type v → Type u} [applicative f] [applicative g] [is_comm_applicative f] [is_comm_applicative g] : is_comm_applicative (comp f g) := by { refine { .. @comp.is_lawful_applicative f g _ _ _ _, .. }, intros, casesm* comp _ _ _, simp! [map,has_seq.seq] with functor_norm, rw [commutative_map], simp [comp.mk,flip,(∘)] with functor_norm, congr, funext, rw [commutative_map], congr } end comp open functor @[functor_norm] lemma comp.seq_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [applicative f] [applicative g] (h : f (g (α → β))) (x : f (g α)) : comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl
f3c7e3bcbc39f2be8bb5d648b248d20aa85833af
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/plugin/PapyrusPlugin.lean
e1fbe5fafaf560d78ce1a480d6e3f8800a6aeb54
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15
lean
import Papyrus
501d72eb9266190c0366f4c56e3b7e05dd5cf4cf
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/norm_swap.lean
d6dd9aa727c7e81691dd09fa1e284b22a58570a2
[ "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,098
lean
/- Copyright (c) 2021 Yakov Pechersky All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import logic.equiv.defs import tactic.norm_fin /-! # `norm_swap` Evaluating `swap x y z` for numerals `x y z` that are `ℕ`, `ℤ`, or `ℚ`, via a `norm_num` plugin. Terms are passed to `eval`, quickly failing if not of the form `swap x y z`. The expressions for numerals `x y z` are converted to `nat`, and then compared. Based on equality of these `nat`s, equality proofs are generated using either `equiv.swap_apply_left`, `equiv.swap_apply_right`, or `swap_apply_of_ne_of_ne`. -/ open equiv tactic expr open norm_num namespace norm_swap /-- A `norm_num` plugin for normalizing `equiv.swap a b c` where `a b c` are numerals of `ℕ`, `ℤ`, `ℚ` or `fin n`. ``` example : equiv.swap 1 2 1 = 2 := by norm_num ``` -/ @[norm_num] meta def eval : expr → tactic (expr × expr) := λ e, do (swapt, fun_ty, coe_fn_inst, fexpr, c) ← e.match_app_coe_fn <|> fail "did not get an app coe_fn expr", guard (fexpr.get_app_fn.const_name = ``equiv.swap) <|> fail "coe_fn not of equiv.swap", [α, deceq_inst, a, b] ← pure fexpr.get_app_args <|> fail "swap did not have exactly two args applied", na ← a.to_rat <|> (do (fa, _) ← norm_fin.eval_fin_num a, fa.to_rat), nb ← b.to_rat <|> (do (fb, _) ← norm_fin.eval_fin_num b, fb.to_rat), nc ← c.to_rat <|> (do (fc, _) ← norm_fin.eval_fin_num c, fc.to_rat), if nc = na then do p ← mk_mapp `equiv.swap_apply_left [α, deceq_inst, a, b], pure (b, p) else if nc = nb then do p ← mk_mapp `equiv.swap_apply_right [α, deceq_inst, a, b], pure (a, p) else do nic ← mk_instance_cache α, hca ← (prod.snd <$> prove_ne nic c a nc na) <|> (do (_, ff, p) ← norm_fin.prove_eq_ne_fin c a, pure p), hcb ← (prod.snd <$> prove_ne nic c b nc nb) <|> (do (_, ff, p) ← norm_fin.prove_eq_ne_fin c b, pure p), p ← mk_mapp `equiv.swap_apply_of_ne_of_ne [α, deceq_inst, a, b, c, hca, hcb], pure (c, p) end norm_swap
7e16ad6dab6c3eaf5e32a0ce551cfa0b2fbf1e9b
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_geometry/Scheme.lean
f05f267c286d195b2ce9b8d4eaa9863d81d555aa
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
9,528
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 algebraic_geometry.Spec /-! # The category of schemes A scheme is a locally ringed space such that every point is contained in some open set where there is an isomorphism of presheaves between the restriction to that open set, and the structure sheaf of `Spec R`, for some commutative ring `R`. A morphism of schemes is just a morphism of the underlying locally ringed spaces. -/ noncomputable theory open topological_space open category_theory open Top open opposite namespace algebraic_geometry /-- We define `Scheme` as a `X : LocallyRingedSpace`, along with a proof that every point has an open neighbourhood `U` so that that the restriction of `X` to `U` is isomorphic, as a locally ringed space, to `Spec.to_LocallyRingedSpace.obj (op R)` for some `R : CommRing`. -/ structure Scheme extends to_LocallyRingedSpace : LocallyRingedSpace := (local_affine : ∀ x : to_LocallyRingedSpace, ∃ (U : open_nhds x) (R : CommRing), nonempty (to_LocallyRingedSpace.restrict U.open_embedding ≅ Spec.to_LocallyRingedSpace.obj (op R))) namespace Scheme /-- Schemes are a full subcategory of locally ringed spaces. -/ instance : category Scheme := induced_category.category Scheme.to_LocallyRingedSpace /-- The structure sheaf of a Scheme. -/ protected abbreviation sheaf (X : Scheme) := X.to_SheafedSpace.sheaf /-- The forgetful functor from `Scheme` to `LocallyRingedSpace`. -/ @[simps, derive[full, faithful]] def forget_to_LocallyRingedSpace : Scheme ⥤ LocallyRingedSpace := induced_functor _ @[simp] lemma forget_to_LocallyRingedSpace_preimage {X Y : Scheme} (f : X ⟶ Y) : Scheme.forget_to_LocallyRingedSpace.preimage f = f := rfl /-- The forgetful functor from `Scheme` to `Top`. -/ @[simps] def forget_to_Top : Scheme ⥤ Top := Scheme.forget_to_LocallyRingedSpace ⋙ LocallyRingedSpace.forget_to_Top instance {X Y : Scheme} : has_lift_t (X ⟶ Y) (X.to_SheafedSpace ⟶ Y.to_SheafedSpace) := (@@coe_to_lift $ @@coe_base coe_subtype) lemma id_val_base (X : Scheme) : (subtype.val (𝟙 X)).base = 𝟙 _ := rfl @[simp] lemma id_coe_base (X : Scheme) : (↑(𝟙 X) : X.to_SheafedSpace ⟶ X.to_SheafedSpace).base = 𝟙 _ := rfl @[simp] lemma id_app {X : Scheme} (U : (opens X.carrier)ᵒᵖ) : (subtype.val (𝟙 X)).c.app U = X.presheaf.map (eq_to_hom (by { induction U using opposite.rec, cases U, refl })) := PresheafedSpace.id_c_app X.to_PresheafedSpace U @[reassoc] lemma comp_val {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val = f.val ≫ g.val := rfl @[reassoc, simp] lemma comp_coe_base {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) : (↑(f ≫ g) : X.to_SheafedSpace ⟶ Z.to_SheafedSpace).base = f.val.base ≫ g.val.base := rfl @[reassoc, elementwise] lemma comp_val_base {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val.base = f.val.base ≫ g.val.base := rfl @[reassoc, simp] lemma comp_val_c_app {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (f ≫ g).val.c.app U = g.val.c.app U ≫ f.val.c.app _ := rfl lemma congr_app {X Y : Scheme} {f g : X ⟶ Y} (e : f = g) (U) : f.val.c.app U = g.val.c.app U ≫ X.presheaf.map (eq_to_hom (by subst e)) := by { subst e, dsimp, simp } lemma app_eq {X Y : Scheme} (f : X ⟶ Y) {U V : opens Y.carrier} (e : U = V) : f.val.c.app (op U) = Y.presheaf.map (eq_to_hom e.symm).op ≫ f.val.c.app (op V) ≫ X.presheaf.map (eq_to_hom (congr_arg (opens.map f.val.base).obj e)).op := begin rw [← is_iso.inv_comp_eq, ← functor.map_inv, f.val.c.naturality, presheaf.pushforward_obj_map], congr end instance is_LocallyRingedSpace_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] : @is_iso LocallyRingedSpace _ _ _ f := forget_to_LocallyRingedSpace.map_is_iso f @[simp] lemma inv_val_c_app {X Y : Scheme} (f : X ⟶ Y) [is_iso f] (U : opens X.carrier) : (inv f).val.c.app (op U) = X.presheaf.map (eq_to_hom $ by { rw is_iso.hom_inv_id, ext1, refl } : (opens.map (f ≫ inv f).1.base).obj U ⟶ U).op ≫ inv (f.val.c.app (op $ (opens.map _).obj U)) := begin rw [is_iso.eq_comp_inv], erw ← Scheme.comp_val_c_app, rw [Scheme.congr_app (is_iso.hom_inv_id f), Scheme.id_app, ← functor.map_comp, eq_to_hom_trans, eq_to_hom_op], refl end /-- The spectrum of a commutative ring, as a scheme. -/ def Spec_obj (R : CommRing) : Scheme := { local_affine := λ x, ⟨⟨⊤, trivial⟩, R, ⟨(Spec.to_LocallyRingedSpace.obj (op R)).restrict_top_iso⟩⟩, to_LocallyRingedSpace := Spec.LocallyRingedSpace_obj R } @[simp] lemma Spec_obj_to_LocallyRingedSpace (R : CommRing) : (Spec_obj R).to_LocallyRingedSpace = Spec.LocallyRingedSpace_obj R := rfl /-- The induced map of a ring homomorphism on the ring spectra, as a morphism of schemes. -/ def Spec_map {R S : CommRing} (f : R ⟶ S) : Spec_obj S ⟶ Spec_obj R := (Spec.LocallyRingedSpace_map f : Spec.LocallyRingedSpace_obj S ⟶ Spec.LocallyRingedSpace_obj R) @[simp] lemma Spec_map_id (R : CommRing) : Spec_map (𝟙 R) = 𝟙 (Spec_obj R) := Spec.LocallyRingedSpace_map_id R lemma Spec_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) : Spec_map (f ≫ g) = Spec_map g ≫ Spec_map f := Spec.LocallyRingedSpace_map_comp f g /-- The spectrum, as a contravariant functor from commutative rings to schemes. -/ @[simps] def Spec : CommRingᵒᵖ ⥤ Scheme := { obj := λ R, Spec_obj (unop R), map := λ R S f, Spec_map f.unop, map_id' := λ R, by rw [unop_id, Spec_map_id], map_comp' := λ R S T f g, by rw [unop_comp, Spec_map_comp] } /-- The empty scheme, as `Spec 0`. -/ def empty : Scheme := Spec_obj (CommRing.of punit) instance : has_emptyc Scheme := ⟨empty⟩ instance : inhabited Scheme := ⟨∅⟩ /-- The global sections, notated Gamma. -/ def Γ : Schemeᵒᵖ ⥤ CommRing := (induced_functor Scheme.to_LocallyRingedSpace).op ⋙ LocallyRingedSpace.Γ lemma Γ_def : Γ = (induced_functor Scheme.to_LocallyRingedSpace).op ⋙ LocallyRingedSpace.Γ := rfl @[simp] lemma Γ_obj (X : Schemeᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl lemma Γ_obj_op (X : Scheme) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl @[simp] lemma Γ_map {X Y : Schemeᵒᵖ} (f : X ⟶ Y) : Γ.map f = f.unop.1.c.app (op ⊤) := rfl lemma Γ_map_op {X Y : Scheme} (f : X ⟶ Y) : Γ.map f.op = f.1.c.app (op ⊤) := rfl section basic_open variables (X : Scheme) {V U : opens X.carrier} (f g : X.presheaf.obj (op U)) /-- The subset of the underlying space where the given section does not vanish. -/ def basic_open : opens X.carrier := X.to_LocallyRingedSpace.to_RingedSpace.basic_open f @[simp] lemma mem_basic_open (x : U) : ↑x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ x f) := RingedSpace.mem_basic_open _ _ _ @[simp] lemma mem_basic_open_top (f : X.presheaf.obj (op ⊤)) (x : X.carrier) : x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ (⟨x, trivial⟩ : (⊤ : opens _)) f) := RingedSpace.mem_basic_open _ f ⟨x, trivial⟩ @[simp] lemma basic_open_res (i : op U ⟶ op V) : X.basic_open (X.presheaf.map i f) = V ∩ X.basic_open f := RingedSpace.basic_open_res _ i f -- This should fire before `basic_open_res`. @[simp, priority 1100] lemma basic_open_res_eq (i : op U ⟶ op V) [is_iso i] : X.basic_open (X.presheaf.map i f) = X.basic_open f := RingedSpace.basic_open_res_eq _ i f lemma basic_open_subset : X.basic_open f ⊆ U := RingedSpace.basic_open_subset _ _ lemma preimage_basic_open {X Y : Scheme} (f : X ⟶ Y) {U : opens Y.carrier} (r : Y.presheaf.obj $ op U) : (opens.map f.1.base).obj (Y.basic_open r) = @Scheme.basic_open X ((opens.map f.1.base).obj U) (f.1.c.app _ r) := LocallyRingedSpace.preimage_basic_open f r @[simp] lemma preimage_basic_open' {X Y : Scheme} (f : X ⟶ Y) {U : opens Y.carrier} (r : Y.presheaf.obj $ op U) : (opens.map (↑f : X.to_SheafedSpace ⟶ Y.to_SheafedSpace).base).obj (Y.basic_open r) = @Scheme.basic_open X ((opens.map f.1.base).obj U) (f.1.c.app _ r) := LocallyRingedSpace.preimage_basic_open f r @[simp] lemma basic_open_zero (U : opens X.carrier) : X.basic_open (0 : X.presheaf.obj $ op U) = ∅ := LocallyRingedSpace.basic_open_zero _ U @[simp] lemma basic_open_mul : X.basic_open (f * g) = X.basic_open f ⊓ X.basic_open g := RingedSpace.basic_open_mul _ _ _ @[simp] lemma basic_open_of_is_unit {f : X.presheaf.obj (op U)} (hf : is_unit f) : X.basic_open f = U := RingedSpace.basic_open_of_is_unit _ hf end basic_open end Scheme lemma basic_open_eq_of_affine {R : CommRing} (f : R) : (Scheme.Spec.obj $ op R).basic_open ((Spec_Γ_identity.app R).inv f) = prime_spectrum.basic_open f := begin ext, erw Scheme.mem_basic_open_top, suffices : is_unit (structure_sheaf.to_stalk R x f) ↔ f ∉ prime_spectrum.as_ideal x, { exact this }, erw [← is_unit_map_iff (structure_sheaf.stalk_to_fiber_ring_hom R x), structure_sheaf.stalk_to_fiber_ring_hom_to_stalk], exact (is_localization.at_prime.is_unit_to_map_iff (localization.at_prime (prime_spectrum.as_ideal x)) (prime_spectrum.as_ideal x) f : _) end @[simp] lemma basic_open_eq_of_affine' {R : CommRing} (f : (Spec.to_SheafedSpace.obj (op R)).presheaf.obj (op ⊤)) : (Scheme.Spec.obj $ op R).basic_open f = prime_spectrum.basic_open ((Spec_Γ_identity.app R).hom f) := begin convert basic_open_eq_of_affine ((Spec_Γ_identity.app R).hom f), exact (coe_hom_inv_id _ _).symm end end algebraic_geometry
05f96a0bf03bffe5139c0706b1b1e885e409b3bd
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/algebra/uniform_group.lean
850759ec45d6b1bc139c36b45e20b4f494c6f7a1
[ "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
19,650
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 filter 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], 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) /-- The right uniformity on a topological group. -/ 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_zero_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`. -/ /-- `ℤ`-bilinearity for maps between additive commutative groups. -/ 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₁)) (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)) ((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)) ((comap ee (𝓝 (x₀, x₀))) ×ᶠ (comap ff (𝓝 (y₀, y₀)))) (𝓝 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_zero_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 := ((de.comap_nhds_ne_bot _).nonempty_of_mem U₁_nhd), obtain ⟨y₁, y₁_in⟩ : V₁.nonempty := ((df.comap_nhds_ne_bot _).nonempty_of_mem 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 ne_bot.map, 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))) (𝓝 (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
2fff0c7c57d4f16cb46bf60380521c8e40f8e840
46125763b4dbf50619e8846a1371029346f4c3db
/src/measure_theory/decomposition.lean
3ac07f7373b90693130dbdfab14a0344475d54d3
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
8,673
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Hahn decomposition theorem TODO: * introduce finite measures (into nnreal) * show general for signed measures (into ℝ) -/ import measure_theory.measure_space open set lattice filter open_locale classical topological_space namespace measure_theory variables {α : Type*} [measurable_space α] {μ ν : measure α} -- suddenly this is necessary?! private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) : γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d := by linarith lemma hahn_decomposition (hμ : μ univ < ⊤) (hν : ν univ < ⊤) : ∃s, is_measurable s ∧ (∀t, is_measurable t → t ⊆ s → ν t ≤ μ t) ∧ (∀t, is_measurable t → t ⊆ - s → μ t ≤ ν t) := begin let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal, let c : set ℝ := d '' {s | is_measurable s }, let γ : ℝ := Sup c, have hμ : ∀s, μ s < ⊤ := assume s, lt_of_le_of_lt (measure_mono $ subset_univ _) hμ, have hν : ∀s, ν s < ⊤ := assume s, lt_of_le_of_lt (measure_mono $ subset_univ _) hν, have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ennreal) = μ s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hμ _), have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ennreal) = ν s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hν _), have d_empty : d ∅ = 0, { simp [d], rw [measure_empty, measure_empty], simp }, have d_split : ∀s t, is_measurable s → is_measurable t → d s = d (s \ t) + d (s ∩ t), { assume s t hs ht, simp only [d], rw [measure_eq_inter_diff hs ht, measure_eq_inter_diff hs ht, ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _), nnreal.coe_add, nnreal.coe_add], simp only [sub_eq_add_neg, neg_add], ac_refl }, have d_Union : ∀(s : ℕ → set α), (∀n, is_measurable (s n)) → monotone s → tendsto (λn, d (s n)) at_top (𝓝 (d (⋃n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ⊤ _).comp $ tendsto_measure_Union hs hm), exact hμ _, exact hν _ }, have d_Inter : ∀(s : ℕ → set α), (∀n, is_measurable (s n)) → (∀n m, n ≤ m → s m ⊆ s n) → tendsto (λn, d (s n)) at_top (𝓝 (d (⋂n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ⊤ _).comp $ tendsto_measure_Inter hs hm _), exact hμ _, exact ⟨0, hμ _⟩, exact hν _, exact ⟨0, hν _⟩ }, have bdd_c : bdd_above c, { use (μ univ).to_nnreal, rintros r ⟨s, hs, rfl⟩, refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _, rw [nnreal.coe_le, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ], exact measure_mono (subset_univ _) }, have c_nonempty : c.nonempty := nonempty.image _ ⟨_, is_measurable.empty⟩, have d_le_γ : ∀s, is_measurable s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩, have : ∀n:ℕ, ∃s : set α, is_measurable s ∧ γ - (1/2)^n < d s, { assume n, have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n), rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩, exact ⟨s, hs, hlt⟩ }, rcases classical.axiom_of_choice this with ⟨e, he⟩, change ℕ → set α at e, have he₁ : ∀n, is_measurable (e n) := assume n, (he n).1, have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2, let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e, have hf : ∀n m, is_measurable (f n m), { assume n m, simp only [f, finset.inf_eq_infi], exact is_measurable.bInter (countable_encodable _) (assume i _, he₁ _) }, have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c, { assume a b c d hab hcd, dsimp only [f], rw [finset.inf_eq_infi, finset.inf_eq_infi], refine bInter_subset_bInter_left _, simp, rintros j ⟨hbj, hjc⟩, exact ⟨le_trans hab hbj, lt_of_lt_of_le hjc $ add_le_add_right hcd 1⟩ }, have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1), { assume n m hnm, have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm), simp only [f], rw [finset.Ico.succ_top this, finset.inf_insert, set.inter_comm], refl }, have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n), { assume n m h, refine nat.le_induction _ _ n h, { have := he₂ m, simp only [f], rw [finset.Ico.succ_singleton, finset.inf_singleton], exact aux this }, { assume n (hmn : m ≤ n) ih, have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)), { calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤ γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) : begin refine add_le_add_left (add_le_add_left _ _) γ, simp only [pow_add, pow_one, le_sub_iff_add_le], linarith end ... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) : by simp only [sub_eq_add_neg]; ac_refl ... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih ... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) : by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc] ... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) : begin rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)), union_diff_left, union_inter_cancel_left], ac_refl, exact (he₁ _).union (hf _ _), exact (he₁ _) end ... ≤ γ + d (f m (n + 1)) : add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ }, exact (add_le_add_iff_left γ).1 this } }, let s := ⋃ m, ⋂n, f m n, have γ_le_d_s : γ ≤ d s, { have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 γ), { suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 (γ - 2 * 0)), { simpa }, exact (tendsto_const_nhds.sub $ tendsto_const_nhds.mul $ tendsto_pow_at_top_nhds_0_of_lt_1 (le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) }, have hd : tendsto (λm, d (⋂n, f m n)) at_top (𝓝 (d (⋃ m, ⋂ n, f m n))), { refine d_Union _ _ _, { assume n, exact is_measurable.Inter (assume m, hf _ _) }, { exact assume n m hnm, subset_Inter (assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } }, refine le_of_tendsto_of_tendsto (@at_top_ne_bot ℕ _ _) hγ hd (univ_mem_sets' $ assume m, _), change γ - 2 * (1 / 2) ^ m ≤ d (⋂ (n : ℕ), f m n), have : tendsto (λn, d (f m n)) at_top (𝓝 (d (⋂ n, f m n))), { refine d_Inter _ _ _, { assume n, exact hf _ _ }, { assume n m hnm, exact f_subset_f (le_refl _) hnm } }, refine ge_of_tendsto (@at_top_ne_bot ℕ _ _) this (mem_at_top_sets.2 ⟨m, assume n hmn, _⟩), change γ - 2 * (1 / 2) ^ m ≤ d (f m n), refine le_trans _ (le_d_f _ _ hmn), exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) }, have hs : is_measurable s := is_measurable.Union (assume n, is_measurable.Inter (assume m, hf _ _)), refine ⟨s, hs, _, _⟩, { assume t ht hts, have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $ calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s ... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts] ... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le], simpa only [d, le_sub_iff_add_le, zero_add] using this }, { assume t ht hts, have : d t ≤ 0, exact ((add_le_add_iff_left γ).1 $ calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _) ... = d (s ∪ t) : begin rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right, diff_eq_self.2], exact assume a ⟨hat, has⟩, hts hat has end ... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le], simpa only [d, sub_le_iff_le_add, zero_add] using this } end end measure_theory
eaba90b4d74d2c21781d35390f3032b0c3f0fa78
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/control/equiv_functor.lean
bf80dc9194bb224009477e453e70f692232f4126
[ "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
3,448
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 logic.equiv.defs /-! # Functions functorial with respect to equivalences > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/649 > Any changes to this file require a corresponding PR to mathlib4. An `equiv_functor` is a function from `Type → Type` equipped with the additional data of coherently mapping equivalences to equivalences. In categorical language, it is an endofunctor of the "core" of the category `Type`. -/ universes u₀ u₁ u₂ v₀ v₁ v₂ open function /-- An `equiv_functor` is only functorial with respect to equivalences. To construct an `equiv_functor`, it suffices to supply just the function `f α → f β` from an equivalence `α ≃ β`, and then prove the functor laws. It's then a consequence that this function is part of an equivalence, provided by `equiv_functor.map_equiv`. -/ class equiv_functor (f : Type u₀ → Type u₁) := (map : Π {α β}, (α ≃ β) → (f α → f β)) (map_refl' : Π α, map (equiv.refl α) = @id (f α) . obviously) (map_trans' : Π {α β γ} (k : α ≃ β) (h : β ≃ γ), map (k.trans h) = (map h) ∘ (map k) . obviously) restate_axiom equiv_functor.map_refl' restate_axiom equiv_functor.map_trans' attribute [simp] equiv_functor.map_refl namespace equiv_functor section variables (f : Type u₀ → Type u₁) [equiv_functor f] {α β : Type u₀} (e : α ≃ β) /-- An `equiv_functor` in fact takes every equiv to an equiv. -/ def map_equiv : f α ≃ f β := { to_fun := equiv_functor.map e, inv_fun := equiv_functor.map e.symm, left_inv := λ x, by { convert (congr_fun (equiv_functor.map_trans e e.symm) x).symm, simp, }, right_inv := λ y, by { convert (congr_fun (equiv_functor.map_trans e.symm e) y).symm, simp, }, } @[simp] lemma map_equiv_apply (x : f α) : map_equiv f e x = equiv_functor.map e x := rfl lemma map_equiv_symm_apply (y : f β) : (map_equiv f e).symm y = equiv_functor.map e.symm y := rfl @[simp] lemma map_equiv_refl (α) : map_equiv f (equiv.refl α) = equiv.refl (f α) := by simpa [equiv_functor.map_equiv] @[simp] lemma map_equiv_symm : (map_equiv f e).symm = map_equiv f e.symm := equiv.ext $ map_equiv_symm_apply f e /-- The composition of `map_equiv`s is carried over the `equiv_functor`. For plain `functor`s, this lemma is named `map_map` when applied or `map_comp_map` when not applied. -/ @[simp] lemma map_equiv_trans {γ : Type u₀} (ab : α ≃ β) (bc : β ≃ γ) : (map_equiv f ab).trans (map_equiv f bc) = map_equiv f (ab.trans bc) := equiv.ext $ λ x, by simp [map_equiv, map_trans'] end @[priority 100] instance of_is_lawful_functor (f : Type u₀ → Type u₁) [functor f] [is_lawful_functor f] : equiv_functor f := { map := λ α β e, functor.map e, map_refl' := λ α, by { ext, apply is_lawful_functor.id_map, }, map_trans' := λ α β γ k h, by { ext x, apply (is_lawful_functor.comp_map k h x), } } lemma map_equiv.injective (f : Type u₀ → Type u₁) [applicative f] [is_lawful_applicative f] {α β : Type u₀} (h : ∀ γ, function.injective (pure : γ → f γ)) : function.injective (@equiv_functor.map_equiv f _ α β) := λ e₁ e₂ H, equiv.ext $ λ x, h β (by simpa [equiv_functor.map] using equiv.congr_fun H (pure x)) end equiv_functor
e0ae96ccd70372d49585238d6ff830dbf73f7ca8
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/lean/json.lean
319cae4e5ee7292f30367f6e2f248131bf48bff2
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
605
lean
import Init.Lean.Data.Json.Parser import Init.Lean.Data.Json.Printer def test (s : String) : String := match Lean.Json.parse s with | Except.ok res => toString res | Except.error err => err #eval test "null" #eval test "false" #eval test "true" #eval test "123.456e-7" #eval test "-0.01e8" #eval test "\"\"" #eval test "\"abc\"" #eval test "[true, 123, \"foo\", []]" #eval test "{\"a\": 1.2, \"b\": \"foo\", \"c\": null, \"d\": {\"foo\": \"bar\"}, \"e\": [{}]}" #eval test "[false_]" #eval test "[" #eval test "]" #eval test "{" #eval test "\"" #eval test "1." #eval test "{foo: 1}" #eval test " "
6bb376cc0286ffb171818d55aab207f0039a0bcd
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/ideal/basic.lean
b4a03c6b8d82367e332bfc33d75d51f6d3e5254b
[ "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
24,737
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.atoms import order.compactly_generated import tactic.abel import data.nat.choose.sum import linear_algebra.finsupp /-! # Ideals over a ring This file defines `ideal R`, the type of (left) ideals over a ring `R`. Note that over commutative rings, left ideals and two-sided ideals are equivalent. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support right ideals, and two-sided ideals over non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators pointwise /-- A (left) ideal in a semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [semiring R] := submodule R R section semiring namespace ideal variables [semiring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem variables (a) lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem a variables {a} @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h lemma sum_mem (I : ideal α) {ι : Type*} {t : finset ι} {f : ι → α} : (∀c∈t, f c ∈ I) → (∑ i in t, f i) ∈ I := submodule.sum_mem I theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := h.exists_left_inv in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := hy.exists_left_inv, have := I.mul_mem_left y' h, rwa [← mul_assoc, hy', one_mul] at this, end /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s @[simp] lemma submodule_span_eq {s : set α} : submodule.span α s = ideal.span s := rfl @[simp] lemma span_empty : span (∅ : set α) = ⊥ := submodule.span_empty @[simp] lemma span_univ : span (set.univ : set α) = ⊤ := submodule.span_univ lemma span_union (s t : set α) : span (s ∪ t) = span s ⊔ span t := submodule.span_union _ _ lemma span_Union {ι} (s : ι → set α) : span (⋃ i, s i) = ⨆ i, span (s i) := submodule.span_Union _ lemma mem_span {s : set α} (x) : x ∈ span s ↔ ∀ p : ideal α, s ⊆ p → x ∈ p := mem_Inter₂ lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma span_singleton_le_iff_mem {x : α} : span {x} ≤ I ↔ x ∈ I := submodule.span_singleton_le_iff_mem _ _ lemma span_insert (x) (s : set α) : span (insert x s) = span ({x} : set α) ⊔ span s := submodule.span_insert x s lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot lemma span_singleton_ne_top {α : Type*} [comm_semiring α] {x : α} (hx : ¬ is_unit x) : ideal.span ({x} : set α) ≠ ⊤ := (ideal.ne_top_iff_one _).mpr $ λ h1, let ⟨y, hy⟩ := ideal.mem_span_singleton'.mp h1 in hx ⟨⟨x, y, mul_comm y x ▸ hy, hy⟩, rfl⟩ @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] @[simp] lemma span_one : span (1 : set α) = ⊤ := by rw [←set.singleton_one, span_singleton_one] lemma span_eq_top_iff_finite (s : set α) : span s = ⊤ ↔ ∃ s' : finset α, ↑s' ⊆ s ∧ span (s' : set α) = ⊤ := begin simp_rw eq_top_iff_one, exact ⟨submodule.mem_span_finite_of_mem_span, λ ⟨s', h₁, h₂⟩, span_mono h₁ h₂⟩ end lemma mem_span_singleton_sup {S : Type*} [comm_semiring S] {x y : S} {I : ideal S} : x ∈ ideal.span {y} ⊔ I ↔ ∃ (a : S) (b ∈ I), a * y + b = x := begin rw submodule.mem_sup, split, { rintro ⟨ya, hya, b, hb, rfl⟩, obtain ⟨a, rfl⟩ := mem_span_singleton'.mp hya, exact ⟨a, b, hb, rfl⟩ }, { rintro ⟨a, b, hb, rfl⟩, exact ⟨a * y, ideal.mem_span_singleton'.mpr ⟨a, rfl⟩, b, hb, rfl⟩ } end /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x + b = a } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ class is_prime (I : ideal α) : Prop := (ne_top' : I ≠ ⊤) (mem_or_mem' : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I) theorem is_prime_iff {I : ideal α} : is_prime I ↔ I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := ⟨λ h, ⟨h.1, λ _ _, h.2⟩, λ h, ⟨h.1, λ _ _, h.2⟩⟩ theorem is_prime.ne_top {I : ideal α} (hI : I.is_prime) : I ≠ ⊤ := hI.1 theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) {x y : α} : x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.mem_or_mem (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { rw pow_zero at H, exact (mt (eq_top_iff_one _).2 hI.1).elim H }, { rw pow_succ at H, exact or.cases_on (hI.mem_or_mem H) id ih } end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime_iff, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem lemma bot_prime {R : Type*} [ring R] [is_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ class is_maximal (I : ideal α) : Prop := (out : is_coatom I) theorem is_maximal_def {I : ideal α} : I.is_maximal ↔ is_coatom I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_maximal.ne_top {I : ideal α} (h : I.is_maximal) : I ≠ ⊤ := (is_maximal_def.1 h).1 theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := is_maximal_def.trans $ and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.1.2 _ h)⟩ instance : is_coatomic (ideal α) := begin apply complete_lattice.coatomic_of_top_compact, rw ←span_singleton_one, exact submodule.singleton_span_is_compact_element 1, end /-- **Krull's theorem**: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := let ⟨m, hm⟩ := (eq_top_or_exists_le_coatom I).resolve_left hI in ⟨m, ⟨⟨hm.1⟩, hm.2⟩⟩ variables (α) /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) bot_ne_top in ⟨I, hI⟩ variables {α} instance [nontrivial α] : nontrivial (ideal α) := begin rcases @exists_maximal α _ _ with ⟨M, hM, _⟩, exact nontrivial_of_ne M ⊤ hM end /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [semiring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, ∃ i ∈ I, y * x + i = 1 := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, z, hz, hy⟩, refine ⟨y, z, _, hy.symm⟩, rwa ← span_eq I, end section lattice variables {R : Type u} [semiring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Sort*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Sort*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, I.zero_mem, add_mem' := λ a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := λ a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl end pi lemma Inf_is_prime_of_is_chain {s : set (ideal α)} (hs : s.nonempty) (hs' : is_chain (≤) s) (H : ∀ p ∈ s, ideal.is_prime p) : (Inf s).is_prime := ⟨λ e, let ⟨x, hx⟩ := hs in (H x hx).ne_top (eq_top_iff.mpr (e.symm.trans_le (Inf_le hx))), λ x y e, or_iff_not_imp_left.mpr $ λ hx, begin rw ideal.mem_Inf at hx ⊢ e, push_neg at hx, obtain ⟨I, hI, hI'⟩ := hx, intros J hJ, cases hs'.total hI hJ, { exact h (((H I hI).mem_or_mem (e hI)).resolve_left hI') }, { exact ((H J hJ).mem_or_mem (e hJ)).resolve_left (λ x, hI' $ h x) }, end⟩ end ideal end semiring section comm_semiring variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different -- order. namespace ideal variables [comm_semiring α] (I : ideal α) @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [comm_ring α] [is_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime_iff, prime, span_singleton_eq_top, hp, mem_span_singleton] theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin let J : ideal α := submodule.span α (insert x ↑I), have IJ : I ≤ J := (set.subset.trans (subset_insert _ _) subset_span), have xJ : x ∈ J := ideal.subset_span (set.mem_insert x I), cases is_maximal_iff.1 H with _ oJ, specialize oJ J x IJ hx xJ, rcases submodule.mem_span_insert.mp oJ with ⟨a, b, h, oe⟩, obtain (F : y * 1 = y * (a • x + b)) := congr_arg (λ g : α, y * g) oe, rw [← mul_one y, F, mul_add, mul_comm, smul_eq_mul, mul_assoc], refine submodule.add_mem I (I.mul_mem_left a hxy) (submodule.smul_mem I y _), rwa submodule.span_eq at h, end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime lemma span_singleton_lt_span_singleton [comm_ring β] [is_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [comm_ring β] [is_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left b h variables {b} lemma pow_mem_of_mem (ha : a ∈ I) (n : ℕ) (hn : 0 < n) : a ^ n ∈ I := nat.cases_on n (not.elim dec_trivial) (λ m hm, (pow_succ a m).symm ▸ I.mul_mem_right (a^m) ha) hn theorem is_prime.mul_mem_iff_mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I ↔ x ∈ I ∨ y ∈ I := λ x y, ⟨hI.mem_or_mem, by { rintro (h | h), exacts [I.mul_mem_right y h, I.mul_mem_left x h] }⟩ theorem is_prime.pow_mem_iff_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (hn : 0 < n) : r ^ n ∈ I ↔ r ∈ I := ⟨hI.mem_of_pow_mem n, (λ hr, I.pow_mem_of_mem hr n hn)⟩ theorem pow_multiset_sum_mem_span_pow (s : multiset α) (n : ℕ) : s.sum ^ (s.card * n + 1) ∈ span ((s.map (λ x, x ^ (n + 1))).to_finset : set α) := begin induction s using multiset.induction_on with a s hs, { simp }, simp only [finset.coe_insert, multiset.map_cons, multiset.to_finset_cons, multiset.sum_cons, multiset.card_cons, add_pow], refine submodule.sum_mem _ _, intros c hc, rw mem_span_insert, by_cases h : n+1 ≤ c, { refine ⟨a ^ (c - (n + 1)) * s.sum ^ ((s.card + 1) * n + 1 - c) * (((s.card + 1) * n + 1).choose c), 0, submodule.zero_mem _, _⟩, rw mul_comm _ (a ^ (n + 1)), simp_rw ← mul_assoc, rw [← pow_add, add_zero, add_tsub_cancel_of_le h], }, { use 0, simp_rw [zero_mul, zero_add], refine ⟨_,_,rfl⟩, replace h : c ≤ n := nat.lt_succ_iff.mp (not_le.mp h), have : (s.card + 1) * n + 1 - c = s.card * n + 1 + (n - c), { rw [add_mul, one_mul, add_assoc, add_comm n 1, ← add_assoc, add_tsub_assoc_of_le h] }, rw [this, pow_add], simp_rw [mul_assoc, mul_comm (s.sum ^ (s.card * n + 1)), ← mul_assoc], exact mul_mem_left _ _ hs } end theorem sum_pow_mem_span_pow {ι} (s : finset ι) (f : ι → α) (n : ℕ) : (∑ i in s, f i) ^ (s.card * n + 1) ∈ span ((λ i, f i ^ (n + 1)) '' s) := begin convert pow_multiset_sum_mem_span_pow (s.1.map f) n, { rw multiset.card_map, refl }, rw [multiset.map_map, multiset.to_finset_map, finset.val_to_finset, finset.coe_image] end theorem span_pow_eq_top (s : set α) (hs : span s = ⊤) (n : ℕ) : span ((λ x, x ^ n) '' s) = ⊤ := begin rw eq_top_iff_one, cases n, { obtain rfl | ⟨x, hx⟩ := eq_empty_or_nonempty s, { rw [set.image_empty, hs], trivial }, { exact subset_span ⟨_, hx, pow_zero _⟩ } }, rw [eq_top_iff_one, span, finsupp.mem_span_iff_total] at hs, rcases hs with ⟨f, hf⟩, change f.support.sum (λ a, f a * a) = 1 at hf, have := sum_pow_mem_span_pow f.support (λ a, f a * a) n, rw [hf, one_pow] at this, refine (span_le).mpr _ this, rintros _ hx, simp_rw [finset.mem_coe, set.mem_image] at hx, rcases hx with ⟨x, hx, rfl⟩, have : span ({x ^ (n + 1)} : set α) ≤ span ((λ (x : α), x ^ (n + 1)) '' s), { rw [span_le, set.singleton_subset_iff], exact subset_span ⟨x, x.prop, rfl⟩ }, refine this _, rw [mul_pow, mem_span_singleton], exact ⟨f x ^ (n + 1), mul_comm _ _⟩ end end ideal end comm_semiring section ring namespace ideal variables [ring α] (I : ideal α) {a b : α} protected lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := neg_mem_iff protected lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left protected lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := sub_mem lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' end ideal end ring section division_ring variables {K : Type u} [division_ring K] (I : ideal K) namespace ideal /-- All ideals in a division ring are trivial. -/ lemma eq_bot_or_top : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end /-- Ideals of a `division_ring` are a simple order. Thanks to the way abbreviations work, this automatically gives a `is_simple_module K` instance. -/ instance : is_simple_order (ideal K) := ⟨eq_bot_or_top⟩ lemma eq_bot_of_prime [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal : is_maximal (⊥ : ideal K) := ⟨⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩⟩ end ideal end division_ring section comm_ring namespace ideal theorem mul_sub_mul_mem {R : Type*} [comm_ring R] (I : ideal R) {a b c d : R} (h1 : a - b ∈ I) (h2 : c - d ∈ I) : a * c - b * d ∈ I := begin rw (show a * c - b * d = (a - b) * c + b * (c - d), by {rw [sub_mul, mul_sub], abel}), exact I.add_mem (I.mul_mem_right _ h1) (I.mul_mem_left _ h2), end end ideal end comm_ring namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := set_like.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : ¬ is_field R) : M ≠ ⊥ := begin rintros h, rw h at max, rcases max with ⟨⟨h1, h2⟩⟩, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, { simp }, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.1.2 I Ibot at Itop, end end ideal variables {a b : α} /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [semiring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_semiring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end
48f7e32f66954497207072ba0748dd273cb954a0
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/two_category.lean
c849c053604f1fd0e54b7f7ba6b06a6a283bcf7c
[]
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
4,271
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 .natural_transformation open tqft.categories open tqft.categories.functor open tqft.categories.natural_transformation namespace tqft.categories.two_category universe variables u v w structure StrictTwoCategory := (_0 : Type u) (_1 : _0 → _0 → Type v) (_2 : Π { X Y : _0 }, _1 X Y → _1 X Y → Type w) (identity_0 : Π X : _0, _1 X X) (identity_1 : Π { X Y : _0 }, Π f : _1 X Y, _2 f f) (compose_1 : Π { X Y Z : _0 }, _1 X Y → _1 Y Z → _1 X Z) (compose_2_vertically : Π { X Y : _0 }, Π { f g h : _1 X Y }, _2 f g → _2 g h → _2 f h) (compose_2_horizontally : Π { X Y Z : _0 }, Π { f g : _1 X Y }, Π { h k : _1 Y Z }, _2 f g → _2 h k → _2 (compose_1 f h) (compose_1 g k) ) (left_identity : ∀ { X Y : _0 } (f : _1 X Y), compose_1 (identity_0 X) f = f) (right_identity : ∀ { X Y : _0 } (f : _1 X Y), compose_1 f (identity_0 Y) = f) (associativity_1 : ∀ { W X Y Z : _0 } (f : _1 W X) (g : _1 X Y) (h : _1 Y Z), compose_1 (compose_1 f g) h = compose_1 f (compose_1 g h)) (up_identity : ∀ { X Y : _0 } { f g : _1 X Y } ( α : _2 f g ), compose_2_vertically α (identity_1 g) = α) (down_identity : ∀ { X Y : _0 } { f g : _1 X Y } ( α : _2 f g ), compose_2_vertically (identity_1 f) α = α) (associativity_2_vertical : ∀ { X Y : _0 } { f g h k : _1 X Y } ( α : _2 f g ) ( β : _2 g h ) ( γ : _2 h k ), compose_2_vertically (compose_2_vertically α β) γ = compose_2_vertically α (compose_2_vertically β γ)) (associativity_2_horizontal : ∀ { W X Y Z : _0 } { f g : _1 W X } { h k : _1 X Y } { i j : _1 Y Z } ( α: _2 f g ) ( β : _2 h k ) ( γ : _2 i j ), compose_2_horizontally (compose_2_horizontally α β) γ = ⟦ compose_2_horizontally α (compose_2_horizontally β γ) ⟧) (interchange : ∀ { X Y Z : _0 } { f g h : _1 X Y } { i j k : _1 Y Z } ( α : _2 f g ) ( β : _2 i j ) ( γ : _2 g h ) ( δ : _2 j k ), compose_2_vertically (compose_2_horizontally α β) (compose_2_horizontally γ δ) = compose_2_horizontally (compose_2_vertically α γ) (compose_2_vertically β δ)) attribute [simp] StrictTwoCategory.left_identity StrictTwoCategory.right_identity StrictTwoCategory.up_identity StrictTwoCategory.down_identity attribute [ematch] StrictTwoCategory.associativity_1 StrictTwoCategory.associativity_2_vertical StrictTwoCategory.associativity_2_horizontal StrictTwoCategory.interchange definition CAT : StrictTwoCategory := { _0 := Category, _1 := λ C D, Functor C D, _2 := λ _ _ F G, NaturalTransformation F G, identity_0 := λ C, IdentityFunctor C, identity_1 := λ _ _ F, IdentityNaturalTransformation F, compose_1 := λ _ _ _ F G, FunctorComposition F G, compose_2_vertically := λ _ _ _ _ _ α β, vertical_composition_of_NaturalTransformations α β, compose_2_horizontally := λ _ _ _ _ _ _ _ α β, horizontal_composition_of_NaturalTransformations α β, left_identity := ♯, right_identity := ♯, associativity_1 := ♮, up_identity := ♯, down_identity := ♯, associativity_2_vertical := ♯, associativity_2_horizontal := ♯, interchange := ♯ } definition HomCategory ( C : StrictTwoCategory ) ( X Y : C._0 ) : Category := { Obj := C._1 X Y, Hom := λ f g, C._2 f g, identity := λ f, C.identity_1 f, compose := λ _ _ _ α β, C.compose_2_vertically α β, left_identity := ♮, right_identity := ♮, associativity := ♮ } -- PROJECT show that HomCategory C X X is (strict) monoidal? structure DualMorphisms { C : StrictTwoCategory } { X Y : C._0 } ( f : C._1 X Y ) ( g : C._1 Y X ) := ( unit : C._2 (C.compose_1 f g) (C.identity_0 X) ) ( counit : C._2 (C.identity_0 Y) (C.compose_1 g f) ) -- TODO we need to rewrite along associativity_1 -- ( zigzag_right : C.compose_2_vertically (C.compose_2_horizontally (C.identity_1 f) counit) (C.compose_2_horizontally unit (C.identity_1 f)) = C.identity_1 f) -- TODO the other zigzag end tqft.categories.two_category
a32a8d93d156c58bed9f04c89169a859eb44e80d
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/app/VCGBlock.lean
ef759acd3f3d8ae2e7e3f05695c531d03f427383
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
34,174
lean
import LeanLLVM.AST import LeanLLVM.LLVMLib import LeanLLVM.PP import SMTLIB.Syntax import X86Semantics.Common -- for reg names import ReoptVCG.Types import ReoptVCG.VCGBackend import ReoptVCG.WordSize import ReoptVCG.MCStdLib import ReoptVCG.SMT namespace ReoptVCG open LLVM (LLVMType Typed PrimType Value) open SMT (smtM IdGen.empty) open SMT.sort (smt_bool) open x86 (reg64) open BlockVCG (globalThrow) open x86.vcg (RegState) namespace BlockVCG -- | Stop verifying this block. def haltBlock {α} (msg : String) : BlockVCG α := localThrow msg -- | This prepends the LLVM and machine code location information for -- display to user. def prependLocation (msg : String) : BlockVCG String := do fnName ← BlockVCGContext.llvmFunName <$> read; lbl ← BlockVCGContext.currentBlock <$> read; instIdx ← BlockVCGState.llvmInstIndex <$> get; curAddr ← BlockVCGState.mcCurAddr <$> get; pure $ renderMCInstError fnName lbl instIdx curAddr msg -- | Report an error at the given location and stop verification of -- this block. FIXME this currently uses a callback (which will report an error via IO) -- _and_ calls `haltBlock`, which will return a local error with an error message. At -- some point we probably just want to use the latter when we move away from using IO -- as much. def fatalBlockError {α} (msg : String) : BlockVCG α := do thisInst ← BlockVCGState.llvmInstIndex <$> get; curAddr ← BlockVCGState.mcCurAddr <$> get; callback <- ProverInterface.blockErrorCallback <$> BlockVCGContext.callbackFns <$> read; liftIO $ callback thisInst curAddr msg; haltBlock msg def addCommand (cmd : SMT.command) : BlockVCG Unit := do prover <- (fun (s : BlockVCGContext) => s.callbackFns) <$> read; liftIO $ prover.addCommandCallback cmd def runsmtM {a : Type} (m : smtM a) : BlockVCG a := do let run' := fun (s : BlockVCGState) => (let r := SMT.runsmtM s.idGen m; ((r.fst, r.snd.snd.reverse) , {s with idGen := r.snd.fst})); (r, cmds) <- modifyGet run'; _ <- List.mapM addCommand cmds; pure r -- | Add assertion that the propositon is true without requiring it to be proven. def addAssert (p : SMT.term smt_bool) : BlockVCG Unit := addCommand $ SMT.Raw.command.assert p -- FIXME -- | @proveTrue p msg@ adds a proof obligation @p@ is true for all -- interpretations of constants with the message @msg@. def proveTrue (p : SMT.term smt_bool) (msg : String) : BlockVCG Unit := do annMsg <- prependLocation msg; prover <- BlockVCGContext.callbackFns <$> read; liftIO $ prover.proveTrueCallback p annMsg; -- Add command for future proofs addAssert p -- | @proveEq x y msg@ add a proof obligation named @msg@ asserting -- that @x@ equals @y@. def proveEq {s : SMT.sort} (x y : SMT.term s) (msg : String) : BlockVCG Unit := do prover <- BlockVCGContext.callbackFns <$> read; annMsg <- prependLocation msg; liftIO $ prover.proveTrueCallback (SMT.eq x y) annMsg; -- FIXME: was proveFalseCallback/SMT.distinct -- Add command for future proofs addAssert (SMT.eq x y) -- | Add assertion that the propositon is true without requiring it to be proven. def addComment (str : String) : BlockVCG Unit := addCommand $ SMT.Raw.command.comment str -- FIXME? end BlockVCG export BlockVCG (addCommand proveTrue proveEq addAssert addComment) -------------------------------------------------------------------------------- -- Type <-> SMT @[reducible] def HasSMTSort : LLVMType -> Prop | LLVM.LLVMType.ptr _ => True | LLVM.LLVMType.prim pt => match pt with | LLVM.PrimType.integer i => i > 0 | _ => False | _ => False -- | Convert LLVM type to SMT sort. def asSMTSort : forall (tp : LLVMType) (pf : HasSMTSort tp), SMT.sort | LLVM.LLVMType.ptr _, _ => SMT.sort.bitvec 64 | LLVM.LLVMType.prim (LLVM.PrimType.integer i), _ => SMT.sort.bitvec i namespace HasSMTSort open LLVM.LLVMType open LLVM.PrimType protected def dec : forall (tp : LLVMType), Decidable (HasSMTSort tp) | ptr t => isTrue True.intro | prim pt => match pt with | integer i => Nat.decLt _ _ | label => isFalse (fun x => x) | token => isFalse (fun x => x) | void => isFalse (fun x => x) | floatType _ => isFalse (fun x => x) | x86mmx => isFalse (fun x => x) | metadata => isFalse (fun x => x) | alias _ => isFalse (fun x => x) | array _ _ => isFalse (fun x => x) | funType _ _ _ => isFalse (fun x => x) | struct _ _ => isFalse (fun x => x) | vector _ _ => isFalse (fun x => x) instance {tp : LLVMType} : Decidable (HasSMTSort tp) := HasSMTSort.dec tp end HasSMTSort def asSMTSort' (tp : LLVMType) : Option SMT.sort := if H : HasSMTSort tp then some (asSMTSort tp H) else none def coerceToSMTSort (ty : LLVMType) : BlockVCG SMT.sort := match asSMTSort' ty with | some tp => pure tp | none => BlockVCG.globalThrow $ "Unexpected type " ++ (ppLLVM ty) -------------------------------------------------------------------------------- -- Ident <-> SMT def lookupIdent (i : LLVM.Ident) (s : SMT.sort) : BlockVCG (SMT.term s) := do m <- BlockVCGState.llvmIdentMap <$> get; match m.find? i with | some (Sigma.mk s' tm) => if H : s' = s then pure (Eq.recOn H tm) else BlockVCG.globalThrow ("Sort mismatch for " ++ i.asString) | none => BlockVCG.globalThrow ("Unknown ident: " ++ i.asString) def freshIdent (i : LLVM.Ident) (s : SMT.sort) : BlockVCG (SMT.term s) := do sym <- BlockVCG.runsmtM (SMT.freshSymbol i.asString); -- FIXME: this should be primitive in SMT let tm := SMT.mk_symbol sym s; modify (fun s => {s with llvmIdentMap := s.llvmIdentMap.insert i (Sigma.mk _ tm)}); pure tm def defineTerm {s : SMT.sort} (i : LLVM.Ident) (tm : SMT.term s) : BlockVCG (SMT.term s) := do sym <- BlockVCG.runsmtM (SMT.define_fun i.asString [] s tm); modify (fun s => {s with llvmIdentMap := s.llvmIdentMap.insert i (Sigma.mk _ sym)}); pure sym def declareTerm (i : LLVM.Ident) (s : SMT.sort) : BlockVCG (SMT.term s) := do sym <- BlockVCG.runsmtM (SMT.declare_fun i.asString [] s); modify (fun s => {s with llvmIdentMap := s.llvmIdentMap.insert i (Sigma.mk _ sym)}); pure sym -------------------------------------------------------------------------------- -- MC Events section open x86.vcg (Event) open x86.vcg.Event open BlockVCG (liftIO globalThrow) def mcNextAddr (s : BlockVCGState) : MemAddr := s.mcCurAddr + s.mcCurSize -- | Get next events def getNextEvents : BlockVCG Unit := do ctx <- read; s <- get; let addr := mcNextAddr s; when (not (addr < ctx.mcBlockEndAddr)) $ globalThrow $ "Unexpected end of machine code events."; -- FIXMEL df, x87Top -- BlockVCG.liftIO $ IO.println ("Decoding at " ++ addr.ppHex); addComment ("MC: at " ++ addr.ppHex); (events, idGen', sz) <- match x86.vcg.instructionEvents ctx.mcBlockMap s.mcCurRegs s.idGen addr ctx.mcModuleVCGContext.decoder with | Except.error e => globalThrow e | Except.ok r => pure r; -- Update local index and next addr set $ { s with idGen := idGen' , mcCurAddr := addr , mcCurSize := sz , mcEvents := events } -- | Set machine code registers from reg state. def setMCRegs (regs : x86.vcg.RegState) : BlockVCG Unit := -- FIXME -- topVal <- case regs^.boundValue X87_TopReg of -- BVValue _w i | 0 <= i, i <= 7 -> pure $! fromInteger i -- _ -> error "Unexpected X87_TOP value" -- dfVal <- case regs^.boundValue DF of -- BoolValue b -> pure b -- _ -> error "Unexpected direction flag" modify $ fun s => { s with mcCurRegs := regs } def getSupportedType (s : SMT.sort) : BlockVCG (x86.vcg.SupportedMemType s) := do mcstd <- BlockVCGContext.mcStdLib <$> read; let mops := mcstd.memOpsBySort; match mops s with | some ops => pure ops | none => globalThrow $ "Unexpected type " ++ toString s def declareMem : BlockVCG x86.vcg.memory := BlockVCG.runsmtM $ SMT.declare_fun "mem" [] x86.vcg.memory_t def mcWrite (addr : x86.vcg.memaddr) (s : SMT.sort) (val : SMT.term s) : BlockVCG Unit := do curMem <- (fun (s : BlockVCGState) => s.mcCurMem) <$> get; supType <- getSupportedType s; nextMem <- BlockVCG.runsmtM $ SMT.define_fun "mem" [] x86.vcg.memory_t (supType.writeMem curMem addr val); modify $ fun s => { s with mcCurMem := nextMem } def mcRead (addr : x86.vcg.memaddr) (s : SMT.sort) : BlockVCG (SMT.term s) := do curMem <- BlockVCGState.mcCurMem <$> get; supType <- getSupportedType s; pure (supType.readMem curMem addr) def mcAssignRead (addr : x86.vcg.memaddr) (s : SMT.sort) (smtVar : SMT.term s) : BlockVCG Unit := do v <- mcRead addr s; addAssert (SMT.eq smtVar v) -- | Execute the machine-code only events that occur before jumping to the given address partial def execMCOnlyEvents : MemAddr -> BlockVCG Unit | endAddr => do evts <- BlockVCGState.mcEvents <$> get; match evts with | Command cmd :: mevs => do -- BlockVCG.liftIO $ IO.println ("execMCOnlyEvents: Command"); addCommand cmd; modify (fun s => { s with mcEvents := mevs }); execMCOnlyEvents endAddr | Warning msg :: mevs => do liftIO $ IO.println msg; modify (fun s => { s with mcEvents := mevs }); execMCOnlyEvents endAddr | MCOnlyStackReadEvent mcAddr n smtValVar :: mevs => do -- BlockVCG.liftIO $ IO.println ("execMCOnlyEvents: MCOnlyStackReadEvent"); -- TODO: Fix this to the following -- A MCOnlyStack read means the machine code reads memory, but -- the llvm does not. -- -- We currently check that these reads only access the stack as -- the only current use of these annotations is to mark register -- spills, return address read/writes, and frame pointer/callee saved -- register saves/restores. -- -- Checking this is on the stack also ensures there are no side effects -- from mem-mapped IO reads since the stack should not be mem-mapped IO. (do thisIP <- BlockVCGState.mcCurAddr <$> get; stdLib <- BlockVCGContext.mcStdLib <$> read; -- FIXME: assert 8 dvd n -- FIMXE: make this take a Nat? proveTrue (stdLib.onStack mcAddr (SMT.bvimm _ (n / 8))) ("machine code read at " ++ thisIP.ppHex ++ " is not within stack space.")); -- Define value from reading Macaw heap mcAssignRead mcAddr (SMT.sort.bitvec n) smtValVar; -- Process future events. modify (fun s => { s with mcEvents := mevs }); execMCOnlyEvents endAddr -- Every LLVM write should have a machine code write (but not -- necessarily vice versa), we pattern match on machine code -- writes. | MCOnlyStackWriteEvent mcAddr n smtVal :: mevs => do -- BlockVCG.liftIO $ IO.println ("execMCOnlyEvents: MCOnlyStackWriteEvent"); -- We need to assert that this werite will not be visible to LLVM. -- FIXME - once we have allocas this will need to be mcOnlyStackRange (do thisIP <- BlockVCGState.mcCurAddr <$> get; stdLib <- BlockVCGContext.mcStdLib <$> read; -- FIXME: assert 8 dvd n proveTrue (stdLib.onStack mcAddr (SMT.bvimm _ (n / 8))) ("machine code write at " ++ thisIP.ppHex ++ " is in unreserved stack space.")); -- do addr <- mcCurAddr <$> get; -- proveTrue (evalRangeCheck mcOnlyStackRange mcAddr (memReprBytes tp)) $ -- printf "machine code write at %s is in unreserved stack space." (show addr) -- Update stack with write. mcWrite mcAddr (SMT.sort.bitvec n) smtVal; -- Process next events modify $ fun s => {s with mcEvents := mevs }; execMCOnlyEvents endAddr -- This checks to see if the next instruction jumps to the next ip, -- and if so it runs it. | FetchAndExecuteEvent regs :: mevs => do -- BlockVCG.liftIO $ IO.println ("execMCOnlyEvents: fetch and exec case"); when (not mevs.isEmpty) $ globalThrow "MC event after fetch and execute"; modify $ fun s => { s with mcEvents := [] }; -- Update registers setMCRegs regs; -- Process next events nextAddr <- mcNextAddr <$> get; -- BlockVCG.liftIO $ IO.println ("execMCOnlyEvents: fetch and exec case: " ++ nextAddr.ppHex ++ " " ++ endAddr.ppHex); -- FIXME: this is fragile ... match SMT.bvAsConst regs.ip with | some nextAddr' => if nextAddr = nextAddr' ∧ nextAddr < endAddr then do getNextEvents; execMCOnlyEvents endAddr else pure () | none => pure () | [] => do -- BlockVCG.liftIO $ IO.println ("execMCOnlyEvents: empty case"); nextAddr <- mcNextAddr <$> get; when (nextAddr < endAddr) $ do getNextEvents; execMCOnlyEvents endAddr | e :: _ => do -- BlockVCG.liftIO $ IO.println ("execMCOnlyEvents: done at " ++ repr e); pure () -- -- | Get the next MC event that could interact with LLVM. -- popMCEvent :: HasCallStack => BlockVCG M.Event -- popMCEvent = do -- endAddr <- asks mcBlockEndAddr -- execMCOnlyEvents endAddr -- evts <- gets mcEvents -- case evts of -- [] -> do -- error "Reached end of block" -- (h:r) -> do -- modify $ \s -> s { mcEvents = r } -- pure h end -- -- | Move to end of current block. def mcExecuteToEnd : BlockVCG Unit := do endAddr <- (fun (s : BlockVCGContext) => s.mcBlockEndAddr) <$> read; execMCOnlyEvents endAddr; evts <- (fun (s : BlockVCGState) => s.mcEvents) <$> get; match evts with | [] => pure () | e :: _ => BlockVCG.globalThrow $ "Expecting end of block, got " ++ repr e -------------------------------------------------------------------------------- -- Literal constructors def mkInt {w : Nat} (v : Int) (H : w > 0) : SMT.term (asSMTSort (LLVM.LLVMType.prim (LLVM.PrimType.integer w)) H) := SMT.bvimm' w v section open LLVM.Value def primEval : forall (tp : LLVMType) (H :HasSMTSort tp), Value -> BlockVCG (SMT.term (asSMTSort tp H)) | tp, H, ident i => lookupIdent i (asSMTSort tp H) | LLVM.LLVMType.prim (LLVM.PrimType.integer w), H, integer i => pure (mkInt i H) | _, _, _ => BlockVCG.globalThrow "unimplemented" end -- -------------------------------------------------------------------------------- -- -- Branch support -- AMK: `initBlockRegValues` is used in the Haskell implementation of `verifyBlockPreconditions` -- ... but for ours I just use a helper `checkInitRegVals` since there isn't an obvious -- analogue to the `X86Reg` from flexdis86 (i.e., a way to index the IP, X87 top reg, and DF).. -- def initBlockRegValues (ann : ReachableBlockAnn) : List (Fin 16 × SMT.term (SMT.sort.bitvec 64)) := -- [ (Some X86_IP, SMT.bvhexadecimal (toInteger (Ann.blockAddr blockAnn)) 64) -- -- , (Some X87_TopReg, SMT.bvdecimal (toInteger (Ann.blockX87Top blockAnn)) 3) -- -- , (Some DF, if Ann.blockDFFlag blockAnn then SMT.true else SMT.false) -- ] -------------------------------------------------------------------------------- -- Function calls -- In initial state def stackHighTerm : BlockVCG x86.vcg.memaddr := do stdLib <- BlockVCGContext.mcStdLib <$> read; pure (stdLib.funStartRegs.get_reg64 x86.reg64.rsp) -- In initial state def returnAddrTerm : BlockVCG x86.vcg.memaddr := do stdLib <- BlockVCGContext.mcStdLib <$> read; -- FIXME sht <- stackHighTerm; let addrOp := stdLib.memOps WordSize.word64; pure (addrOp.readMem stdLib.blockStartMem sht) axiom VCGBlock_sorry: forall P, P -- Converts a machine word to be the same width as a given LLVM type. In the monad to allow failure def wordAsType (w : x86.vcg.bitvec 64) (ty : LLVMType) : BlockVCG (PSigma (fun (H : HasSMTSort ty) => SMT.term (asSMTSort ty H))) := match ty with | ty@(LLVM.LLVMType.ptr _) => do let pf : HasSMTSort ty := True.intro; pure (PSigma.mk pf w) | ty@(LLVM.LLVMType.prim (LLVM.PrimType.integer 64)) => do let pf : HasSMTSort ty := rfl; -- proves 0 < 64 = true, sort of grossly pure (PSigma.mk pf w) | ty@(LLVM.LLVMType.prim (LLVM.PrimType.integer i)) => do if H : 0 < i /\ i < 64 then do let pf : HasSMTSort ty := H.left; let pf' : (i - 1 + 1) - 0 = i := VCGBlock_sorry _; let smcv0 := SMT.extract (i - 1) 0 w; let r := @Eq.recOn _ _ (fun a _ => SMT.term (SMT.sort.bitvec a)) _ pf' smcv0; pure (PSigma.mk pf r) else globalThrow "Unexpected sort in wordAsType" | _ => globalThrow "Unexpected sort in wordAsType" def proveRegRel (msg : String) (w : x86.vcg.bitvec 64) : LLVM.Typed LLVM.Value -> BlockVCG Unit | { type := ty, value := v } => do PSigma.mk pf mcv <- wordAsType w ty; lv <- primEval ty pf v; proveEq lv mcv msg def llvmReturn (mlret : Option (Typed Value)) : BlockVCG Unit := do mcExecuteToEnd; regs <- BlockVCGState.mcCurRegs <$> get; _ <- (do sht <- stackHighTerm; proveEq (regs.get_reg64 x86.reg64.rsp) (SMT.bvadd sht (SMT.bvimm _ 8)) "stack height at return matches init."); _ <- (do ra <- returnAddrTerm; proveEq regs.ip ra "return address matches entry value."); -- FIXME checkDirectionFlagClear stdLib <- BlockVCGContext.mcStdLib <$> read; let rEq r := proveEq (regs.get_reg64 r) (stdLib.funStartRegs.get_reg64 r) ("value of " ++ r.name ++ " at return is preserved."); List.forM rEq x86CalleeSavedGPRegs; match mlret with | none => pure () | some v => proveRegRel "return values match" (regs.get_reg64 x86.reg64.rax) v def llvmInvoke (isTailCall : Bool) (fsym : LLVM.Symbol) (args : Array (Typed Value)) (lRet : Option (LLVM.Ident × LLVMType)) : BlockVCG Unit := do when isTailCall $ globalThrow "Tail calls are unimplemented"; BlockVCGContext.mcBlockEndAddr <$> read >>= execMCOnlyEvents; regs <- BlockVCGState.mcCurRegs <$> get; -------------------- -- Pre call -- FIXME assertFnNameEq fsym regs.ip when (args.size > x86ArgGPRegs.length) $ globalThrow "Too many arguments"; let proveOne v (r : x86.reg64) := proveRegRel ("argument matches register " ++ r.repr) (regs.get_reg64 r) v; List.forM₂ proveOne args.toList x86ArgGPRegs; -- FIXME checkDirectionFlagClear; postCallRIP <- mcNextAddr <$> get; -- FIXME: generalise returnAddrTerm? -- Check stored return value matches next instruction (do addrOnStack <- mcRead (regs.get_reg64 x86.reg64.rsp) _; proveEq addrOnStack (SMT.bvimm 64 postCallRIP) "return address matches next instruction."); -------------------- -- Post call -- Construct new register after the call. let postCallRSP := SMT.bvadd (regs.get_reg64 x86.reg64.rsp) (SMT.bvimm _ 8); -- create a newRegs <- (do rs <- BlockVCG.runsmtM $ x86.vcg.RegState.declare_const ("a" ++ postCallRIP.ppHex ++ "_") postCallRIP; let rs_with_rsp := x86.vcg.RegState.update_reg64 x86.reg64.rsp (fun _ => postCallRSP) rs; let copy_reg s r := x86.vcg.RegState.update_reg64 r (fun _ => regs.get_reg64 r) s; pure (List.foldl copy_reg rs_with_rsp x86CalleeSavedGPRegs)); modify $ fun s => {s with mcCurRegs := newRegs }; -- Update machine code memory to post-call memory. (do newMem <- declareMem; oldMem <- BlockVCGState.mcCurMem <$> get; sht <- stackHighTerm; addAssert $ SMT.eqrange newMem oldMem postCallRSP (SMT.bvadd sht (SMT.bvimm _ 7)); modify $ fun s => {s with mcCurMem := newMem }); -- Assign returned value by assigning LLVM variable match lRet with | none => pure () | some (i, ty) => do PSigma.mk pf mcv <- wordAsType (newRegs.get_reg64 x86.reg64.rax) ty; defineTerm i mcv $> () -------------------------------------------------------------------------------- -- Arithmetic section open LLVM.Value open LLVM.ICmpOp def arithOpFunc {n : Nat} : LLVM.ArithOp -> SMT.term (SMT.sort.bitvec n) -> SMT.term (SMT.sort.bitvec n) -> SMT.term (SMT.sort.bitvec n) | LLVM.ArithOp.add _ _, x, y => SMT.bvadd x y | LLVM.ArithOp.sub _ _, x, y => SMT.bvsub x y | LLVM.ArithOp.mul _ _, x, y => SMT.bvmul x y | _, _, _ => SMT.bvimm _ 0 -- FIXME def bitOpFunc {n : Nat} : LLVM.BitOp -> SMT.term (SMT.sort.bitvec n) -> SMT.term (SMT.sort.bitvec n) -> SMT.term (SMT.sort.bitvec n) | LLVM.BitOp.and, x, y => SMT.bvand x y | LLVM.BitOp.or, x, y => SMT.bvor x y | LLVM.BitOp.xor, x, y => SMT.bvxor x y | _, _, _ => SMT.bvimm _ 0 -- FIXME def icmpOpFunc {n : Nat} : LLVM.ICmpOp -> SMT.term (SMT.sort.bitvec n) -> SMT.term (SMT.sort.bitvec n) -> SMT.term smt_bool | ieq, x, y => SMT.eq x y | ine, x, y => SMT.not (SMT.eq x y) | iugt, x, y => SMT.bvugt x y | iuge, x, y => SMT.bvuge x y | iult, x, y => SMT.bvult x y | iule, x, y => SMT.bvule x y | isgt, x, y => SMT.bvsgt x y | isge, x, y => SMT.bvsge x y | islt, x, y => SMT.bvslt x y | isle, x, y => SMT.bvsle x y end def tryPrimEval (tp : LLVMType) (v:Value) : BlockVCG (Sigma SMT.term) := if h : HasSMTSort tp then do t ← primEval tp h v; pure $ ⟨asSMTSort tp h, t⟩ else BlockVCG.globalThrow $ "unable to evaluate llvm term "++(ppLLVM v)++" at type "++(ppLLVM tp) -------------------------------------------------------------------------------- -- Block Precondition Verification namespace BlockVCG -- def checkInitRegVals -- (blockAnn : ReachableBlockAnn) -- -- ^ Message to preface verification comments/messages/etc -- (goalFn : SMT.term SMT.sort.smt_bool → SMT.term SMT.sort.smt_bool) -- : BlockVCG Unit := do -- -- Check the instruction pointer -- let expectedIp : SMT.term SMT.sort.bv64 := SMT.bvimm 64 blockAnn.startAddr.toNat; -- regs <- BlockVCGState.mcCurRegs <$> get; -- proveTrue (goalFn (SMT.eq expectedIp regs.ip)) "Checking the IP register."; -- -- Check x87Top value -- --let expectedX87Top : SMT.term SMT.sort.bv64 := SMT.bv 64 blockAnn.startAddr.toNat; -- -- (Some X87_TopReg, SMT.bvdecimal (toInteger (Ann.blockX87Top blockAnn)) 3) -- -- FIXME check BlockVCGState.mcX87Top value against expected ^ -- -- Check the direction flag -- --let expectedDF : SMT.term SMT.sort.bv64 := SMT.bvimm 64 blockAnn.startAddr.toNat; -- -- (Some DF, if Ann.blockDFFlag blockAnn then SMT.true else SMT.false) -- -- FIXME check BlockVCGState.mcDF value against expected ^ -- pure () -- cf. `verifyBlockPreconditions` def verifyPreconditions (prefixDescr : String) -- ^ Message to preface verification comments/messages/etc (goalFn : SMT.term SMT.sort.smt_bool → SMT.term SMT.sort.smt_bool) -- ^ Function applied to predicates before verification allowing us -- to conditionally validate some of the preconditions. (lbl : LLVM.BlockLabel) -- ^ LLVM label of the block we are jumping to. : BlockVCG Unit := do blkMap ← BlockVCGContext.funBlkAnnotations <$> read; match findBlock blkMap lbl with | none => fatalBlockError $ "Target block "++(ppBlockLabel lbl)++" lacks annotations." | some (BlockAnn.unreachable, _) => proveTrue (goalFn SMT.false) $ "target block "++(ppBlockLabel lbl)++"is unreachable." | some (BlockAnn.reachable tgtBlockAnn, varMap) => do firstLabel ← BlockVCGContext.firstBlockLabel <$> read; -- Ensure we're not in the first block when (lbl == firstLabel) $ globalThrow "LLVM should not jump to first label in function."; -- Check initialized register values (just rip for now) (do regs <- BlockVCGState.mcCurRegs <$> get; let expected := SMT.bvimm 64 tgtBlockAnn.startAddr.toNat; proveTrue (goalFn (SMT.eq expected regs.ip)) (prefixDescr ++ " register rip.")); -- checkInitRegVals tgtBlockAnn goalFn; srcLbl <- BlockVCGContext.currentBlock <$> read; -- Resolve terms for SMT variables which can appear in precondition statements. let resolvePhiVarVal : LLVM.Ident → (LLVM.LLVMType × BlockLabelValMap) → BlockVCG (Sigma SMT.term) := λ nm val => let (tp, valMap) := val; match valMap.find? srcLbl with | some v => tryPrimEval tp v | none => globalThrow $ "Could not find initial value of llvm variable `"++nm.asString++"`."; phiTermMap ← varMap.mapM resolvePhiVarVal; -- Verify each precondition tgtBlockAnn.preconds.forM (λ precondExpr => do p ← evalPrecondition phiTermMap.find? precondExpr; proveTrue (goalFn p) $ prefixDescr++" precondition: "++precondExpr.toString) -- Check allocations are preserved. -- FIXME actually do this when we get to reasoning about allocas. -- curAllocas <- gets mcPendingAllocaOffsetMap -- when (Ann.blockAllocas tgtBlockAnn /= curAllocas) $ do -- fatalBlockError $ printf "Allocations in jump to %s do not match." (ppBlock lbl) end BlockVCG -------------------------------------------------------------------------------- -- stepNextStmt section open LLVM.Instruction open BlockVCG (verifyPreconditions) def stepNextStmt (stmt : LLVM.Stmt) : BlockVCG Bool := do match stmt.instr with | phi _ _ => globalThrow "Unexpected phi in stepNextStmt" -- | alloca : LLVMType -> Option (typed value) -> Option Nat -> instruction | arith aop { type := lty, value := lhs } rhs => do if H : HasSMTSort lty then do lhsv <- primEval lty H lhs; rhsv <- primEval lty H rhs; match asSMTSort lty H, stmt.assign, lhsv, rhsv with | _, none, _, _ => pure () | SMT.sort.bitvec n, some i, l, r => defineTerm i (arithOpFunc aop l r) $> () | _, _, _, _ => BlockVCG.globalThrow "Unexpected sort"; pure True else BlockVCG.globalThrow "Unexpected type" | bit bop { type := lty, value := lhs } rhs => do if H : HasSMTSort lty then do lhsv <- primEval lty H lhs; rhsv <- primEval lty H rhs; match asSMTSort lty H, stmt.assign, lhsv, rhsv with | _, none, _, _ => pure () | SMT.sort.bitvec n, some i, l, r => defineTerm i (bitOpFunc bop l r) $> () | _, _, _, _ => BlockVCG.globalThrow "Unexpected sort"; pure True else BlockVCG.globalThrow "Unexpected type" | call tailcall o_ty f args => do match f with | LLVM.Value.symbol s => llvmInvoke tailcall s args (match o_ty, stmt.assign with | some ty, some i => some (i, ty) | _, _ => none) | _ => globalThrow "VCG currently only supports direct calls."; pure True -- | conv : conv_op -> typed value -> LLVMType -> instruction | icmp bop { type := lty, value := lhs } rhs => do if H : HasSMTSort lty then do lhsv <- primEval lty H lhs; rhsv <- primEval lty H rhs; match asSMTSort lty H, stmt.assign, lhsv, rhsv with | _, none, _, _ => pure () | SMT.sort.bitvec n, some i, l, r => defineTerm i (SMT.smt_ite (icmpOpFunc bop l r) (SMT.bvimm 1 1) (SMT.bvimm 1 0)) $> () | _, _, _, _ => BlockVCG.globalThrow "Unexpected sort"; pure True else BlockVCG.globalThrow "Unexpected type" | br { type := _lty, value := cnd } tlbl flbl => do mcExecuteToEnd; let pf : HasSMTSort (LLVM.LLVMType.prim (LLVM.PrimType.integer 1)) := rfl; cndTerm <- primEval _ pf cnd; let c := SMT.eq cndTerm (SMT.bvimm _ 1); verifyPreconditions "true branch" (SMT.impl c) tlbl; verifyPreconditions "false branch" (SMT.impl (SMT.not c)) flbl; pure False | jump lbl => do mcExecuteToEnd; verifyPreconditions "jump" (fun x => x) lbl; pure False | ret v => llvmReturn (some v) $> false | retVoid => llvmReturn none $> false | _ => BlockVCG.globalThrow "(stepNextStmt) unimplemented" -- | conv : conv_op -> typed value -> LLVMType -> instruction -- | alloca : LLVMType -> Option (typed value) -> Option Nat -> instruction -- | load : typed value -> Option atomic_ordering -> Option Nat /- align -/ -> instruction -- | store : typed value -> typed value -> Option Nat /- align -/ -> instruction -- /- -- | fence : option string -> atomic_ordering -> instruction -- | cmp_xchg (weak : bool) (volatile : bool) : typed value -> typed value -> typed value -- -> option string -> atomic_ordering -> atomic_ordering -> instruction -- | atomic_rw (volatile : bool) : atomic_rw_op -> typed value -> typed value -- -> option string -> atomic_ordering -> instruction -- -/ -- | fcmp : fcmp_op -> typed value -> value -> instruction -- | gep (bounds : Bool) : typed value -> Array (typed value) -> instruction -- | select : typed value -> typed value -> value -> instruction -- | extract_value : typed value -> List Nat -> instruction -- | insert_value : typed value -> typed value -> List Nat -> instruction -- | extract_elt : typed value -> value -> instruction -- | insert_elt : typed value -> typed value -> value -> instruction -- | shuffle_vector : typed value -> value -> typed value -> instruction -- | invoke : LLVMType -> value -> List (typed value) -> block_label -> block_label -> instruction -- | comment : String -> instruction -- | unreachable -- | unwind -- | va_arg : typed value -> LLVMType -> instruction -- | indirect_br : typed value -> List block_label -> instruction -- | switch : typed value -> block_label -> List (Nat × block_label) -> instruction -- | landing_pad : LLVMType -> Option (typed value) -> Bool -> List (clause × typed value) -> instruction -- | resume : typed value -> instruction end -------------------------------------------------------------------------------- -- Runner namespace BlockVCG -- cf. `runBlockVCG` protected def run (mctx : ModuleVCGContext) (funAnn : FunctionAnn) (bmap : ReachableBlockAnnMap) (firstBlock : LLVM.BlockLabel) (firstAddr : MCAddr) -- FIXME: maybe not strictly required (thisBlock : LLVM.BlockLabel) (blockAnn : ReachableBlockAnn) (m : BlockVCG Unit) : IO Unit := do mctx.proverGen.blockCallback funAnn.llvmFunName thisBlock $ fun prover => do let blockStart := blockAnn.startAddr.toNat; let sz := blockAnn.codeSize; let blockMap : MCBlockAnnMap := (let mk (e : MCMemoryEvent) := (e.addr.toNat, e.info); RBMap.ofList (List.map mk blockAnn.memoryEvents.toList)); ((stdLib, blockRegs), idGen') <- prover.runsmtM IdGen.empty (do let ann := mctx.annotations; stdLib <- x86.vcg.MCStdLib.make firstAddr.addr.toNat ann.pageSize ann.stackGuardPageCount; blockRegs <- if thisBlock = firstBlock then pure stdLib.funStartRegs else x86.vcg.RegState.declare_const ("a" ++ blockStart.ppHex ++ "_") blockStart; -- FIXME df etc. pure (stdLib, blockRegs)); let ctx := { BlockVCGContext . mcModuleVCGContext := mctx , llvmFunName := funAnn.llvmFunName , funBlkAnnotations := bmap , firstBlockLabel := firstBlock , currentBlock := thisBlock , callbackFns := prover , mcBlockEndAddr := blockStart + sz , mcBlockMap := blockMap , mcStdLib := stdLib }; let s := { BlockVCGState . mcCurAddr := blockStart , mcCurSize := 0 , mcCurRegs := blockRegs , mcCurMem := stdLib.blockStartMem , mcEvents := [] , idGen := idGen' , llvmInstIndex := 0 , llvmIdentMap := RBMap.empty }; r <- ((m.run ctx).run' s).run; match r with | Except.ok _ => pure () | Except.error e => match e with | BlockVCGError.localErr msg => IO.println $ "Local error encountered during BlockVCG.run: " ++ msg | BlockVCGError.globalErr msg => throw $ IO.userError $ "Fatal error encountered in BlockVCG.run: " ++ msg end BlockVCG -- | Verify c over LLVM stmts -- -- Note. This is written to take a function rather than directly call -- @stepNextStmtg@ so that the call stack is cleaner. def checkEachStmt : List LLVM.Stmt → BlockVCG Unit | [] => BlockVCG.globalThrow "We have reached end of LLVM events without a block terminator." | (stmt::stmts) => do BlockVCG.addComment $ "LLVM: " ++ (ppLLVM stmt); continue ← stepNextStmt stmt; modify (λ s => {s with llvmInstIndex := s.llvmInstIndex + 1 }); if continue then checkEachStmt stmts else unless stmts.isEmpty $ BlockVCG.globalThrow "Expected return to be last LLVM statement." def defineArgBinding (b : LLVMMCArgBinding) : BlockVCG Unit := do funStartRegs ← (x86.vcg.MCStdLib.funStartRegs ∘ BlockVCGContext.mcStdLib) <$> read; let val : SMT.term SMT.sort.bv64 := funStartRegs.get_reg64 b.register; _ ← defineTerm b.llvmArgName val; pure () def definePhiVar (nm : LLVM.Ident) (entry : LLVM.LLVMType × BlockLabelValMap) : BlockVCG Unit := do let (tp, _) := entry; s ← coerceToSMTSort tp; _ ← declareTerm nm s; pure () /-- Verify a reachable block satisfies its specification. cf `verifyBlock` --/ def verifyReachableBlock (blockAnn : ReachableBlockAnn) (args : List LLVMMCArgBinding) (phiVarMap : PhiVarMap) (stmts : List LLVM.Stmt) : BlockVCG Unit := do -- Add LLVM declarations for all existing allocations. -- FIXME we skip alloca stuff for now, FYI. -- forM_ (Ann.blockAllocas blockAnn) $ \a -> do -- when (Ann.allocaExisting a) $ do -- allocaDeclarations (Ann.allocaIdent a) (SMT.bvdecimal (toInteger (Ann.allocaSize a)) 64) -- -- Declare LLVM arguments in terms of the registers at function start. args.forM defineArgBinding; -- Declare phi variables phiVarMap.mfor definePhiVar; llvmIdentTermMap ← BlockVCGState.llvmIdentMap <$> get; -- -- Assume preconditions blockAnn.preconds.forM (λ pExpr => do pTerm ← evalPrecondition llvmIdentTermMap.find? pExpr; addAssert pTerm); -- -- Start processing LLVM statements checkEachStmt stmts end ReoptVCG
8f99e0c6e91ae48a328b63b3e7b796b67786c2fe
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/quotient.lean
a046da6f01a1d0e9ffe3446dd4ca1ab689170d67
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,006
lean
import data.set.basic import data.quot variables {α : Type*} {β : Type*} [s : setoid α] namespace quotient lemma prod_preimage_eq_image (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) end quotient lemma quot_mk_quotient_mk {α :Type*} [setoid α] (a : α) : quot.mk setoid.r a = ⟦a⟧ := rfl noncomputable def habitant_of_quotient_habitant {α : Type*} {s : setoid α} (x : quotient s) : α := (classical.inhabited_of_nonempty $ (nonempty_quotient_iff s).1 ⟨x⟩).default
efe9c4cd0ff28fc565570462f883db881def40f0
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/linear_algebra/exterior_algebra.lean
2c2a8f8250c628b58bccf6ffe01480f3bf20cb9f
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,945
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhangir Azerbayev, Adam Topaz, Eric Wieser. -/ import algebra.ring_quot import linear_algebra.tensor_algebra import linear_algebra.alternating import group_theory.perm.sign /-! # Exterior Algebras We construct the exterior algebra of a semimodule `M` over a commutative semiring `R`. ## Notation The exterior algebra of the `R`-semimodule `M` is denoted as `exterior_algebra R M`. It is endowed with the structure of an `R`-algebra. Given a linear morphism `f : M → A` from a semimodule `M` to another `R`-algebra `A`, such that `cond : ∀ m : M, f m * f m = 0`, there is a (unique) lift of `f` to an `R`-algebra morphism, which is denoted `exterior_algebra.lift R f cond`. The canonical linear map `M → exterior_algebra R M` is denoted `exterior_algebra.ι R`. ## Theorems The main theorems proved ensure that `exterior_algebra R M` satisfies the universal property of the exterior algebra. 1. `ι_comp_lift` is fact that the composition of `ι R` with `lift R f cond` agrees with `f`. 2. `lift_unique` ensures the uniqueness of `lift R f cond` with respect to 1. ## Definitions * `ι_multi` is the `alternating_map` corresponding to the wedge product of `ι R m` terms. ## Implementation details The exterior algebra of `M` is constructed as a quotient of the tensor algebra, as follows. 1. We define a relation `exterior_algebra.rel R M` on `tensor_algebra R M`. This is the smallest relation which identifies squares of elements of `M` with `0`. 2. The exterior algebra is the quotient of the tensor algebra by this relation. -/ variables (R : Type*) [comm_semiring R] variables (M : Type*) [add_comm_monoid M] [semimodule R M] namespace exterior_algebra open tensor_algebra /-- `rel` relates each `ι m * ι m`, for `m : M`, with `0`. The exterior algebra of `M` is defined as the quotient modulo this relation. -/ inductive rel : tensor_algebra R M → tensor_algebra R M → Prop | of (m : M) : rel ((ι R m) * (ι R m)) 0 end exterior_algebra /-- The exterior algebra of an `R`-semimodule `M`. -/ @[derive [inhabited, semiring, algebra R]] def exterior_algebra := ring_quot (exterior_algebra.rel R M) namespace exterior_algebra variables {M} -- typeclass resolution times out here, so we give it a hand instance {S : Type*} [comm_ring S] [semimodule S M] : ring (exterior_algebra S M) := let i : ring (tensor_algebra S M) := infer_instance in @ring_quot.ring (tensor_algebra S M) i (exterior_algebra.rel S M) /-- The canonical linear map `M →ₗ[R] exterior_algebra R M`. -/ def ι : M →ₗ[R] exterior_algebra R M := (ring_quot.mk_alg_hom R _).to_linear_map.comp (tensor_algebra.ι R) variables {R} /-- As well as being linear, `ι m` squares to zero -/ @[simp] theorem ι_square_zero (m : M) : (ι R m) * (ι R m) = 0 := begin erw [←alg_hom.map_mul, ring_quot.mk_alg_hom_rel R (rel.of m), alg_hom.map_zero _], end variables {A : Type*} [semiring A] [algebra R A] @[simp] theorem comp_ι_square_zero (g : exterior_algebra R M →ₐ[R] A) (m : M) : g (ι R m) * g (ι R m) = 0 := by rw [←alg_hom.map_mul, ι_square_zero, alg_hom.map_zero] variables (R) /-- Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition: `cond : ∀ m : M, f m * f m = 0`, this is the canonical lift of `f` to a morphism of `R`-algebras from `exterior_algebra R M` to `A`. -/ @[simps symm_apply] def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = 0} ≃ (exterior_algebra R M →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : M →ₗ[R] A), λ x y (h : rel R M x y), by { induction h, rw [alg_hom.map_zero, alg_hom.map_mul, tensor_algebra.lift_ι_apply, f.prop] }⟩, inv_fun := λ F, ⟨F.to_linear_map.comp (ι R), λ m, by rw [ linear_map.comp_apply, alg_hom.to_linear_map_apply, comp_ι_square_zero]⟩, left_inv := λ f, by { ext, simp [ι] }, right_inv := λ F, by { ext, simp [ι] } } @[simp] theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) : (lift R ⟨f, cond⟩).to_linear_map.comp (ι R) = f := (subtype.mk_eq_mk.mp $ (lift R).symm_apply_apply ⟨f, cond⟩) @[simp] theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (x) : lift R ⟨f, cond⟩ (ι R x) = f x := (linear_map.ext_iff.mp $ ι_comp_lift R f cond) x @[simp] theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (g : exterior_algebra R M →ₐ[R] A) : g.to_linear_map.comp (ι R) = f ↔ g = lift R ⟨f, cond⟩ := begin convert (lift R).symm_apply_eq, rw lift_symm_apply, simp only, end attribute [irreducible] ι lift -- Marking `exterior_algebra` irreducible makes our `ring` instances inaccessible. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. variables {R M} @[simp] theorem lift_comp_ι (g : exterior_algebra R M →ₐ[R] A) : lift R ⟨g.to_linear_map.comp (ι R), comp_ι_square_zero _⟩ = g := begin convert (lift R).apply_symm_apply g, rw lift_symm_apply, refl, end /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {f g : exterior_algebra R M →ₐ[R] A} (h : f.to_linear_map.comp (ι R) = g.to_linear_map.comp (ι R)) : f = g := begin apply (lift R).symm.injective, rw [lift_symm_apply, lift_symm_apply], simp only [h], end /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv : exterior_algebra R M →ₐ[R] R := exterior_algebra.lift R ⟨(0 : M →ₗ[R] R), λ m, by simp⟩ lemma algebra_map_left_inverse : function.left_inverse algebra_map_inv (algebra_map R $ exterior_algebra R M) := λ x, by simp [algebra_map_inv] /-- The left-inverse of `ι`. As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable algebra structure. -/ def ι_inv : exterior_algebra R M →ₗ[R] M := (triv_sq_zero_ext.snd_hom R M).comp (lift R ⟨triv_sq_zero_ext.inr_hom R M, λ m, triv_sq_zero_ext.inr_mul_inr R _ m m⟩).to_linear_map lemma ι_left_inverse : function.left_inverse ι_inv (ι R : M → exterior_algebra R M) := λ x, by simp [ι_inv] @[simp] lemma ι_add_mul_swap (x y : M) : ι R x * ι R y + ι R y * ι R x = 0 := calc _ = ι R (x + y) * ι R (x + y) : by simp [mul_add, add_mul] ... = _ : ι_square_zero _ lemma ι_mul_prod_list {n : ℕ} (f : fin n → M) (i : fin n) : (ι R $ f i) * (list.of_fn $ λ i, ι R $ f i).prod = 0 := begin induction n with n hn, { exact i.elim0, }, { rw [list.of_fn_succ, list.prod_cons, ←mul_assoc], by_cases h : i = 0, { rw [h, ι_square_zero, zero_mul], }, { replace hn := congr_arg ((*) $ ι R $ f 0) (hn (λ i, f $ fin.succ i) (i.pred h)), simp only at hn, rw [fin.succ_pred, ←mul_assoc, mul_zero] at hn, refine (eq_zero_iff_eq_zero_of_add_eq_zero _).mp hn, rw [← add_mul, ι_add_mul_swap, zero_mul], } } end variables (R) /-- The product of `n` terms of the form `ι R m` is an alternating map. This is a special case of `multilinear_map.mk_pi_algebra_fin` -/ def ι_multi (n : ℕ) : alternating_map R M (exterior_algebra R M) (fin n) := let F := (multilinear_map.mk_pi_algebra_fin R n (exterior_algebra R M)).comp_linear_map (λ i, ι R) in { map_eq_zero_of_eq' := λ f x y hfxy hxy, begin rw [multilinear_map.comp_linear_map_apply, multilinear_map.mk_pi_algebra_fin_apply], wlog h : x < y := lt_or_gt_of_ne hxy using x y, clear hxy, induction n with n hn generalizing x y, { exact x.elim0, }, { rw [list.of_fn_succ, list.prod_cons], by_cases hx : x = 0, -- one of the repeated terms is on the left { rw hx at hfxy h, rw [hfxy, ←fin.succ_pred y (ne_of_lt h).symm], exact ι_mul_prod_list (f ∘ fin.succ) _, }, -- ignore the left-most term and induct on the remaining ones, decrementing indices { convert mul_zero _, refine hn (λ i, f $ fin.succ i) (x.pred hx) (y.pred (ne_of_lt $ lt_of_le_of_lt x.zero_le h).symm) (fin.pred_lt_pred_iff.mpr h) _, simp only [fin.succ_pred], exact hfxy, } } end, to_fun := F, ..F} variables {R} lemma ι_multi_apply {n : ℕ} (v : fin n → M) : ι_multi R n v = (list.of_fn $ λ i, ι R (v i)).prod := rfl end exterior_algebra namespace tensor_algebra variables {R M} /-- The canonical image of the `tensor_algebra` in the `exterior_algebra`, which maps `tensor_algebra.ι R x` to `exterior_algebra.ι R x`. -/ def to_exterior : tensor_algebra R M →ₐ[R] exterior_algebra R M := tensor_algebra.lift R (exterior_algebra.ι R) @[simp] lemma to_exterior_ι (m : M) : (tensor_algebra.ι R m).to_exterior = exterior_algebra.ι R m := by simp [to_exterior] end tensor_algebra
13727c699c715ef8ee7f6f670277edf1754f1de8
9a0b1b3a653ea926b03d1495fef64da1d14b3174
/tidy/lib/env.lean
90a8ee2926867d8d5b899c598a40d9f3be941246
[ "Apache-2.0" ]
permissive
khoek/mathlib-tidy
8623b27b4e04e7d598164e7eaf248610d58f768b
866afa6ab597c47f1b72e8fe2b82b97fff5b980f
refs/heads/master
1,585,598,975,772
1,538,659,544,000
1,538,659,544,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
868
lean
namespace environment meta def decl_omap {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_omap $ λ d, some (f d) meta def get_decls (e : environment) : list declaration := e.decl_map id meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name -- Warning, I have to compute a list of all of the declarations first. meta def decl_ommap {α : Type} (e : environment) (f : declaration → tactic (option α)) : tactic (list α) := e.get_decls.mfoldl (λ l d, do r ← f d, return $ match r with | some r := r :: l | none := l end ) [] end environment
47e7c8b6c7fa4bbbf5c214e1ba1287c5ad4e1578
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/category_theory/limits/preserves.lean
395b5eace7ff4be3244fa79833d5f1110c18069c
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,243
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.limits.limits /-! # Preservation and reflection of (co)limits. There are various distinct notions of "preserving limits". The one we aim to capture here is: A functor F : C → D "preserves limits" if it sends every limit cone in C to a limit cone in D. Informally, F preserves all the limits which exist in C. Note that: * Of course, we do not want to require F to *strictly* take chosen limit cones of C to chosen limit cones of D. Indeed, the above definition makes no reference to a choice of limit cones so it makes sense without any conditions on C or D. * Some diagrams in C may have no limit. In this case, there is no condition on the behavior of F on such diagrams. There are other notions (such as "flat functor") which impose conditions also on diagrams in C with no limits, but these are not considered here. In order to be able to express the property of preserving limits of a certain form, we say that a functor F preserves the limit of a diagram K if F sends every limit cone on K to a limit cone. This is vacuously satisfied when K does not admit a limit, which is consistent with the above definition of "preserves limits". -/ 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 {J : Type v} [small_category J] {K : J ⥤ C} class preserves_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cone K}, is_limit c → is_limit (F.map_cone c)) class preserves_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cocone K}, is_colimit c → is_colimit (F.map_cocone c)) /-- A functor which preserves limits preserves chosen limits up to isomorphism. -/ def preserves_limit_iso (K : J ⥤ C) [has_limit.{v} K] (F : C ⥤ D) [has_limit.{v} (K ⋙ F)] [preserves_limit K F] : F.obj (limit K) ≅ limit (K ⋙ F) := is_limit.cone_point_unique_up_to_iso (preserves_limit.preserves (limit.is_limit K)) (limit.is_limit (K ⋙ F)) /-- A functor which preserves colimits preserves chosen colimits up to isomorphism. -/ def preserves_colimit_iso (K : J ⥤ C) [has_colimit.{v} K] (F : C ⥤ D) [has_colimit.{v} (K ⋙ F)] [preserves_colimit K F] : F.obj (colimit K) ≅ colimit (K ⋙ F) := is_colimit.cone_point_unique_up_to_iso (preserves_colimit.preserves (colimit.is_colimit K)) (colimit.is_colimit (K ⋙ F)) class preserves_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_limit : Π {K : J ⥤ C}, preserves_limit K F) class preserves_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_colimit : Π {K : J ⥤ C}, preserves_colimit K F) class preserves_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_limits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_limits_of_shape J F) class preserves_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_colimits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_colimits_of_shape J F) attribute [instance, priority 100] -- see Note [lower instance priority] preserves_limits_of_shape.preserves_limit preserves_limits.preserves_limits_of_shape preserves_colimits_of_shape.preserves_colimit preserves_colimits.preserves_colimits_of_shape instance preserves_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_limits_subsingleton (F : C ⥤ D) : subsingleton (preserves_limits F) := by { split, intros, cases a, cases b, cc } instance preserves_colimits_subsingleton (F : C ⥤ D) : subsingleton (preserves_colimits F) := by { split, intros, cases a, cases b, cc } instance id_preserves_limits : preserves_limits (𝟭 C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_preserves_colimits : preserves_colimits (𝟭 C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) local attribute [elab_simple] preserves_limit.preserves preserves_colimit.preserves instance comp_preserves_limit [preserves_limit K F] [preserves_limit (K ⋙ F) G] : preserves_limit K (F ⋙ G) := ⟨λ c h, preserves_limit.preserves (preserves_limit.preserves h)⟩ instance comp_preserves_colimit [preserves_colimit K F] [preserves_colimit (K ⋙ F) G] : preserves_colimit K (F ⋙ G) := ⟨λ c h, preserves_colimit.preserves (preserves_colimit.preserves h)⟩ end /-- If F preserves one limit cone for the diagram K, then it preserves any limit cone for K. -/ def preserves_limit_of_preserves_limit_cone {F : C ⥤ D} {t : cone K} (h : is_limit t) (hF : is_limit (F.map_cone t)) : preserves_limit K F := ⟨λ t' h', is_limit.of_iso_limit hF (functor.map_iso _ (is_limit.unique_up_to_iso h h'))⟩ /-- If F preserves one colimit cocone for the diagram K, then it preserves any colimit cocone for K. -/ def preserves_colimit_of_preserves_colimit_cocone {F : C ⥤ D} {t : cocone K} (h : is_colimit t) (hF : is_colimit (F.map_cocone t)) : preserves_colimit K F := ⟨λ t' h', is_colimit.of_iso_colimit hF (functor.map_iso _ (is_colimit.unique_up_to_iso h h'))⟩ /- A functor F : C → D reflects limits if whenever the image of a cone under F is a limit cone in D, the cone was already a limit cone in C. Note that again we do not assume a priori that D actually has any limits. -/ class reflects_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cone K}, is_limit (F.map_cone c) → is_limit c) class reflects_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cocone K}, is_colimit (F.map_cocone c) → is_colimit c) class reflects_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_limit : Π {K : J ⥤ C}, reflects_limit K F) class reflects_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_colimit : Π {K : J ⥤ C}, reflects_colimit K F) class reflects_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_limits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_limits_of_shape J F) class reflects_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_colimits_of_shape J F) instance reflects_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_limits_subsingleton (F : C ⥤ D) : subsingleton (reflects_limits F) := by { split, intros, cases a, cases b, cc } instance reflects_colimits_subsingleton (F : C ⥤ D) : subsingleton (reflects_colimits F) := by { split, intros, cases a, cases b, cc } @[priority 100] -- see Note [lower instance priority] instance reflects_limit_of_reflects_limits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_limits_of_shape J F] : reflects_limit K F := reflects_limits_of_shape.reflects_limit @[priority 100] -- see Note [lower instance priority] instance reflects_colimit_of_reflects_colimits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_colimits_of_shape J F] : reflects_colimit K F := reflects_colimits_of_shape.reflects_colimit @[priority 100] -- see Note [lower instance priority] instance reflects_limits_of_shape_of_reflects_limits (F : C ⥤ D) [H : reflects_limits F] : reflects_limits_of_shape J F := reflects_limits.reflects_limits_of_shape @[priority 100] -- see Note [lower instance priority] instance reflects_colimits_of_shape_of_reflects_colimits (F : C ⥤ D) [H : reflects_colimits F] : reflects_colimits_of_shape J F := reflects_colimits.reflects_colimits_of_shape instance id_reflects_limits : reflects_limits (𝟭 C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_reflects_colimits : reflects_colimits (𝟭 C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_reflects_limit [reflects_limit K F] [reflects_limit (K ⋙ F) G] : reflects_limit K (F ⋙ G) := ⟨λ c h, reflects_limit.reflects (reflects_limit.reflects h)⟩ instance comp_reflects_colimit [reflects_colimit K F] [reflects_colimit (K ⋙ F) G] : reflects_colimit K (F ⋙ G) := ⟨λ c h, reflects_colimit.reflects (reflects_colimit.reflects h)⟩ end end category_theory.limits
b5c425f1b7485d970f5b9b2fc160518d9cbe7af4
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/equiv/local_equiv.lean
2b34575485843045b9e5e972ea2715f99797e621
[ "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
24,804
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.basic /-! # Local equivalences This files defines equivalences between subsets of given types. An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two local equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`. ## Main definitions `equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ `local_equiv.symm` : the inverse of a local equiv `local_equiv.trans` : the composition of two local equivs `local_equiv.refl` : the identity local equiv `local_equiv.of_set` : the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local equivs (see below in implementation notes) ## Implementation notes There are at least three possible implementations of local equivalences: * equivs on subtypes * pairs of functions taking values in `option α` and `option β`, equal to none where the local equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The local_equiv version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`). In particular, the equality notion between local equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no local equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal local equivs, this is not an issue in practice. Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. -/ mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining readability. The typical use case is the following, in a file on manifolds: If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste its output. The list of lemmas should be reasonable (contrary to the output of `squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick enough. " -- register in the simpset `mfld_simps` several lemmas that are often useful when dealing -- with manifolds attribute [mfld_simps] id.def function.comp.left_id set.mem_set_of_eq set.image_eq_empty set.univ_inter set.preimage_univ set.prod_mk_mem_set_prod_eq and_true set.mem_univ set.mem_image_of_mem true_and set.mem_inter_eq set.mem_preimage function.comp_app set.inter_subset_left set.mem_prod set.range_id and_self set.mem_range_self eq_self_iff_true forall_const forall_true_iff set.inter_univ set.preimage_id function.comp.right_id not_false_iff and_imp set.prod_inter_prod set.univ_prod_univ true_or or_true namespace tactic.interactive /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ meta def mfld_set_tac : tactic unit := do goal ← tactic.target, match goal with | `(%%e₁ = %%e₂) := `[ext my_y, split; { assume h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps }] | `(%%e₁ ⊆ %%e₂) := `[assume my_y h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps] | _ := tactic.fail "goal should be an equality or an inclusion" end end tactic.interactive open function set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ @[nolint has_inhabited_instance] structure local_equiv (α : Type*) (β : Type*) := (to_fun : α → β) (inv_fun : β → α) (source : set α) (target : set β) (map_source' : ∀{x}, x ∈ source → to_fun x ∈ target) (map_target' : ∀{x}, x ∈ target → inv_fun x ∈ source) (left_inv' : ∀{x}, x ∈ source → inv_fun (to_fun x) = x) (right_inv' : ∀{x}, x ∈ target → to_fun (inv_fun x) = x) /-- Associating a local_equiv to an equiv-/ def equiv.to_local_equiv (e : equiv α β) : local_equiv α β := { to_fun := e.to_fun, inv_fun := e.inv_fun, source := univ, target := univ, map_source' := λx hx, mem_univ _, map_target' := λy hy, mem_univ _, left_inv' := λx hx, e.left_inv x, right_inv' := λx hx, e.right_inv x } namespace local_equiv variables (e : local_equiv α β) (e' : local_equiv β γ) /-- The inverse of a local equiv -/ protected def symm : local_equiv β α := { to_fun := e.inv_fun, inv_fun := e.to_fun, source := e.target, target := e.source, map_source' := e.map_target', map_target' := e.map_source', left_inv' := e.right_inv', right_inv' := e.left_inv' } instance : has_coe_to_fun (local_equiv α β) := ⟨_, local_equiv.to_fun⟩ @[simp, mfld_simps] theorem coe_mk (f : α → β) (g s t ml mr il ir) : (local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp, mfld_simps] lemma to_fun_as_coe : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h protected lemma maps_to : maps_to e e.source e.target := λ _, e.map_source @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h protected lemma left_inv_on : left_inv_on e.symm e e.source := λ _, e.left_inv @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma right_inv_on : right_inv_on e.symm e e.target := λ _, e.right_inv /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv : equiv (e.source) (e.target) := { to_fun := λ x, ⟨e x, e.map_source x.mem⟩, inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩, left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx, right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy } @[simp, mfld_simps] lemma symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := by { cases e, refl } /-- A local equiv induces a bijection between its source and target -/ lemma bij_on_source : bij_on e e.source e.target := inv_on.bij_on ⟨e.left_inv_on, e.right_inv_on⟩ e.maps_to e.symm_maps_to lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := begin refine subset.antisymm (λx hx, _) (λx hx, _), { rcases (mem_image _ _ _).1 hx with ⟨y, ys, hy⟩, rw ← hy, split, { apply e.map_source, exact h ys }, { rwa [mem_preimage, e.left_inv (h ys)] } }, { rw ← e.right_inv hx.1, exact mem_image_of_mem _ hx.2 } end lemma image_inter_source_eq (s : set α) : e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' (s ∩ e.source) := e.image_eq_target_inter_inv_preimage (inter_subset_right _ _) lemma image_inter_source_eq' (s : set α) : e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' s := begin rw e.image_eq_target_inter_inv_preimage (inter_subset_right _ _), ext x, split; { assume hx, simp at hx, simp [hx] } end lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_inter_target_eq (s : set β) : e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' (s ∩ e.target) := e.symm.image_inter_source_eq _ lemma symm_image_inter_target_eq' (s : set β) : e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' s := e.symm.image_inter_source_eq' _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := begin ext x, split, { rintros ⟨hx, xs⟩, simp only [mem_preimage, hx, e.left_inv, mem_preimage] at xs, exact ⟨hx, xs⟩ }, { rintros ⟨hx, xs⟩, simp [hx, xs] } end lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma image_source_eq_target : e '' e.source = e.target := e.bij_on_source.image_eq lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := λx hx, e.map_source hx lemma inv_image_target_eq_source : e.symm '' e.target = e.source := e.symm.bij_on_source.image_eq lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := λx hx, e.map_target hx /-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/ @[ext] protected lemma ext {e e' : local_equiv α β} (h : ∀x, e x = e' x) (hsymm : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := begin have A : (e : α → β) = e', by { ext x, exact h x }, have B : (e.symm : β → α) = e'.symm, by { ext x, exact hsymm x }, have I : e '' e.source = e.target := e.image_source_eq_target, have I' : e' '' e'.source = e'.target := e'.image_source_eq_target, rw [A, hs, I'] at I, cases e; cases e', simp * at * end /-- Restricting a local equivalence to e.source ∩ s -/ protected def restr (s : set α) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := e.source ∩ s, target := e.target ∩ e.symm⁻¹' s, map_source' := λx hx, begin simp only with mfld_simps at hx, simp only [hx] with mfld_simps, end, map_target' := λy hy, begin simp only with mfld_simps at hy, simp only [hy] with mfld_simps, end, left_inv' := λx hx, e.left_inv hx.1, right_inv' := λy hy, e.right_inv hy.1 } @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl @[simp, mfld_simps] lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp, mfld_simps] lemma restr_univ {e : local_equiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity local equiv -/ protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv @[simp, mfld_simps] lemma refl_source : (local_equiv.refl α).source = univ := rfl @[simp, mfld_simps] lemma refl_target : (local_equiv.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl @[simp, mfld_simps] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_restr_source (s : set α) : ((local_equiv.refl α).restr s).source = s := by simp @[simp, mfld_simps] lemma refl_restr_target (s : set α) : ((local_equiv.refl α).restr s).target = s := by { change univ ∩ id⁻¹' s = s, simp } /-- The identity local equiv on a set `s` -/ def of_set (s : set α) : local_equiv α α := { to_fun := id, inv_fun := id, source := s, target := s, map_source' := λx hx, hx, map_target' := λx hx, hx, left_inv' := λx hx, rfl, right_inv' := λx hx, rfl } @[simp, mfld_simps] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl @[simp, mfld_simps] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl @[simp, mfld_simps] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm (s : set α) : (local_equiv.of_set s).symm = local_equiv.of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) : local_equiv α γ := { to_fun := e' ∘ e, inv_fun := e.symm ∘ e'.symm, source := e.source, target := e'.target, map_source' := λx hx, by simp [h.symm, hx], map_target' := λy hy, by simp [h, hy], left_inv' := λx hx, by simp [hx, h.symm], right_inv' := λy hy, by simp [hy, h] } /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_equiv α γ := local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _) @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl @[simp, mfld_simps] lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := by mfld_set_tac lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := by rw [e.trans_source', inter_comm e.target, e.symm_image_inter_target_eq] lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := image_source_eq_target (local_equiv.symm (local_equiv.restr (local_equiv.symm e) (e'.source))) @[simp, mfld_simps] lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp, mfld_simps] lemma trans_refl : e.trans (local_equiv.refl β) = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) @[simp, mfld_simps] lemma refl_trans : (local_equiv.refl α).trans e = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id]) lemma trans_refl_restr (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) lemma trans_refl_restr' (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] } lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc } /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same local equiv. -/ def eq_on_source (e e' : local_equiv α β) : Prop := e.source = e'.source ∧ (e.source.eq_on e e') /-- `eq_on_source` is an equivalence relation -/ instance eq_on_source_setoid : setoid (local_equiv α β) := { r := eq_on_source, iseqv := ⟨ λe, by simp [eq_on_source], λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 hx).symm }, λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2, h.2 hx], rwa ← h.1 }⟩⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- Two equivalent local equivs have the same source -/ lemma eq_on_source.source_eq {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local equivs coincide on the source -/ lemma eq_on_source.eq_on {e e' : local_equiv α β} (h : e ≈ e') : e.source.eq_on e e' := h.2 /-- Two equivalent local equivs have the same target -/ lemma eq_on_source.target_eq {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target := by simp only [← image_source_eq_target, ← h.source_eq, h.2.image_eq] /-- If two local equivs are equivalent, so are their inverses. -/ lemma eq_on_source.symm' {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := begin refine ⟨h.target_eq, eq_on_of_left_inv_on_of_right_inv_on e.left_inv_on _ _⟩; simp only [symm_source, h.target_eq, h.source_eq, e'.symm_maps_to], exact e'.right_inv_on.congr_right e'.symm_maps_to (h.source_eq ▸ h.eq_on.symm), end /-- Two equivalent local equivs have coinciding inverses on the target -/ lemma eq_on_source.symm_eq_on {e e' : local_equiv α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.eq_on /-- Composition of local equivs respects equivalence -/ lemma eq_on_source.trans' {e e' : local_equiv α β} {f f' : local_equiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := begin split, { rw [trans_source'', trans_source'', ← he.target_eq, ← hf.1], exact (he.symm'.eq_on.mono $ inter_subset_left _ _).image_eq }, { assume x hx, rw trans_source at hx, simp [(he.2 hx.1).symm, hf.2 hx.2] } end /-- Restriction of local equivs respects equivalence -/ lemma eq_on_source.restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := begin split, { simp [he.1] }, { assume x hx, simp only [mem_inter_eq, restr_source] at hx, exact he.2 hx.1 } end /-- Preimages are respected by equivalence -/ lemma eq_on_source.source_inter_preimage_eq {e e' : local_equiv α β} (he : e ≈ e') (s : set β) : e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s := begin ext x, simp only [mem_inter_eq, mem_preimage], split, { assume hx, rwa [← he.2 hx.1, ← he.source_eq] }, { assume hx, rwa [← (setoid.symm he).2 hx.1, he.source_eq] } end /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_equiv.of_set e.source := begin have A : (e.trans e.symm).source = e.source, by mfld_set_tac, refine ⟨by simp [A], λx hx, _⟩, rw A at hx, simp only [hx] with mfld_simps end /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ lemma trans_symm_self : e.symm.trans e ≈ local_equiv.of_set e.target := trans_self_symm (e.symm) /-- Two equivalent local equivs are equal when the source and target are univ -/ lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := begin apply local_equiv.ext (λx, _) (λx, _) h.1, { apply h.2, rw s, exact mem_univ _ }, { apply h.symm'.2, rw [symm_source, t], exact mem_univ _ } end section prod /-- The product of two local equivs, as a local equiv on the product. -/ def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := { source := set.prod e.source e'.source, target := set.prod e.target e'.target, to_fun := λp, (e p.1, e' p.2), inv_fun := λp, (e.symm p.1, e'.symm p.2), map_source' := λp hp, by { simp at hp, simp [hp] }, map_target' := λp hp, by { simp at hp, simp [map_target, hp] }, left_inv' := λp hp, by { simp at hp, simp [hp] }, right_inv' := λp hp, by { simp at hp, simp [hp] } } @[simp, mfld_simps] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl @[simp, mfld_simps] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := by ext x; simp [prod_coe_symm] @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} (e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext x; simp [ext_iff]; tauto end prod end local_equiv namespace set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence between `α` and `β`. -/ @[simps] noncomputable def bij_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (t : set β) (hf : bij_on f s t) : local_equiv α β := { to_fun := f, inv_fun := inv_fun_on f s, source := s, target := t, map_source' := hf.maps_to, map_target' := hf.surj_on.maps_to_inv_fun_on, left_inv' := hf.inv_on_inv_fun_on.1, right_inv' := hf.inv_on_inv_fun_on.2 } /-- A map injective on a subset of its domain provides a local equivalence. -/ @[simp, mfld_simps] noncomputable def inj_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (hf : inj_on f s) : local_equiv α β := hf.bij_on_image.to_local_equiv f s (f '' s) end set namespace equiv /- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local equiv to that of the equiv. -/ variables (e : equiv α β) (e' : equiv β γ) @[simp, mfld_simps] lemma to_local_equiv_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma to_local_equiv_symm_coe : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma to_local_equiv_source : e.to_local_equiv.source = univ := rfl @[simp, mfld_simps] lemma to_local_equiv_target : e.to_local_equiv.target = univ := rfl @[simp, mfld_simps] lemma refl_to_local_equiv : (equiv.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv]) end equiv
fe634b5b4bd369de6342fd576127aff21c4b16e3
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/GetConst.lean
e16e5161f025e5e8745073e6e6db60a38edc7e79
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,516
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.GlobalInstances namespace Lean.Meta private def canUnfoldDefault (cfg : Config) (info : ConstantInfo) : CoreM Bool := do match cfg.transparency with | .all => return true | .default => return !(← isIrreducible info.name) | m => if (← isReducible info.name) then return true else if m == .instances && isGlobalInstance (← getEnv) info.name then return true else return false def canUnfold (info : ConstantInfo) : MetaM Bool := do let ctx ← read if let some f := ctx.canUnfold? then f ctx.config info else canUnfoldDefault ctx.config info def getConst? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(.thmInfo _)) => getTheoremInfo info | some (info@(.defnInfo _)) => if (← canUnfold info) then return info else return none | some info => return some info | none => throwUnknownConstant constName def getConstNoEx? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(.thmInfo _)) => getTheoremInfo info | some (info@(.defnInfo _)) => if (← canUnfold info) then return info else return none | some info => return some info | none => return none end Meta
e44d49a1d8dff9f82eaf4dda2a326a416f7440da
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/seq/wseq.lean
c55be3a1b2301d47a5e2b8e4eb9b35aea12f4df7
[ "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
56,216
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.basic import data.seq.seq namespace stream open function universes u v w /- coinductive wseq (α : Type u) : Type u | nil : wseq α | cons : α → wseq α → wseq α | think : wseq α → wseq α -/ /-- Weak sequences. While the `seq` structure allows for lists which may not be finite, a weak sequence also allows the computation of each element to involve an indeterminate amount of computation, including possibly an infinite loop. This is represented as a regular `seq` interspersed with `none` elements to indicate that computation is ongoing. This model is appropriate for Haskell style lazy lists, and is closed under most interesting computation patterns on infinite lists, but conversely it is difficult to extract elements from it. -/ def wseq (α) := seq (option α) namespace wseq variables {α : Type u} {β : Type v} {γ : Type w} /-- Turn a sequence into a weak sequence -/ def of_seq : seq α → wseq α := (<$>) some /-- Turn a list into a weak sequence -/ def of_list (l : list α) : wseq α := of_seq l /-- Turn a stream into a weak sequence -/ def of_stream (l : stream α) : wseq α := of_seq l instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩ instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩ instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩ /-- The empty weak sequence -/ def nil : wseq α := seq.nil instance : inhabited (wseq α) := ⟨nil⟩ /-- Prepend an element to a weak sequence -/ def cons (a : α) : wseq α → wseq α := seq.cons (some a) /-- Compute for one tick, without producing any elements -/ def think : wseq α → wseq α := seq.cons none /-- Destruct a weak sequence, to (eventually possibly) produce either `none` for `nil` or `some (a, s)` if an element is produced. -/ def destruct : wseq α → computation (option (α × wseq α)) := computation.corec (λ s, match seq.destruct s with | none := sum.inl none | some (none, s') := sum.inr s' | some (some a, s') := sum.inl (some (a, s')) end) /-- Recursion principle for weak sequences, compare with `list.rec_on`. -/ def rec_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s := seq.rec_on s h1 (λ o, option.rec_on o h3 h2) /-- membership for weak sequences-/ protected def mem (a : α) (s : wseq α) := seq.mem (some a) s instance : has_mem α (wseq α) := ⟨wseq.mem⟩ theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a /-- Get the head of a weak sequence. This involves a possibly infinite computation. -/ def head (s : wseq α) : computation (option α) := computation.map ((<$>) prod.fst) (destruct s) /-- Encode a computation yielding a weak sequence into additional `think` constructors in a weak sequence -/ def flatten : computation (wseq α) → wseq α := seq.corec (λ c, match computation.destruct c with | sum.inl s := seq.omap return (seq.destruct s) | sum.inr c' := some (none, c') end) /-- Get the tail of a weak sequence. This doesn't need a `computation` wrapper, unlike `head`, because `flatten` allows us to hide this in the construction of the weak sequence itself. -/ def tail (s : wseq α) : wseq α := flatten $ (λ o, option.rec_on o nil prod.snd) <$> destruct s /-- drop the first `n` elements from `s`. -/ def drop (s : wseq α) : ℕ → wseq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Get the nth element of `s`. -/ def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n) /-- Convert `s` to a list (if it is finite and completes in finite time). -/ def to_list (s : wseq α) : computation (list α) := @computation.corec (list α) (list α × wseq α) (λ ⟨l, s⟩, match seq.destruct s with | none := sum.inl l.reverse | some (none, s') := sum.inr (l, s') | some (some a, s') := sum.inr (a::l, s') end) ([], s) /-- Get the length of `s` (if it is finite and completes in finite time). -/ def length (s : wseq α) : computation ℕ := @computation.corec ℕ (ℕ × wseq α) (λ ⟨n, s⟩, match seq.destruct s with | none := sum.inl n | some (none, s') := sum.inr (n, s') | some (some a, s') := sum.inr (n+1, s') end) (0, s) /-- A weak sequence is finite if `to_list s` terminates. Equivalently, it is a finite number of `think` and `cons` applied to `nil`. -/ class is_finite (s : wseq α) : Prop := (out : (to_list s).terminates) instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h.out /-- Get the list corresponding to a finite weak sequence. -/ def get (s : wseq α) [is_finite s] : list α := (to_list s).get /-- A weak sequence is *productive* if it never stalls forever - there are always a finite number of `think`s between `cons` constructors. The sequence itself is allowed to be infinite though. -/ class productive (s : wseq α) : Prop := (nth_terminates : ∀ n, (nth s n).terminates) theorem productive_iff (s : wseq α) : productive s ↔ ∀ n, (nth s n).terminates := ⟨λ h, h.1, λ h, ⟨h⟩⟩ instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h.nth_terminates instance head_terminates (s : wseq α) [productive s] : (head s).terminates := s.nth_terminates 0 /-- Replace the `n`th element of `s` with `a`. -/ def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (some a, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Remove the `n`th element of `s`. -/ def remove_nth (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (none, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Map the elements of `s` over `f`, removing any values that yield `none`. -/ def filter_map (f : α → option β) : wseq α → wseq β := seq.corec (λ s, match seq.destruct s with | none := none | some (none, s') := some (none, s') | some (some a, s') := some (f a, s') end) /-- Select the elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α := filter_map (λ a, if p a then some a else none) -- example of infinite list manipulations /-- Get the first element of `s` satisfying `p`. -/ def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) := head $ filter p s /-- Zip a function over two weak sequences -/ def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ := @seq.corec (option γ) (wseq α × wseq β) (λ ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (none, s1, s2') | some (none, s1'), some (some a2, s2') := some (none, s1', s2) | some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2') | _, _ := none end) (s1, s2) /-- Zip two weak sequences into a single sequence of pairs -/ def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk /-- Get the list of indexes of elements of `s` satisfying `p` -/ def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ := (zip s (stream.nats : wseq ℕ)).filter_map (λ ⟨a, n⟩, if p a then some n else none) /-- Get the index of the first element of `s` satisfying `p` -/ def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ := (λ o, option.get_or_else o 0) <$> head (find_indexes p s) /-- Get the index of the first occurrence of `a` in `s` -/ def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a) /-- Get the indexes of occurrences of `a` in `s` -/ def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a) /-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in some order (nondeterministically). -/ def union (s1 s2 : wseq α) : wseq α := @seq.corec (option α) (wseq α × wseq α) (λ ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | none, none := none | some (a1, s1'), none := some (a1, s1', nil) | none, some (a2, s2') := some (a2, nil, s2') | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (some a1, s1', s2') | some (none, s1'), some (some a2, s2') := some (some a2, s1', s2') | some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2') end) (s1, s2) /-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/ def is_empty (s : wseq α) : computation bool := computation.map option.is_none $ head s /-- Calculate one step of computation -/ def compute (s : wseq α) : wseq α := match seq.destruct s with | some (none, s') := s' | _ := s end /-- Get the first `n` elements of a weak sequence -/ def take (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ ⟨n, s⟩, match n, seq.destruct s with | 0, _ := none | m+1, none := none | m+1, some (none, s') := some (none, m+1, s') | m+1, some (some a, s') := some (some a, m, s') end) (n, s) /-- Split the sequence at position `n` into a finite initial segment and the weak sequence tail -/ def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) := @computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ ⟨n, l, s⟩, match n, seq.destruct s with | 0, _ := sum.inl (l.reverse, s) | m+1, none := sum.inl (l.reverse, s) | m+1, some (none, s') := sum.inr (n, l, s') | m+1, some (some a, s') := sum.inr (m, a::l, s') end) (n, [], s) /-- Returns `tt` if any element of `s` satisfies `p` -/ def any (s : wseq α) (p : α → bool) : computation bool := computation.corec (λ s : wseq α, match seq.destruct s with | none := sum.inl ff | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inl tt else sum.inr s' end) s /-- Returns `tt` if every element of `s` satisfies `p` -/ def all (s : wseq α) (p : α → bool) : computation bool := computation.corec (λ s : wseq α, match seq.destruct s with | none := sum.inl tt | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inr s' else sum.inl ff end) s /-- Apply a function to the elements of the sequence to produce a sequence of partial results. (There is no `scanr` because this would require working from the end of the sequence, which may not exist.) -/ def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α := cons a $ @seq.corec (option α) (α × wseq β) (λ ⟨a, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, a, s') | some (some b, s') := let a' := f a b in some (some a', a', s') end) (a, s) /-- Get the weak sequence of initial segments of the input sequence -/ def inits (s : wseq α) : wseq (list α) := cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, l, s') | some (some a, s') := let l' := l.concat a in some (some l'.to_list, l', s') end) (dlist.empty, s) /-- Like take, but does not wait for a result. Calculates `n` steps of computation and returns the sequence computed so far -/ def collect (s : wseq α) (n : ℕ) : list α := (seq.take n s).filter_map id /-- Append two weak sequences. As with `seq.append`, this may not use the second sequence if the first one takes forever to compute -/ def append : wseq α → wseq α → wseq α := seq.append /-- Map a function over a weak sequence -/ def map (f : α → β) : wseq α → wseq β := seq.map (option.map f) /-- Flatten a sequence of weak sequences. (Note that this allows empty sequences, unlike `seq.join`.) -/ def join (S : wseq (wseq α)) : wseq α := seq.join ((λ o : option (wseq α), match o with | none := seq1.ret none | some s := (none, s) end) <$> S) /-- Monadic bind operator for weak sequences -/ def bind (s : wseq α) (f : α → wseq β) : wseq β := join (map f s) /-- lift a relation to a relation over weak sequences -/ @[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) : option (α × wseq α) → option (β × wseq β) → Prop | none none := true | (some (a, s)) (some (b, t)) := R a b ∧ C s t | _ _ := false theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop} (H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) : ∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p | none none h := trivial | (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h | none (some _) h := false.elim h | (some (_, _)) none h := false.elim h theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop} (H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p := lift_rel_o.imp (λ _ _, id) H /-- Definitino of bisimilarity for weak sequences-/ @[simp] def bisim_o (R : wseq α → wseq α → Prop) : option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} : bisim_o R o p → bisim_o S o p := lift_rel_o.imp_right _ H /-- Two weak sequences are `lift_rel R` related if they are either both empty, or they are both nonempty and the heads are `R` related and the tails are `lift_rel R` related. (This is a coinductive definition.) -/ def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop := ∃ C : wseq α → wseq β → Prop, C s t ∧ ∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t) /-- If two sequences are equivalent, then they have the same values and the same computational behavior (i.e. if one loops forever then so does the other), although they may differ in the number of `think`s needed to arrive at the answer. -/ def equiv : wseq α → wseq α → Prop := lift_rel (=) theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t → computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) | ⟨R, h1, h2⟩ := by refine computation.lift_rel.imp _ _ _ (h2 h1); apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩ theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t ↔ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) := ⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), or.inr h, λ s t h, begin have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), { cases h with h h, exact lift_rel_destruct h, assumption }, apply computation.lift_rel.imp _ _ _ h, intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end⟩⟩ infix (name := equiv) ` ~ `:50 := equiv theorem destruct_congr {s t : wseq α} : s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct theorem destruct_congr_iff {s t : wseq α} : s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct_iff theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, begin refine ⟨(=), rfl, λ s t (h : s = t), _⟩, rw ←h, apply computation.lift_rel.refl, intro a, cases a with a, simp, cases a; simp, apply H end theorem lift_rel_o.swap (R : α → β → Prop) (C) : swap (lift_rel_o R C) = lift_rel_o (swap R) (swap C) := by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl } theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) : lift_rel (swap R) s2 s1 := begin refine ⟨swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩, rw [←lift_rel_o.swap, computation.lift_rel.swap], apply lift_rel_destruct h end theorem lift_rel.swap (R : α → β → Prop) : swap (lift_rel R) = lift_rel (swap R) := funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 (h : swap (lift_rel R) s2 s1), by rwa [lift_rel.swap, show swap R = R, from funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s t u h1 h2, begin refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩, rcases h with ⟨t, h1, h2⟩, have h1 := lift_rel_destruct h1, have h2 := lift_rel_destruct h2, refine computation.lift_rel_def.2 ⟨(computation.terminates_of_lift_rel h1).trans (computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩, rcases h1.left ha with ⟨b, hb, t1⟩, have t2 := computation.rel_of_lift_rel h2 hb hc, cases a with a; cases c with c, { trivial }, { cases b, {cases t2}, {cases t1} }, { cases a, cases b with b, {cases t1}, {cases b, cases t2} }, { cases a with a s, cases b with b, {cases t1}, cases b with b t, cases c with c u, cases t1 with ab st, cases t2 with bc tu, exact ⟨H ab bc, t, st, tu⟩ } end 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⟩ @[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s := lift_rel.refl (=) eq.refl @[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s := lift_rel.symm (=) (@eq.symm _) @[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u := lift_rel.trans (=) (@eq.trans _) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ open computation local notation `return` := computation.return @[simp] theorem destruct_nil : destruct (nil : wseq α) = return none := computation.destruct_eq_ret rfl @[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) := computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap] @[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think := computation.destruct_eq_think $ by simp [destruct, think, computation.rmap] @[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none := seq.destruct_nil @[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) := seq.destruct_cons _ _ @[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) := seq.destruct_cons _ _ @[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl @[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl @[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s := begin refine seq.eq_of_bisim (λ s1 s2, flatten (return s2) = s1) _ rfl, intros s' s h, rw ←h, simp [flatten], cases seq.destruct s, { simp }, { cases val with o s', simp } end @[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) := seq.destruct_eq_cons $ by simp [flatten, think] @[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct := begin refine computation.eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, (or.inr ⟨c, rfl, rfl⟩) := begin apply c.rec_on (λ a, _) (λ c', _); repeat {simp}, { cases (destruct a).destruct; simp }, { exact or.inr ⟨c', rfl, rfl⟩ } end end end theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) := terminates_map_iff _ (destruct s) @[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail] @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail] @[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail] @[simp] theorem dropn_nil (n) : drop (nil : wseq α) n = nil := by induction n; simp [*, drop] @[simp] theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop] @[simp] theorem dropn_think (s : wseq α) (n) : drop (think s) n = (drop s n).think := by induction n; simp [*, drop] theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n := congr_arg head (dropn_add _ _ _) theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) := congr_arg head (dropn_tail _ _) @[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil @[simp] theorem join_think (S : wseq (wseq α)) : join (think S) = think (join S) := by { simp [think, join], unfold functor.map, simp [join, seq1.ret] } @[simp] theorem join_cons (s : wseq α) (S) : join (cons s S) = think (append s (join S)) := by { simp [think, join], unfold functor.map, simp [join, cons, append] } @[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _ @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _ @[simp] theorem think_append (s t : wseq α) : append (think s) t = think (append s t) := seq.cons_append _ _ _ @[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _ @[simp] theorem append_assoc (s t u : wseq α) : append (append s t) u = append s (append t u) := seq.append_assoc _ _ _ /-- auxilary defintion of tail over weak sequences-/ @[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α)) | none := return none | (some (a, s)) := destruct s theorem destruct_tail (s : wseq α) : destruct (tail s) = destruct s >>= tail.aux := begin simp [tail], rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc], apply congr_arg, ext1 (_|⟨a, s⟩); apply (@pure_bind computation _ _ _ _ _ _).trans _; simp end /-- auxilary defintion of drop over weak sequences-/ @[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α)) | 0 := return | (n+1) := λ a, tail.aux a >>= drop.aux n theorem drop.aux_none : ∀ n, @drop.aux α n none = return none | 0 := rfl | (n+1) := show computation.bind (return none) (drop.aux n) = return none, by rw [ret_bind, drop.aux_none] theorem destruct_dropn : ∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n | s 0 := (bind_ret' _).symm | s (n+1) := by rw [← dropn_tail, destruct_dropn _ n, destruct_tail, is_lawful_monad.bind_assoc]; refl theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] : terminates (head s) := (head_terminates_iff _).2 $ begin rcases (head_terminates_iff _).1 T with ⟨⟨a, h⟩⟩, simp [tail] at h, rcases exists_of_mem_bind h with ⟨s', h1, h2⟩, unfold functor.map at h1, exact let ⟨t, h3, h4⟩ := computation.exists_of_mem_map h1 in computation.terminates_of_mem h3 end theorem destruct_some_of_destruct_tail_some {s : wseq α} {a} (h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s := begin unfold tail functor.map at h, simp at h, rcases exists_of_mem_bind h with ⟨t, tm, td⟩, clear h, rcases computation.exists_of_mem_map tm with ⟨t', ht', ht2⟩, clear tm, cases t' with t'; rw ←ht2 at td; simp at td, { have := mem_unique td (ret_mem _), contradiction }, { exact ⟨_, ht'⟩ } end theorem head_some_of_head_tail_some {s : wseq α} {a} (h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s := begin unfold head at h, rcases computation.exists_of_mem_map h with ⟨o, md, e⟩, clear h, cases o with o; injection e with h', clear e h', cases destruct_some_of_destruct_tail_some md with a am, exact ⟨_, computation.mem_map ((<$>) (@prod.fst α (wseq α))) am⟩ end theorem head_some_of_nth_some {s : wseq α} {a n} (h : some a ∈ nth s n) : ∃ a', some a' ∈ head s := begin revert a, induction n with n IH; intros, exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h'] end instance productive_tail (s : wseq α) [productive s] : productive (tail s) := ⟨λ n, by rw [nth_tail]; apply_instance⟩ instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) := ⟨λ m, by rw [←nth_add]; apply_instance⟩ /-- Given a productive weak sequence, we can collapse all the `think`s to produce a sequence. -/ def to_seq (s : wseq α) [productive s] : seq α := ⟨λ n, (nth s n).get, λ n h, begin cases e : computation.get (nth s (n + 1)), {assumption}, have := mem_of_get_eq _ e, simp [nth] at this h, cases head_some_of_head_tail_some this with a' h', have := mem_unique h' (@mem_of_get_eq _ _ _ _ h), contradiction end⟩ theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) := by induction h with m' h IH; [exact id, exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)] theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) := nth_terminates_le (nat.zero_le n) theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) := (head_terminates_iff _).1 $ head_terminates_of_nth_terminates T theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) (h2 : ∀ s, C s → C (think s)) : C s := begin apply seq.mem_rec_on M, intros o s' h, cases o with b, { apply h2, cases h, {contradiction}, {assumption} }, { apply h1, apply or.imp_left _ h, intro h, injection h } end @[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s := begin cases s with f al, change some (some a) ∈ some none :: f ↔ some (some a) ∈ f, constructor; intro h, { apply (stream.eq_or_mem_of_mem_cons h).resolve_left, intro, injections }, { apply stream.mem_cons_of_mem _ h } end theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} : some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := begin generalize e : destruct s = c, intro h, revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s; apply s.rec_on _ (λ x s, _) (λ s, _); intros m; have := congr_arg computation.destruct m; simp at this; cases this with i1 i2, { rw [i1, i2], cases s' with f al, unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp, have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp}, rw [h_a_eq_a'], refine ⟨stream.eq_or_mem_of_mem_cons, λ o, _⟩, { cases o with e m, { rw e, apply stream.mem_cons }, { exact stream.mem_cons_of_mem _ m } } }, { simp, exact IH this } end @[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s := eq_or_mem_iff_mem $ by simp [ret_mem] theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s := (mem_cons_iff _ _).2 (or.inr h) theorem mem_cons (s : wseq α) (a) : a ∈ cons a s := (mem_cons_iff _ _).2 (or.inl rfl) theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s := begin intro h, have := h, cases h with n e, revert s, simp [stream.nth], induction n with n IH; intro s; apply s.rec_on _ (λ x s, _) (λ s, _); repeat{simp}; intros m e; injections, { exact or.inr m }, { exact or.inr m }, { apply IH m, rw e, cases tail s, refl } end theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s | 0 h := h | (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h) theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s := begin revert s, induction n with n IH; intros s h, { rcases computation.exists_of_mem_map h with ⟨o, h1, h2⟩, cases o with o; injection h2 with h', cases o with a' s', exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) }, { have := @IH (tail s), rw nth_tail at this, exact mem_of_mem_tail (this h) } end theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n := begin apply mem_rec_on h, { intros a' s' h, cases h with h h, { existsi 0, simp [nth], rw h, apply ret_mem }, { cases h with n h, existsi n+1, simp [nth], exact h } }, { intros s' h, cases h with n h, existsi n, simp [nth], apply think_mem h } end theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n s', some (a, s') ∈ destruct (drop s n) := let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin rcases (head_terminates_iff _).1 ⟨⟨_, h⟩⟩ with ⟨⟨o, om⟩⟩, have := computation.mem_unique (computation.mem_map _ om) h, cases o with o; injection this with i, cases o with a' s', dsimp at i, rw i at om, exact ⟨_, om⟩ end⟩ theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) : ∀ n, computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct (drop s n)) (destruct (drop t n)) | 0 := lift_rel_destruct H | (n+1) := begin simp [destruct_tail], apply lift_rel_bind, apply lift_rel_dropn_destruct n, exact λ a b o, match a, b, o with | none, none, _ := by simp | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2 end end theorem exists_of_lift_rel_left {R : α → β → Prop} {s t} (H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b := let ⟨n, h⟩ := exists_nth_of_mem h, ⟨some (._, s'), sd, rfl⟩ := computation.exists_of_mem_map h, ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in ⟨b, nth_mem (computation.mem_map ((<$>) prod.fst.{v v}) td), ab⟩ theorem exists_of_lift_rel_right {R : α → β → Prop} {s t} (H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b := by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) := let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨⟨_, h⟩⟩ theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ := seq.of_mem_append theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ := seq.mem_append_left theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ @[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) : lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) : lift_rel R (think s) t ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) : lift_rel R s (think t) ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t := by unfold equiv; simp; exact h theorem think_equiv (s : wseq α) : think s ~ s := by unfold equiv; simp; apply equiv.refl theorem think_congr {s t : wseq α} (h : s ~ t) : think s ~ think t := by unfold equiv; simp; exact h theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t := suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from λ s t h o, ⟨this h, this h.symm⟩, begin intros s t h o ho, rcases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩, rw ←dse, cases destruct_congr h with l r, rcases l dsm with ⟨dt, dtm, dst⟩, cases ds with a; cases dt with b, { apply computation.mem_map _ dtm }, { cases b, cases dst }, { cases a, cases dst }, { cases a with a s', cases b with b t', rw dst.left, exact @computation.mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst) _ (destruct t) dtm } end theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s := begin apply computation.mem_rec_on h, { simp }, { intro s', apply equiv.trans, simp [think_equiv] } end theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)} (h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) := let S := λ s t, ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in ⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h, match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin simp, apply lift_rel_bind _ _ h, intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab), intros a b, apply lift_rel_o.imp_right, intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h] end end⟩ theorem flatten_congr {c1 c2 : computation (wseq α)} : computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t := begin apply flatten_congr, unfold functor.map, rw [←bind_ret, ←bind_ret], apply lift_rel_bind _ _ (destruct_congr h), intros a b h, simp, cases a with a; cases b with b, { trivial }, { cases h }, { cases a, cases h }, { cases a with a s', cases b with b t', exact h.right } end theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n := by induction n; simp [*, tail_congr] theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n := head_congr (dropn_congr h _) theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t := suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩, λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in nth_mem ((nth_congr h _ _).1 hn) theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t := by simp only [productive_iff]; exact forall_congr (λ n, terminates_congr $ nth_congr h _) theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t := ⟨λ s t, ∀ n, nth s n ~ nth t n, h, λ s t h, begin refine lift_rel_def.2 ⟨_, _⟩, { rw [←head_terminates_iff, ←head_terminates_iff], exact terminates_congr (h 0) }, { intros a b ma mb, cases a with a; cases b with b, { trivial }, { injection mem_unique (computation.mem_map _ ma) ((h 0 _).2 (computation.mem_map _ mb)) }, { injection mem_unique (computation.mem_map _ ma) ((h 0 _).2 (computation.mem_map _ mb)) }, { cases a with a s', cases b with b t', injection mem_unique (computation.mem_map _ ma) ((h 0 _).2 (computation.mem_map _ mb)) with ab, refine ⟨ab, λ n, _⟩, refine (nth_congr (flatten_equiv (computation.mem_map _ ma)) n).symm.trans ((_ : nth (tail s) n ~ nth (tail t) n).trans (nth_congr (flatten_equiv (computation.mem_map _ mb)) n)), rw [nth_tail, nth_tail], apply h } } end⟩ theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) := begin refine computation.eq_of_bisim (λ c1 c2, ∃ (l : list α) (s : wseq α), c1 = computation.corec length._match_2 (l.length, s) ∧ c2 = computation.map list.length (computation.corec to_list._match_2 (l, s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l, s, h⟩, rw [h.left, h.right], apply s.rec_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l, s, _, _⟩; simp }, { refine ⟨l, s, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := show seq.map some (seq.of_list (a :: l)) = seq.cons (some a) (seq.map some (seq.of_list l)), by simp @[simp] theorem to_list'_nil (l : list α) : computation.corec to_list._match_2 (l, nil) = return l.reverse := destruct_eq_ret rfl @[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) : computation.corec to_list._match_2 (l, cons a s) = (computation.corec to_list._match_2 (a::l, s)).think := destruct_eq_think $ by simp [to_list, cons] @[simp] theorem to_list'_think (l : list α) (s : wseq α) : computation.corec to_list._match_2 (l, think s) = (computation.corec to_list._match_2 (l, s)).think := destruct_eq_think $ by simp [to_list, think] theorem to_list'_map (l : list α) (s : wseq α) : computation.corec to_list._match_2 (l, s) = ((++) l.reverse) <$> to_list s := begin refine computation.eq_of_bisim (λ c1 c2, ∃ (l' : list α) (s : wseq α), c1 = computation.corec to_list._match_2 (l' ++ l, s) ∧ c2 = computation.map ((++) l.reverse) (computation.corec to_list._match_2 (l', s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l', s, h⟩, rw [h.left, h.right], apply s.rec_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l', s, _, _⟩; simp }, { refine ⟨l', s, _, _⟩; simp } end @[simp] theorem to_list_cons (a : α) (s) : to_list (cons a s) = (list.cons a <$> to_list s).think := destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl @[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] := destruct_eq_ret rfl theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) := by induction l with a l IH; simp [ret_mem]; exact think_mem (computation.mem_map _ IH) @[simp] theorem destruct_of_seq (s : seq α) : destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) := destruct_eq_ret $ begin simp [of_seq, head, destruct, seq.destruct, seq.head], rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth], cases seq.nth s 0 with a, { refl }, unfold functor.map, simp [destruct] end @[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head := by simp [head]; cases seq.head s; refl @[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail := begin simp [tail], apply s.rec_on _ (λ x s, _); simp [of_seq], {refl}, rw [seq.head_cons, seq.tail_cons], refl end @[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n) | 0 := rfl | (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq] theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) := by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn] instance productive_of_seq (s : seq α) : productive (of_seq s) := ⟨λ n, by rw nth_of_seq; apply_instance⟩ theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s := begin apply subtype.eq, funext n, dsimp [to_seq], apply get_eq_of_mem, rw nth_of_seq, apply ret_mem end /-- The monadic `return a` is a singleton list containing `a`. -/ def ret (a : α) : wseq α := of_list [a] @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _ @[simp] theorem map_think (f : α → β) (s) : map f (think s) = think (map f s) := seq.map_cons _ _ _ @[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map] @[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret] @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := seq.map_append _ _ _ theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) : map (g ∘ f) s = map g (map f s) := begin dsimp [map], rw ←seq.map_comp, apply congr_fun, apply congr_arg, ext ⟨⟩; refl end theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s := seq.mem_map (option.map f) -- The converse is not true without additional assumptions theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h, (this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _), begin intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S, { refine s.rec_on (S.rec_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try {cases this}; try {contradiction}, substs b' ss, simp at m ⊢, cases o with e IH, { simp [e] }, cases m with e m, { simp [e] }, exact or.imp_left or.inr (IH _ _ rfl m) }, { refine s.rec_on (S.rec_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try { try {have := this.1}, contradiction }; subst ss, { apply or.inr, simp at m ⊢, cases IH s S rfl m with as ex, { exact ⟨s, or.inl rfl, as⟩ }, { rcases ex with ⟨s', sS, as⟩, exact ⟨s', or.inr sS, as⟩ } }, { apply or.inr, simp at m, rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩, exact ⟨s, by simp [sS], as⟩ }, { simp at m IH ⊢, apply IH _ _ rfl m } } end theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨t, tm, bt⟩ := exists_of_mem_join h, ⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩ theorem destruct_map (f : α → β) (s : wseq α) : destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) := begin apply computation.eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧ c2 = computation.map (option.map (prod.map f (map f))) (destruct s)), { intros c1 c2 h, cases h with s h, rw [h.left, h.right], apply s.rec_on _ (λ a s, _) (λ s, _); simp, exact ⟨s, rfl, rfl⟩ }, { exact ⟨s, rfl, rfl⟩ } end theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {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) := ⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t, ⟨s1, s2, rfl, rfl, h1⟩, λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b; simp, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, exact ⟨h2 r, s, rfl, t, rfl, h⟩ } end end⟩ theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t := lift_rel_map _ _ h (λ _ _, congr_arg _) /-- auxilary defintion of `destruct_append` over weak sequences-/ @[simp] def destruct_append.aux (t : wseq α) : option (α × wseq α) → computation (option (α × wseq α)) | none := destruct t | (some (a, s)) := return (some (a, append s t)) theorem destruct_append (s t : wseq α) : destruct (append s t) = (destruct s).bind (destruct_append.aux t) := begin apply computation.eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩, intros c1 c2 h, rcases h with ⟨s, t, h⟩, rw [h.left, h.right], apply s.rec_on _ (λ a s, _) (λ s, _); simp, { apply t.rec_on _ (λ b t, _) (λ t, _); simp, { refine ⟨nil, t, _, _⟩; simp } }, { exact ⟨s, t, rfl, rfl⟩ } end /-- auxilary defintion of `destruct_join` over weak sequences-/ @[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α)) | none := return none | (some (s, S)) := (destruct (append s (join S))).think theorem destruct_join (S : wseq (wseq α)) : destruct (join S) = (destruct S).bind destruct_join.aux := begin apply computation.eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, or.inr ⟨S, rfl, rfl⟩ := begin apply S.rec_on _ (λ s S, _) (λ S, _); simp, { refine or.inr ⟨S, rfl, rfl⟩ } end end end theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β} (h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) : lift_rel R (append s1 s2) (append t1 t2) := ⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1, or.inr ⟨s1, t1, rfl, rfl, h1⟩, λ s t h, match s, t, h with | s, t, or.inl h := begin apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end | ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin simp [destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b, { simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl }, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ } end end⟩ theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop} (ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) : ∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b := begin cases exists_results_of_mem ma with n h, clear ma, revert a S T, apply nat.strong_induction_on n _, intros n IH a S T ST ra, simp [destruct_join] at ra, exact let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra, ⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in by exact match o, p, rop, rs1, rs2, mT with | none, none, _, rs1, rs2, mT := by simp only [destruct_join]; exact ⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩ | some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT := by simp [destruct_append] at rs2; exact let ⟨k1, rs3, ek⟩ := of_results_think rs2, ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3, ⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in by exact match o', p', rop', rs4, rs5, mt with | none, none, _, rs4, rs5', mt := have n1 < n, begin rw [en, ek, ek1], apply lt_of_lt_of_le _ (nat.le_add_right _ _), apply nat.lt_succ_of_le (nat.le_add_right _ _) end, let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩; { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, exact mb } | some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin simp at rs5, refine ⟨some (b, append t' (join T')), _, _⟩, { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, apply ret_mem }, rw eq_of_ret_mem rs5.mem, exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩ end end end end theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)} (h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) := ⟨λ s1 s2, ∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T, ⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin clear _fun_match _x, rw [h1, h2], rw [destruct_append, destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct st), exact λ o p h, match o, p, h with | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩ | none, none, _ := begin dsimp [destruct_append.aux, computation.lift_rel], constructor, { intro, apply lift_rel_join.lem _ ST (λ _ _, id) }, { intros b mb, rw [←lift_rel_o.swap], apply lift_rel_join.lem (swap R), { rw [←lift_rel.swap R, ←lift_rel.swap], apply ST }, { rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)], exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, ⟨t, s, T, S, h2, h1, st, ST⟩ }, { exact mb } } end end end⟩ theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T := lift_rel_join _ h theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → wseq γ} {f2 : β → wseq δ} (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) := lift_rel_join _ (lift_rel_map _ _ h1 @h2) theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2) @[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s := by simp [ret]; apply think_equiv @[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s := begin refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩, intros s' s h, rw ←h, apply lift_rel_rec (λ c1 c2, ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s), { exact λ c1 c2 h, match c1, c2, h with | ._, ._, ⟨s, rfl, rfl⟩ := begin clear h _match, have : ∀ s, ∃ s' : wseq α, (map ret s).join.destruct = (map ret s').join.destruct ∧ destruct s = s'.destruct, from λ s, ⟨s, rfl, rfl⟩, apply s.rec_on _ (λ a s, _) (λ s, _); simp [ret, ret_mem, this, option.exists] end end }, { exact ⟨s, rfl, rfl⟩ } end @[simp] theorem join_append (S T : wseq (wseq α)) : join (append S T) ~ append (join S) (join T) := begin refine ⟨λ s1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T, c1 = destruct (append s (join (append S T))) ∧ c2 = destruct (append s (append (join S) (join T)))) _ _ _ (let ⟨s, S, T, h1, h2⟩ := h in ⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin clear _match h h, apply wseq.rec_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.rec_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.rec_on T _ (λ s T, _) (λ T, _); simp, { refine ⟨s, nil, T, _, _⟩; simp }, { refine ⟨nil, nil, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { refine ⟨nil, S, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { exact ⟨s, S, T, rfl, rfl⟩ } end end end @[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s := begin dsimp [bind], change (λ x, ret (f x)) with (ret ∘ f), rw [map_comp], apply join_map_ret end @[simp] theorem ret_bind (a : α) (f : α → wseq β) : bind (ret a) f ~ f a := by simp [bind] @[simp] theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := begin apply seq.eq_of_bisim (λ s1 s2, ∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply wseq.rec_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.rec_on S _ (λ s S, _) (λ S, _); simp, { exact ⟨map f s, S, rfl, rfl⟩ }, { refine ⟨nil, S, _, _⟩; simp } }, { exact ⟨_, _, rfl, rfl⟩ }, { exact ⟨_, _, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem join_join (SS : wseq (wseq (wseq α))) : join (join SS) ~ join (map join SS) := begin refine ⟨λ s1 s2, ∃ s S SS, s1 = append s (join (append S (join SS))) ∧ s2 = append s (append (join S) (join (map join SS))), ⟨nil, nil, SS, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ s S SS, c1 = destruct (append s (join (append S (join SS)))) ∧ c2 = destruct (append s (append (join S) (join (map join SS))))) _ (destruct s1) (destruct s2) (let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin clear _match h h, apply wseq.rec_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.rec_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.rec_on SS _ (λ S SS, _) (λ SS, _); simp, { refine ⟨nil, S, SS, _, _⟩; simp }, { refine ⟨nil, nil, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { refine ⟨nil, S, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { exact ⟨s, S, SS, rfl, rfl⟩ } end end end @[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) : bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) := begin simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join], apply join_join end instance : monad wseq := { map := @map, pure := @ret, bind := @bind } /- Unfortunately, wseq is not a lawful monad, because it does not satisfy the monad laws exactly, only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient, because the join operation involves lists of quotient elements, with a lifted equivalence relation, and pure quotients cannot handle this type of construction. instance : is_lawful_monad wseq := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end wseq end stream
3af56f82b9be7eb2292a2a9bcb4a362573406907
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/bool/all_any.lean
150e38cf3ab2674cac86fab8bd6e0885ac44d218
[ "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
1,731
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.basic /-! # Boolean quantifiers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This proves a few properties about `list.all` and `list.any`, which are the `bool` universal and existential quantifiers. Their definitions are in core Lean. -/ variables {α : Type*} {p : α → Prop} [decidable_pred p] {l : list α} {a : α} namespace list @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a :: l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ end list
06b9cfb85be8c8d9fa02ef32331106198a61c794
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/order/filter.lean
f7873b0d7083140eae64738955fdf72c0f885d9d
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
75,469
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 Theory of filters on sets. -/ import order.galois_connection data.set data.finset order.zorn open lattice set universes u v w x y local attribute [instance] classical.prop_decidable namespace lattice variables {α : Type u} {ι : Sort v} section variable [complete_lattice α] lemma Inf_eq_finite_sets {s : set α} : Inf s = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t) := le_antisymm (le_infi $ assume t, le_infi $ assume ⟨_, h⟩, Inf_le_Inf h) (le_Inf $ assume b h, infi_le_of_le {b} $ infi_le_of_le (by simp [h]) $ Inf_le $ by simp) lemma infi_insert_finset {ι : Type v} {s : finset ι} {f : ι → α} {i : ι} : (⨅j∈insert i s, f j) = f i ⊓ (⨅j∈s, f j) := by simp [infi_or, infi_inf_eq] lemma infi_empty_finset {ι : Type v} {f : ι → α} : (⨅j∈(∅ : finset ι), f j) = ⊤ := by simp end -- TODO: move lemma inf_left_comm [semilattice_inf α] (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := by rw [← inf_assoc, ← inf_assoc, @inf_comm α _ a] def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}; subst_vars, exact @complete_lattice.le_refl α c, exact @complete_lattice.le_trans α c, exact @complete_lattice.le_antisymm α c, exact @complete_lattice.le_sup_left α c, exact @complete_lattice.le_sup_right α c, exact @complete_lattice.sup_le α c, exact @complete_lattice.inf_le_left α c, exact @complete_lattice.inf_le_right α c, exact @complete_lattice.le_inf α c, exact @complete_lattice.le_top α c, exact @complete_lattice.bot_le α c, exact @complete_lattice.le_Sup α c, exact @complete_lattice.Sup_le α c, exact @complete_lattice.Inf_le α c, exact @complete_lattice.le_Inf α c end end lattice namespace set variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ∩ (g x)) := assume a b h x ⟨h₁, h₂⟩, ⟨hf h h₁, hg h 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 end set open set lattice section order variables {α : Type u} (r : α → α → Prop) local infix `≼` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f z ≼ f x ∧ f z ≼ f y /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, z ≼ x ∧ z ≼ y lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊇) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp [directed_on]; 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₂⟩ end order theorem directed_of_chain {α : Type u} {β : Type v} [preorder β] {f : α → β} {c : set α} (h : zorn.chain (λa b, f b ≤ f a) c) : directed (≤) (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp [this]; exact ⟨b, hb, le_refl _⟩) (assume : a ≠ b, have f b ≤ f a ∨ f a ≤ f b, from h a ha b hb this, or.elim this (assume : f b ≤ f a, ⟨⟨b, hb⟩, this, le_refl _⟩) (assume : f a ≤ f b, ⟨⟨a, ha⟩, le_refl _, this⟩)) structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) namespace filter variables {α : Type u} {f g : filter α} {s t : set α} lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f.sets ↔ s ∈ g.sets := by rw [filter_eq_iff, ext_iff] @[extensionality] protected lemma ext : (∀ s, s ∈ f.sets ↔ s ∈ g.sets) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f.sets := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f.sets → x ⊆ y → y ∈ f.sets := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f.sets → t ∈ f.sets → s ∩ t ∈ f.sets := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f.sets := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f.sets) (h : {x | x ∈ s → x ∈ t} ∈ f.sets) : t ∈ f.sets := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f.sets) → (⋂i∈is, s i) ∈ f.sets := finite.induction_on hf (assume hs, by simp [univ_mem_sets]) (assume i is _ hf hi hs, have h₁ : s i ∈ f.sets, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f.sets, from hi $ assume a ha, hs _ $ by simp [ha], by simp [inter_mem_sets h₁ h₂]) lemma exists_sets_subset_iff : (∃t∈f.sets, t ⊆ s) ↔ s ∈ f.sets := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f.sets) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter [t1, ⋯, tn]` replaces a goal of the form `s ∈ f.sets` and terms `h1 : t1 ∈ f.sets, ⋯, tn ∈ f.sets` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter [t1, ⋯, tn] e` is a short form for `{ filter [t1, ⋯, tn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', match e' with | some e := interactive.exact e | none := skip end end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } instance : inhabited (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ (principal t).sets ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ (principal s).sets := subset.refl _ end principal section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t.sets} ∈ f.sets}, univ_sets := by simp [univ_mem_sets]; exact univ_mem_sets, sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ (join f).sets ↔ {t | s ∈ filter.sets t} ∈ f.sets := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, g.sets ⊆ f.sets, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g.sets, x ∈ f.sets := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ {} : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := {s | generate_sets g s}, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ univ_mem_sets, sets_of_superset := assume x y, hs ▸ mem_sets_of_superset, inter_sets := assume x y, hs ▸ inter_mem_sets } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, hs.symm ▸ iff.refl _ /- Galois insertion from sets of sets into a filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u, generate_sets.basic, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f.sets) (b ∈ g.sets), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ (f ⊓ g).sets ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f.sets) : s ∈ (f ⊓ g).sets := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g.sets) : s ∈ (f ⊓ g).sets := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f.sets) (ht : t ∈ g.sets) : s ∩ t ∈ (f ⊓ g).sets := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α).sets ↔ (∀x, x ∈ s) := iff.refl _ @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.lattice.has_top).1 (top_unique $ assume s hs, (eq_univ_of_forall hs).symm ▸ univ_mem_sets) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.lattice.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α).sets := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ (f ⊔ g).sets ↔ s ∈ f.sets ∧ s ∈ g.sets := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ (Sup s).sets ↔ (∀f∈s, x ∈ (f:filter α).sets) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ (supr f).sets ↔ (∀i, x ∈ (f i).sets) := by simp [supr_sets_eq] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f.sets := show (∀{t}, s ⊆ t → t ∈ f.sets) ↔ s ∈ f.sets, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp lemma monotone_principal : monotone (principal : set α → filter α) := by simp [monotone, principal_mono]; exact assume a b h, h @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp [le_antisymm_iff]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl /- lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f.sets ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f.sets) : ∃x, x ∈ s := have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h, have s ≠ ∅, from assume h, this (h ▸ hs), exists_mem_of_ne_empty this lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} : (∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ := by simp [(@empty_in_sets_eq_bot α f).symm]; exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩ lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets := have ∅ ∈ (f ⊓ principal (- s)).sets, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma infi_sets_eq {f : ι → filter α} (h : directed (≤) f) (ne : nonempty ι) : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := begin simp, exact ⟨i, univ_mem_sets⟩ end, sets_of_superset := begin simp, assume x y i hx hxy, exact ⟨i, mem_sets_of_superset hx hxy⟩ end, inter_sets := begin simp, assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in subset.antisymm (show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i) (Union_subset $ assume i, infi_le f i) lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl lemma Inf_sets_eq_finite {s : set (filter α)} : (Inf s).sets = (⋃ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) := calc (Inf s).sets = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t).sets : by rw [lattice.Inf_eq_finite_sets] ... = (⨆ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) : infi_sets_eq' (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∪ y, ⟨finite_union hx₁ hy₁, union_subset hx₂ hy₂⟩, Inf_le_Inf $ subset_union_left _ _, Inf_le_Inf $ subset_union_right _ _⟩) ⟨∅, by simp⟩ @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.lattice.complete_lattice } private lemma infi_finite_distrib {s : set (filter α)} {f : filter α} (h : finite s) : (⨅ a ∈ s, f ⊔ a) = f ⊔ (Inf s) := finite.induction_on h (by simp only [mem_empty_eq, infi_false, infi_top, Inf_empty, sup_top_eq]) (by intros a s hn hs hi; rw [infi_insert, hi, ← sup_inf_left, Inf_insert]) /- the complementary version with ⨆ g∈s, f ⊓ g does not hold! -/ lemma binfi_sup_eq { f : filter α } {s : set (filter α)} : (⨅ g∈s, f ⊔ g) = f ⊔ Inf s := le_antisymm begin intros t h, cases h with h₁ h₂, rw [Inf_sets_eq_finite] at h₂, simp [and_assoc] at h₂, rcases h₂ with ⟨s', hs', hs's, ht'⟩, have ht : t ∈ (⨅ a ∈ s', f ⊔ a).sets, { rw [infi_finite_distrib], exact ⟨h₁, ht'⟩, exact hs' }, clear h₁ ht', revert ht t, change (⨅ a ∈ s, f ⊔ a) ≤ (⨅ a ∈ s', f ⊔ a), apply infi_le_infi2 _, exact assume i, ⟨i, infi_le_infi2 $ assume h, ⟨hs's h, le_refl _⟩⟩ end (le_infi $ assume g, le_infi $ assume h, sup_le_sup (le_refl f) $ Inf_le h) lemma infi_sup_eq { f : filter α } {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := calc (⨅ x, f ⊔ g x) = (⨅ x (h : ∃i, g i = x), f ⊔ x) : by simp; rw [infi_comm]; simp ... = f ⊔ Inf {x | ∃i, g i = x} : binfi_sup_eq ... = f ⊔ infi g : by rw [Inf_eq_infi]; dsimp; simp; rw [infi_comm]; simp lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⨅a∈s, p a) ≤ t), begin refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, lattice.infi_empty_finset, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, lattice.infi_insert_finset, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this, have eq : (⨅j ∈ s, function.update p a t₁ j) = (⨅j ∈ s, p j), begin congr, funext b, congr, funext h, apply this, assumption end, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, from assume p hpa hp ht, ⟨p a, hpa, (⨅j∈s, p j), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp [union_subset_iff] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := top_unique $ by simp lemma principal_empty : principal (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp [principal_empty, h], assume h, by simp [*, principal_empty]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f.sets) : f ⊓ principal s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ end lattice section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (principal s) = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma mem_map : t ∈ (map m f).sets ↔ {x | m x ∈ t} ∈ f.sets := iff.rfl lemma image_mem_map (hs : s ∈ f.sets) : m '' s ∈ (map m f).sets := f.sets_of_superset hs $ subset_preimage_image m s @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f end map section vmap /-- The inverse map of a filter -/ def vmap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈f.sets, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } end vmap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, univ_sets := by simp, sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t), finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)), by simp [compl_inter, finite_union, ht, hs] } /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) instance : monad filter := { bind := @bind, pure := λ(α : Type u) x, principal {x}, map := @filter.map } instance : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β a f, by simp [bind, Sup_image], bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp [bind, join, map, preimage, principal] } @[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets := by simp; exact id @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } /- map and vmap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_vmap_sets : s ∈ (vmap m g).sets ↔ ∃t∈g.sets, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_vmap (ht : t ∈ g.sets) : m ⁻¹' t ∈ (vmap m g).sets := ⟨t, ht, subset.refl _⟩ lemma vmap_id : vmap id f = f := le_antisymm (assume s, preimage_mem_vmap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma vmap_vmap_comp {m : γ → β} {n : β → α} : vmap m (vmap n f) = vmap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_vmap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem vmap_principal {t : set β} : vmap m (principal t) = principal (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ lemma map_le_iff_le_vmap : map m f ≤ g ↔ f ≤ vmap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_vmap (m : α → β) : galois_connection (map m) (vmap m) := assume f g, map_le_iff_le_vmap lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_vmap m).monotone_l h lemma monotone_map : monotone (map m) | a b := map_mono lemma vmap_mono (h : g₁ ≤ g₂) : vmap m g₁ ≤ vmap m g₂ := (gc_map_vmap m).monotone_u h lemma monotone_vmap : monotone (vmap m) | a b := vmap_mono @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_vmap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_vmap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_vmap m).l_supr @[simp] lemma vmap_top : vmap m ⊤ = ⊤ := (gc_map_vmap m).u_top @[simp] lemma vmap_inf : vmap m (g₁ ⊓ g₂) = vmap m g₁ ⊓ vmap m g₂ := (gc_map_vmap m).u_inf @[simp] lemma vmap_infi {f : ι → filter β} : vmap m (⨅i, f i) = (⨅i, vmap m (f i)) := (gc_map_vmap m).u_infi lemma map_vmap_le : map m (vmap m g) ≤ g := (gc_map_vmap m).l_u_le _ lemma le_vmap_map : f ≤ vmap m (map m f) := (gc_map_vmap m).le_u_l _ @[simp] lemma vmap_bot : vmap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp, by simp⟩ lemma vmap_sup : vmap m (g₁ ⊔ g₂) = vmap m g₁ ⊔ vmap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) (sup_le (vmap_mono le_sup_left) (vmap_mono le_sup_right)) lemma le_map_vmap' {f : filter β} {m : α → β} {s : set β} (hs : s ∈ f.sets) (hm : ∀b∈s, ∃a, m a = b) : f ≤ map m (vmap m f) := assume t' ⟨t, ht, (sub : m ⁻¹' t ⊆ m ⁻¹' t')⟩, by filter_upwards [ht, hs] assume x hxt hxs, let ⟨y, hy⟩ := hm x hxs in hy ▸ sub (show m y ∈ t, from hy.symm ▸ hxt) lemma le_map_vmap {f : filter β} {m : α → β} (hm : ∀x, ∃y, m y = x) : f ≤ map m (vmap m f) := le_map_vmap' univ_mem_sets (assume b _, hm b) lemma vmap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : vmap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp [this, subset.refl], by simp [this, subset.refl]⟩) le_vmap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) map_mono lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have vmap m (map m f) = vmap m (map m g), by rw h, by rwa [vmap_map hm, vmap_map hm] at this lemma vmap_neq_bot {f : filter β} {m : α → β} (hm : ∀t∈f.sets, ∃a, m a ∈ t) : vmap m f ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩, let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s lemma vmap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : vmap m f ≠ ⊥ := vmap_neq_bot $ assume t ht, let ⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht, ⟨a, (ha : m a = b)⟩ := hm b in ⟨a, ha.symm ▸ hx⟩ @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp [*]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h lemma sInter_vmap_sets (f : α → β) (F : filter β) : ⋂₀(vmap f F).sets = ⋂ U ∈ F.sets, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F.sets → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F.sets → f x ∈ B, by simp [set.mem_sInter, set.mem_Inter, mem_vmap_sets, this], split, { intros h U U_in, simpa [set.subset.refl] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f.sets) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f.sets), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f.sets, filter_upwards [h, hs], simp [subset_def] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm) -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≤) f) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ (infi f).sets), have ∃i, preimage m s ∈ (f i).sets, by simp [infi_sets_eq hf hι] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp; assumption, by simp at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (λx y, f x ≤ f y) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp [infi_subtype] ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i (h : p i), map m (f i)) : by simp [infi_subtype] lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f.sets) (htg : t ∈ g.sets) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm (le_inf (map_mono inf_le_left) (map_mono inf_le_right)) (assume s hs, _), simp [map, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y) lemma map_eq_vmap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = vmap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp [h₂, preimage_id] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f.sets), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp [h₁]; apply subset.refl⟩) lemma map_swap_eq_vmap_swap {f : filter (α × β)} : prod.swap <$> f = vmap prod.swap f := map_eq_vmap_of_inverse prod.swap_swap_eq prod.swap_swap_eq /- bind equations -/ @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ (bind f m).sets ↔ ∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets := calc s ∈ (bind f m).sets ↔ {a | s ∈ (m a).sets} ∈ f.sets : by simp [bind] ... ↔ (∃t ∈ f.sets, t ⊆ {a | s ∈ (m a).sets}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) : iff.refl _ lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f.sets) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f.sets), by filter_upwards [h₁, h₂] assume s gh' h', gh' h' lemma bind_sup {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp [bind] lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : bind f h ≤ bind g h := assume s h', h₁ h' lemma principal_bind {s : set α} {f : α → filter β} : (bind (principal s) f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp [Sup_image] lemma seq_mono {β : Type u} {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ <*> g₁ ≤ f₂ <*> g₂ := le_trans (bind_mono2 hf) (bind_mono $ univ_mem_sets' $ assume f, map_mono hg) @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α).sets ↔ a ∈ s := by simp @[simp] lemma mem_return_sets {a : α} {s : set α} : s ∈ (return a : filter α).sets ↔ a ∈ s := mem_pure_sets lemma infi_neq_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≤) f) (hb : ∀i, f i ≠ ⊥): (infi f) ≠ ⊥ := let ⟨x⟩ := hn in assume h, have he: ∅ ∈ (infi f).sets, from h.symm ▸ mem_bot_sets, classical.by_cases (assume : nonempty ι, have ∃i, ∅ ∈ (f i).sets, by rw [infi_sets_eq hd this] at he; simp at he; assumption, let ⟨i, hi⟩ := this in hb i $ bot_unique $ assume s _, (f i).sets_of_superset hi $ empty_subset _) (assume : ¬ nonempty ι, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ this ⟨i⟩) end, this $ mem_univ x) lemma infi_neq_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≤) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _, infi_neq_bot_of_directed hn hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin have hs' : s ∈ (Inf {a : filter α | ∃ (i : ι), a = f i}).sets := hs, rw [Inf_sets_eq_finite] at hs', simp only [mem_Union] at hs', rcases hs' with ⟨is, ⟨fin_is, his⟩, hs⟩, revert his s, refine finite.induction_on fin_is _ (λ fi is fi_ne_is fin_is ih, _); intros his s hs' hs, { rw [Inf_empty, mem_top_sets] at hs, simpa [hs] }, { rw [Inf_insert] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, rcases (his (mem_insert _ _) : ∃i, fi = f i) with ⟨i, rfl⟩, have hs₂ : p s₂, from have his : is ⊆ {x | ∃i, x = f i}, from assume i hi, his $ mem_insert_of_mem _ hi, have infi f ≤ Inf is, from Inf_le_Inf his, ih his (this hs₂) hs₂, exact upw hs (ins hs₁ hs₂) } end @[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := by simp [pure, has_pure.pure] /- tendsto -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂.sets, f ⁻¹' s ∈ l₁.sets := iff.rfl lemma tendsto_iff_vmap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.vmap f := map_le_iff_le_vmap lemma tendsto_cong {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : tendsto f₁ l₁ l₂) (hl : {x | f₁ x = f₂ x} ∈ l₁.sets) : tendsto f₂ l₁ l₂ := by rwa [tendsto, ←map_cong hl] lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp [tendsto] { contextual := tt } lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β} (h : y ≤ x) : tendsto f x z → tendsto f y z := le_trans (map_mono h) lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β} (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z := le_trans h₂ h₁ lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_vmap {f : α → β} {x : filter β} : tendsto f (vmap f x) x := map_vmap_le lemma tendsto_vmap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.vmap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, h.comp tendsto_vmap, assume h, map_le_iff_le_vmap.mp $ by rwa [map_map]⟩ lemma tendsto_vmap'' {m : α → β} {f : filter α} {g : filter β} (s : set α) {i : γ → α} (hs : s ∈ f.sets) (hi : ∀a∈s, ∃c, i c = a) (h : tendsto (m ∘ i) (vmap i f) g) : tendsto m f g := have tendsto m (map i $ vmap i $ f) g, by rwa [tendsto, ←map_compose] at h, le_trans (map_mono $ le_map_vmap' hs hi) this lemma vmap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} {ψ : β → α} (inv₁ : φ ∘ ψ = id) (inv₂ : ψ ∘ φ = id) (lim₁ : tendsto φ f g) (lim₂ : tendsto ψ g f) : vmap φ g = f := begin have ineq₁ := calc vmap φ g = map ψ g : eq.symm (map_eq_vmap_of_inverse inv₂ inv₁) ... ≤ f : lim₂, have ineq₂ : f ≤ vmap φ g := map_le_iff_le_vmap.1 lim₁, exact le_antisymm ineq₁ ineq₂ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp [tendsto] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp [tendsto] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) : tendsto f (x i) y → tendsto f (⨅i, x i) y := tendsto_le_left (infi_le _ _) lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} : tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a.sets := by simp [tendsto] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp [tendsto, image_subset_iff]; refl section lift /-- A variant on `bind` using a function `g` taking a set instead of a member of `α`. -/ protected def lift (f : filter α) (g : set α → filter β) := ⨅s ∈ f.sets, g s variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} lemma lift_sets_eq (hg : monotone g) : (f.lift g).sets = (⋃t∈f.sets, (g t).sets) := infi_sets_eq' (assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht, hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩) ⟨univ, univ_mem_sets⟩ lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f.sets) (hs : s ∈ (g t).sets) : s ∈ (f.lift g).sets := le_principal_iff.mp $ show f.lift g ≤ principal s, from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs lemma mem_lift_sets (hg : monotone g) {s : set β} : s ∈ (f.lift g).sets ↔ (∃t∈f.sets, s ∈ (g t).sets) := by rw [lift_sets_eq hg]; simp only [mem_Union] lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (hg : g s ≤ h) : f.lift g ≤ h := infi_le_of_le s $ infi_le_of_le hs $ hg lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β} (hh : ∀s∈f.sets, h ≤ g s) : h ≤ f.lift g := le_infi $ assume s, le_infi $ assume hs, hh s hs lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ := infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩ lemma lift_mono' (hg : ∀s∈f.sets, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) := have monotone (map m ∘ g), from monotone_comp hg monotone_map, filter_eq $ set.ext $ by simp [mem_lift_sets, hg, @mem_lift_sets _ _ f _ this] lemma vmap_lift_eq {m : γ → β} (hg : monotone g) : vmap m (f.lift g) = f.lift (vmap m ∘ g) := have monotone (vmap m ∘ g), from monotone_comp hg monotone_vmap, filter_eq $ set.ext begin simp only [hg, @mem_lift_sets _ _ f _ this, vmap, mem_lift_sets, mem_set_of_eq, exists_prop, function.comp_apply], exact λ s, ⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩, λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩ end theorem vmap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (vmap m f).lift g = f.lift (g ∘ preimage m) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩) (le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩, infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub) lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) : (map m f).lift g = f.lift (g ∘ image m) := le_antisymm (infi_le_infi2 $ assume s, ⟨image m s, infi_le_infi2 $ assume hs, ⟨ f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h, le_refl _⟩⟩) (infi_le_infi2 $ assume t, ⟨preimage m t, infi_le_infi2 $ assume ht, ⟨ht, hg $ assume x, assume h : x ∈ m '' preimage m t, let ⟨y, hy, h_eq⟩ := h in show x ∈ t, from h_eq ▸ hy⟩⟩) lemma lift_comm {g : filter β} {h : set α → set β → filter γ} : f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) lemma lift_assoc {h : set β → filter γ} (hg : monotone g) : (f.lift g).lift h = f.lift (λs, (g s).lift h) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩) (le_infi $ assume t, le_infi $ assume ht, let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h') lemma lift_lift_same_le_lift {g : set α → set α → filter β} : f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) := le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs lemma lift_lift_same_eq_lift {g : set α → set α → filter β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)): f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) := le_antisymm lift_lift_same_le_lift (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le (s ∩ t) $ infi_le_of_le (inter_mem_sets hs ht) $ calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _) ... ≤ g s t : hg₁ s (inter_subset_right _ _)) lemma lift_principal {s : set α} (hg : monotone g) : (principal s).lift g = g s := le_antisymm (infi_le_of_le s $ infi_le _ $ subset.refl _) (le_infi $ assume t, le_infi $ assume hi, hg hi) theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) := assume a b h, lift_mono (hf h) (hg h) lemma lift_neq_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) := classical.by_cases (assume hn : nonempty β, calc f.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f.sets}, g s.val) ≠ ⊥ : by simp [filter.lift, infi_subtype] ... ↔ (∀s:{ s // s ∈ f.sets}, g s.val ≠ ⊥) : infi_neq_bot_iff_of_directed hn (assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩, hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩) ... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩) (assume hn : ¬ nonempty β, have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn, have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn, calc (f.lift g ≠ ⊥) ↔ false : by simp [h₁] ... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩ ... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp [h₂]) @[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g := le_antisymm (lift_le univ_mem_sets $ le_refl g) (le_lift $ assume s hs, le_refl g) @[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} : f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h := by simp [filter.lift, infi_inf_eq] @[simp] lemma lift_principal2 {f : filter α} : f.lift principal = f := le_antisymm (assume s hs, mem_lift hs (mem_principal_self s)) (le_infi $ assume s, le_infi $ assume hs, by simp [hs]) lemma lift_infi {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, have g_mono : monotone g, from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h, have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t, from assume t ht, infi_sets_induct ht (let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets) (assume i s₁ s₂ hs₁ hs₂, @hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂) (assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁), begin rw [lift_sets_eq g_mono], simp only [mem_Union, exists_imp_distrib], exact assume t ht hs, this t ht hs end) end lift section lift' /-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `vmap`. -/ protected def lift' (f : filter α) (h : set α → set β) := f.lift (principal ∘ h) variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β} lemma mem_lift' {t : set α} (ht : t ∈ f.sets) : h t ∈ (f.lift' h).sets := le_principal_iff.mp $ show f.lift' h ≤ principal (h t), from infi_le_of_le t $ infi_le_of_le ht $ le_refl _ lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h).sets ↔ (∃t∈f.sets, h t ⊆ s) := have monotone (principal ∘ h), from assume a b h, principal_mono.mpr $ hh h, by simp [filter.lift', @mem_lift_sets α β f _ this] lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (hg : principal (g s) ≤ h) : f.lift' g ≤ h := lift_le hs hg lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ := lift_mono hf $ assume s, principal_mono.mpr $ hh s lemma lift'_mono' (hh : ∀s∈f.sets, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs lemma lift'_cong (hh : ∀s∈f.sets, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ := le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm) lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) := calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) : map_lift_eq $ monotone_comp hh monotone_principal ... = f.lift' (image m ∘ h) : by simp [function.comp, filter.lift'] lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) : (map m f).lift' g = f.lift' (g ∘ image m) := map_lift_eq2 $ monotone_comp hg monotone_principal theorem vmap_lift'_eq {m : γ → β} (hh : monotone h) : vmap m (f.lift' h) = f.lift' (preimage m ∘ h) := calc vmap m (f.lift' h) = f.lift (vmap m ∘ principal ∘ h) : vmap_lift_eq $ monotone_comp hh monotone_principal ... = f.lift' (preimage m ∘ h) : by simp [function.comp, filter.lift'] theorem vmap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (vmap m f).lift' g = f.lift' (g ∘ preimage m) := vmap_lift_eq2 $ monotone_comp hg monotone_principal lemma lift'_principal {s : set α} (hh : monotone h) : (principal s).lift' h = principal (h s) := lift_principal $ monotone_comp hh monotone_principal lemma principal_le_lift' {t : set β} (hh : ∀s∈f.sets, t ⊆ h s) : principal t ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs) theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) := assume a b h, lift'_mono (hf h) (hg h) lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift h = f.lift (λs, h (g s)) := calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) : lift_assoc (monotone_comp hg monotone_principal) ... = f.lift (λs, h (g s)) : by simp [lift_principal, hh] lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift' h = f.lift' (λs, h (g s)) := lift_lift'_assoc hg (monotone_comp hh monotone_principal) lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ} (hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) := lift_assoc hg lemma lift_lift'_same_le_lift' {g : set α → set α → set β} : f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) := lift_lift_same_le_lift lemma lift_lift'_same_eq_lift' {g : set α → set α → set β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)): f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) := lift_lift_same_eq_lift (assume s, monotone_comp monotone_id $ monotone_comp (hg₁ s) monotone_principal) (assume t, monotone_comp (hg₂ t) monotone_principal) lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} : f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) := le_antisymm (le_infi $ assume t, le_infi $ assume ht, calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s : inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _) ... = _ : by simp) (le_inf (le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le_of_le ht $ by simp; exact inter_subset_right _ _) (infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp; exact inter_subset_left _ _)) lemma lift'_neq_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) := calc (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) : lift_neq_bot_iff (monotone_comp hh monotone_principal) ... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp [principal_eq_bot_iff] @[simp] lemma lift'_id {f : filter α} : f.lift' id = f := lift_principal2 lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β} (h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, by simp [h_le]; exact h_le s hs lemma lift_infi' {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hf : directed (≤) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, begin rw [lift_sets_eq hg], simp only [mem_Union, exists_imp_distrib, infi_sets_eq hf hι], exact assume t i ht hs, mem_infi_sets i $ mem_lift ht hs end) lemma lift'_infi {f : ι → filter α} {g : set α → set β} (hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) := lift_infi hι $ by simp; apply assume s t, hg theorem vmap_eq_lift' {f : filter β} {m : α → β} : vmap m f = f.lift' (preimage m) := filter_eq $ set.ext $ by simp [mem_lift'_sets, monotone_preimage, vmap] end lift' section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x <- seq, y <- top, return (x, y)} hence: s ∈ F <-> ∃n, [n..∞] × univ ⊆ s G := do {y <- top, x <- seq, return (x, y)} hence: s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.vmap prod.fst ⊓ g.vmap prod.snd lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets := inter_mem_inf_sets (preimage_mem_vmap hs) (preimage_mem_vmap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) := begin simp [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f := tendsto_inf_left tendsto_vmap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g := tendsto_inf_right tendsto_vmap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) := tendsto_inf.2 ⟨tendsto_vmap_iff.2 h₁, tendsto_vmap_iff.2 h₂⟩ lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) : filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) := by rw [filter.prod, vmap_infi, infi_inf i]; simp [filter.prod] lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) : filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) := by rw [filter.prod, vmap_infi, inf_infi i]; simp [filter.prod] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ := inf_le_inf (vmap_mono hf) (vmap_mono hg) lemma prod_vmap_vmap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : filter.prod (vmap m₁ f₁) (vmap m₂ f₂) = vmap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := by simp [filter.prod, vmap_vmap_comp] lemma prod_comm' : filter.prod f g = vmap (prod.swap) (filter.prod g f) := by simp [filter.prod, vmap_vmap_comp, function.comp, inf_comm] lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) := by rw [prod_comm', ← map_swap_eq_vmap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _))) lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) := by simp only [filter.prod, vmap_inf, inf_comm, inf_assoc, lattice.inf_left_comm] @[simp] lemma prod_bot1 {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma prod_bot2 {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : filter.prod (principal s) (principal t) = principal (set.prod s t) := by simp [filter.prod, vmap_principal]; refl lemma prod_def {f : filter α} {g : filter β} : f.prod g = (f.lift $ λs, g.lift' $ set.prod s) := have ∀(s:set α) (t : set β), principal (set.prod s t) = (principal s).vmap prod.fst ⊓ (principal t).vmap prod.snd, by simp; intros; refl, begin simp [filter.lift', function.comp, this, -vmap_principal, lift_inf], rw [← vmap_lift_eq monotone_principal, ← vmap_lift_eq monotone_principal], simp [filter.prod] end lemma prod_same_eq : filter.prod f f = f.lift' (λt, set.prod t t) := by rw [prod_def]; from lift_lift'_same_eq_lift' (assume s, set.monotone_prod monotone_const monotone_id) (assume t, set.monotone_prod monotone_id monotone_const) lemma mem_prod_same_iff {s : set (α×α)} : s ∈ (filter.prod f f).sets ↔ (∃t∈f.sets, set.prod t t ⊆ s) := by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id lemma prod_lift_lift {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) := begin simp only [prod_def], rw [lift_assoc], apply congr_arg, funext x, rw [lift_comm], apply congr_arg, funext y, rw [lift'_lift_assoc], exact hg₂, exact hg₁ end lemma prod_lift'_lift' {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) := begin rw [prod_def, lift_lift'_assoc], apply congr_arg, funext x, rw [lift'_lift'_assoc], exact hg₂, exact set.monotone_prod monotone_const monotone_id, exact hg₁, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, set.monotone_prod monotone_id monotone_const) end lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := calc filter.prod f g ≠ ⊥ ↔ (∀s∈f.sets, g.lift' (set.prod s) ≠ ⊥) : begin rw [prod_def, lift_neq_bot_iff], exact (monotone_lift' monotone_const $ monotone_lam $ assume s, set.monotone_prod monotone_id monotone_const) end ... ↔ (∀s∈f.sets, ∀t∈g.sets, s ≠ ∅ ∧ t ≠ ∅) : begin apply forall_congr, intro s, apply forall_congr, intro hs, rw [lift'_neq_bot_iff], apply forall_congr, intro t, apply forall_congr, intro ht, rw [set.prod_neq_empty_iff], exact set.monotone_prod monotone_const monotone_id end ... ↔ (∀s∈f.sets, s ≠ ∅) ∧ (∀t∈g.sets, t ≠ ∅) : ⟨assume h, ⟨assume s hs, (h s hs univ univ_mem_sets).left, assume t ht, (h univ univ_mem_sets t ht).right⟩, assume ⟨h₁, h₂⟩ s hs t ht, ⟨h₁ s hs, h₂ t ht⟩⟩ ... ↔ _ : by simp only [forall_sets_neq_empty_iff_neq_bot] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (filter.prod x y) z ↔ ∀ W ∈ z.sets, ∃ U ∈ x.sets, ∃ V ∈ y.sets, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp [tendsto_def, mem_prod_iff, set.prod_sub_preimage_iff] lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} : filter.tendsto f (filter.prod x x) y ↔ ∀ W ∈ y.sets, ∃ U ∈ x.sets, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W := by simp [tendsto_def, mem_prod_same_iff, set.prod_sub_preimage_iff] end prod /- at_top and at_bot -/ /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ (@at_top α _).sets := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [inhabited α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ := infi_neq_bot_of_directed (by apply_instance) (assume a b, ⟨a ⊔ b, by simp {contextual := tt}⟩) (assume a, by simp [principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a)) @[simp] lemma mem_at_top_sets [inhabited α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α).sets ↔ ∃a:α, ∀b≥a, b ∈ s := iff.intro (assume h, infi_sets_induct h ⟨default α, by simp⟩ (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b, assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩) (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩)) (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x) lemma map_at_top_eq [inhabited α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) := calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) : map_infi_eq (assume a b, ⟨a ⊔ b, by simp {contextual := tt}⟩) ⟨default α⟩ ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (λs:finset γ, s.image j) at_top at_top := tendsto_infi.2 $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal.2 $ assume t (ht : s.image i ⊆ t), calc s = (s.image i).image j : by simp [finset.image_image, (∘), h]; exact finset.image_id.symm ... ⊆ t.image j : finset.image_subset_image ht /- ultrafilter -/ section ultrafilter open zorn variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_pure {a : α} : ultrafilter (pure a) := ⟨pure_neq_bot, assume g hg ha, have {a} ∈ g.sets, begin simp at ha, assumption end, show ∀s∈g.sets, {a} ⊆ s, from classical.by_contradiction $ begin simp only [classical.not_forall, not_imp, exists_imp_distrib, singleton_subset_iff], exact assume s ⟨hs, hna⟩, have {a} ∩ s ∈ g.sets, from inter_mem_sets ‹{a} ∈ g.sets› hs, have ∅ ∈ g.sets, from mem_sets_of_superset this $ assume x ⟨hxa, hxs⟩, begin simp at hxa; simp [hxa] at hxs, exact hna hxs end, have g = ⊥, from empty_in_sets_eq_bot.mp this, hg this end⟩ lemma ultrafilter_unique (hg : ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_neq_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ lemma le_of_ultrafilter {g : filter α} (hf : ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left lemma mem_or_compl_mem_of_ultrafilter (hf : ultrafilter f) (s : set α) : s ∈ f.sets ∨ - s ∈ f.sets := classical.or_iff_not_imp_right.2 $ assume : - s ∉ f.sets, have f ≤ principal s, from le_of_ultrafilter hf $ assume h, this $ mem_sets_of_neq_bot $ by simp [*], by simp at this; assumption lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : ultrafilter f) (h : s ∪ t ∈ f.sets) : s ∈ f.sets ∨ t ∈ f.sets := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : -s ∈ f.sets, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets := finite.induction_on hs (by simp [empty_in_sets_eq_bot, hf.left]) $ λ t s' ht' hs' ih, by simp; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f.sets, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets := have his : finite (image s is), from finite_image s his, have h : (⋃₀ image s is) ∈ f.sets, from by simp [sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_of_split {f : filter α} (hf : f ≠ ⊥) (h : ∀s, s ∈ f.sets ∨ - s ∈ f.sets) : ultrafilter f := ⟨hf, assume g hg g_le s hs, (h s).elim id $ assume : - s ∈ f.sets, have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this), by simp [empty_in_sets_eq_bot, hg] at this; contradiction⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : ultrafilter f) : ultrafilter (map m f) := ultrafilter_of_split (by simp [map_eq_bot_iff, h.left]) $ assume s, show preimage m s ∈ f.sets ∨ - preimage m s ∈ f.sets, from mem_or_compl_mem_of_ultrafilter h (preimage m s) /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ ultrafilter (ultrafilter_of f) := begin have h' := classical.epsilon_spec (exists_ultrafilter h), simp [ultrafilter_of, dif_neg, h], simp at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp [ultrafilter_of, dif_pos, h]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le end ultrafilter end filter
a6b0c44d75a0eef268e540e88c4d01f53c6d7d1d
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_topology/dold_kan/notations.lean
e7194e9cf2bd89407c055b5b9e759749e0a47901
[ "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
702
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.alternating_face_map_complex /-! # Notations for the Dold-Kan equivalence This file defines the notation `K[X] : chain_complex C ℕ` for the alternating face map complex of `(X : simplicial_object C)` where `C` is a preadditive category, as well as `N[X]` for the normalized subcomplex in the case `C` is an abelian category. -/ localized "notation `K[`X`]` := algebraic_topology.alternating_face_map_complex.obj X" in dold_kan localized "notation `N[`X`]` := algebraic_topology.normalized_Moore_complex.obj X" in dold_kan
ef36d344d7688b9f255b799aa1266319925f8520
7cdf3413c097e5d36492d12cdd07030eb991d394
/world_experiments/world9/level4.lean
163665c7ff3e8675023ab5b1b831246792a41bb6
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
797
lean
import game.world5.level3 -- hide namespace mynat -- hide /- # World 5 : Inequality world ## Level 4 : `le_trans` -/ /- Lemma ≤ is transitive. In other words, if $a\leq b$ and $b\leq c$ then $a\leq c$. -/ theorem le_trans {{a b c : mynat}} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := begin [less_leaky] cases hab with d hd, cases hbc with e he, use (d + e), rw ←add_assoc, rw ←hd, assumption, end /- Congratulations -- you just proved that the natural numbers are a preorder. -/ instance : preorder mynat := by structure_helper -- hide end mynat -- hide /- I think that to go further, I (Kevin) have to teach you that implication is a function, and Mohammad has to make the worlds in this game depend on each other in a non-linear manner. This is all to come in V1.1. -/
07f8ea654aaa047ceed4e00157e03d8458d9c5c7
ca37452420f42eb9a19643a034c532fb39187bd0
/lemmas_from_ramsey.lean
a1c1be4369221216cdb16ae066db60fe47c19f99
[]
no_license
minchaowu/Kruskal.lean
0096fd12c6732dcb55214907e7241df27d22a51e
0ec4a724c18d8fa2bc1e81dfc026a045888526d5
refs/heads/master
1,589,975,750,330
1,481,928,508,000
1,481,928,508,000
70,121,484
0
0
null
null
null
null
UTF-8
Lean
false
false
3,364
lean
import data.nat data.set open classical nat function set section -- the least number principle. lemma alt_of_wf {A : set ℕ}: ∀ n, n ∈ A → ∃₀ a ∈ A, ∀₀ b ∈ A, a ≤ b := take n, nat.strong_induction_on n (take n, assume IH, assume ninA, by_cases (suppose ∃₀ m ∈ A, m < n, obtain m (Hm : m ∈ A ∧ m < n), from this, IH m (and.right Hm) (and.left Hm)) (suppose ¬ ∃₀ m ∈ A, m < n, have ∀₀ m ∈ A, ¬ m < n, by+ rewrite not_bounded_exists at this ; exact this, have ∀ m, m ∈ A → n ≤ m, from λ m, λ HmA, le_of_not_gt (this HmA), exists.intro n (and.intro ninA this))) theorem wf_of_le (S : set ℕ) (H : S ≠ ∅) : ∃₀ a ∈ S, ∀₀ b ∈ S, a ≤ b := have ∃ x, x ∈ S, from exists_mem_of_ne_empty H, obtain n (Hn : n ∈ S), from this, alt_of_wf n Hn noncomputable definition chooseleast (S : set ℕ) (H : S ≠ ∅) : ℕ := have ∃₀ a ∈ S, ∀₀ b ∈ S, a ≤ b, from wf_of_le S H, some this theorem least_is_mem (S : set ℕ) (H : S ≠ ∅) : chooseleast S H ∈ S := have H1 : ∃₀ a ∈ S, ∀₀ b ∈ S, a ≤ b, from wf_of_le S H, have inS : some H1 ∈ S, from proof and.left (some_spec H1) qed, have chooseleast S H = some H1, from rfl, by+ rewrite -this at inS ; exact inS theorem minimality {S : set ℕ} {a : ℕ} {H0 : S ≠ ∅} (H : a = chooseleast S H0): ∀₀ x ∈ S, a ≤ x := take b, assume Hb, have H1 : ∃₀ n ∈ S, ∀₀ m ∈ S, n ≤ m, from wf_of_le S H0, have chooseleast S H0 = some H1, from rfl, have eq : a = some H1, by+ rewrite this at H;exact H, have ∀₀ m ∈ S, some H1 ≤ m, from proof and.right (some_spec H1) qed, have some H1 ≤ b, from this Hb, by+ simp end lemma nonzero_card_of_finite {A : Type} {S : set A} (H : card S ≠ 0) : finite S := by_contradiction (suppose ¬ finite S, have card S = 0, from card_of_not_finite this, H this) lemma mem_not_in_diff {A : Type} {S : set A} {a : A} : a ∉ S \ '{a} := suppose a ∈ S \ '{a}, have a ∉ '{a}, from not_mem_of_mem_diff this, this (mem_singleton a) lemma insert_of_diff_singleton {A : Type} {S : set A} {a : A} (H : a ∈ S) : insert a (S \ '{a}) = S := begin apply eq_of_subset_of_subset, intros x h, apply or.elim h, intro, simp, intro hr, apply and.left hr, intro x h', cases (decidable.em (x ∈ '{a})), apply or.inl, apply eq_of_mem_singleton, simp, apply or.inr, apply and.intro, repeat simp end lemma union_of_diff_singleton {A : Type} {S : set A} {a : A} (H : a ∈ S) : S \ '{a} ∪ '{a} = S := begin apply eq_of_subset_of_subset, intros x h, apply or.elim h, intro hl, apply and.left hl, intro hr, have x = a, from (and.left (mem_singleton_iff x a)) hr, rewrite this, simp, intros x h', cases (decidable.em (x ∈ '{a})), apply or.inr, simp, apply or.inl, apply and.intro, repeat simp end lemma finite_singleton {A : Type} {a : A} : finite '{a} := have carda : card '{a} = 1, from card_singleton a, have (1:ℕ) ≠ 0, from dec_trivial, have card '{a} ≠ 0, by+ rewrite -carda at this;exact this, nonzero_card_of_finite this lemma sub_of_eq {A : Type} {S T: set A} (H : S = T) : S ⊆ T := have T ⊆ T, from subset.refl T, by+ rewrite -H at this{1};exact this theorem ne_empty_of_mem' {X : Type} {s : set X} {x : X} (H : x ∈ s) : s ≠ ∅ := begin intro Hs, rewrite Hs at H, apply not_mem_empty _ H end --this is on github
6a9ea918c8dda635fcc50c1f0717c38a5b14a9f9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/analytic/composition.lean
520255f56928feaf25bb748cac3de386a2b44520
[]
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
39,534
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.analytic.basic import Mathlib.combinatorics.composition import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u_5 namespace Mathlib /-! # Composition of analytic functions in this file we prove that the composition of analytic functions is analytic. The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then `g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y)) = ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`. For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping `(y₀, ..., y_{i₁ + ... + iₙ - 1})` to `qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`. Then `g ∘ f` is obtained by summing all these multilinear functions. To formalize this, we use compositions of an integer `N`, i.e., its decompositions into a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these terms over all `c : composition N`. To complete the proof, we need to show that this power series has a positive radius of convergence. This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to `g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it corresponds to a part of the whole sum, on a subset that increases to the whole space. By summability of the norms, this implies the overall convergence. ## Main results * `q.comp p` is the formal composition of the formal multilinear series `q` and `p`. * `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions `q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`. * `analytic_at.comp` states that the composition of analytic functions is analytic. * `formal_multilinear_series.comp_assoc` states that composition is associative on formal multilinear series. ## Implementation details The main technical difficulty is to write down things. In particular, we need to define precisely `q.comp_along_composition p c` and to show that it is indeed a continuous multilinear function. This requires a whole interface built on the class `composition`. Once this is set, the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection, running over difficulties due to the dependent nature of the types under consideration, that are controlled thanks to the interface for `composition`. The associativity of composition on formal multilinear series is a nontrivial result: it does not follow from the associativity of composition of analytic functions, as there is no uniqueness for the formal multilinear series representing a function (and also, it holds even when the radius of convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering double sums in a careful way. The change of variables is a canonical (combinatorial) bijection `composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described in more details below in the paragraph on associativity. -/ /-! ### Composing formal multilinear series -/ namespace formal_multilinear_series /-! In this paragraph, we define the composition of formal multilinear series, by summing over all possible compositions of `n`. -/ /-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/ def apply_composition {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : (fin n → E) → fin (composition.length c) → F := fun (v : fin n → E) (i : fin (composition.length c)) => coe_fn (p (composition.blocks_fun c i)) (v ∘ ⇑(composition.embedding c i)) theorem apply_composition_ones {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : apply_composition p (composition.ones n) = fun (v : fin n → E) (i : fin (composition.length (composition.ones n))) => coe_fn (p 1) fun (_x : fin 1) => v (coe_fn (fin.cast_le (composition.length_le (composition.ones n))) i) := sorry theorem apply_composition_single {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) (v : fin n → E) : apply_composition p (composition.single n hn) v = fun (j : fin (composition.length (composition.single n hn))) => coe_fn (p n) v := sorry @[simp] theorem remove_zero_apply_composition {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : apply_composition (remove_zero p) c = apply_composition p c := sorry /-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This will be the key point to show that functions constructed from `apply_composition` retain multilinearity. -/ theorem apply_composition_update {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) (j : fin n) (v : fin n → E) (z : E) : apply_composition p c (function.update v j z) = function.update (apply_composition p c v) (composition.index c j) (coe_fn (p (composition.blocks_fun c (composition.index c j))) (function.update (v ∘ ⇑(composition.embedding c (composition.index c j))) (composition.inv_embedding c j) z)) := sorry @[simp] theorem comp_continuous_linear_map_apply_composition {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (p : formal_multilinear_series 𝕜 F G) (f : continuous_linear_map 𝕜 E F) (c : composition n) (v : fin n → E) : apply_composition (comp_continuous_linear_map p f) c v = apply_composition p c (⇑f ∘ v) := sorry end formal_multilinear_series namespace continuous_multilinear_map /-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear map `f` in `c.length` variables, one may form a multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `f` to the resulting vector. It is called `f.comp_along_composition_aux p c`. This function admits a version as a continuous multilinear map, called `f.comp_along_composition p c` below. -/ def comp_along_composition_aux {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (fun (i : fin (composition.length c)) => F) G) : multilinear_map 𝕜 (fun (i : fin n) => E) G := multilinear_map.mk (fun (v : fin n → E) => coe_fn f (formal_multilinear_series.apply_composition p c v)) sorry sorry /-- The norm of `f.comp_along_composition_aux p c` is controlled by the product of the norms of the relevant bits of `f` and `p`. -/ theorem comp_along_composition_aux_bound {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (fun (i : fin (composition.length c)) => F) G) (v : fin n → E) : norm (coe_fn (comp_along_composition_aux p c f) v) ≤ (norm f * finset.prod finset.univ fun (i : fin (composition.length c)) => norm (p (composition.blocks_fun c i))) * finset.prod finset.univ fun (i : fin n) => norm (v i) := sorry /-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear map `f` in `c.length` variables, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `f` to the resulting vector. It is called `f.comp_along_composition p c`. It is constructed from the analogous multilinear function `f.comp_along_composition_aux p c`, together with a norm control to get the continuity. -/ def comp_along_composition {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (fun (i : fin (composition.length c)) => F) G) : continuous_multilinear_map 𝕜 (fun (i : fin n) => E) G := multilinear_map.mk_continuous (comp_along_composition_aux p c f) (norm f * finset.prod finset.univ fun (i : fin (composition.length c)) => norm (p (composition.blocks_fun c i))) (comp_along_composition_aux_bound p c f) @[simp] theorem comp_along_composition_apply {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (fun (i : fin (composition.length c)) => F) G) (v : fin n → E) : coe_fn (comp_along_composition p c f) v = coe_fn f (formal_multilinear_series.apply_composition p c v) := rfl end continuous_multilinear_map namespace formal_multilinear_series /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition p c`. It is constructed from the analogous multilinear function `q.comp_along_composition_aux p c`, together with a norm control to get the continuity. -/ def comp_along_composition {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : continuous_multilinear_map 𝕜 (fun (i : fin n) => E) G := continuous_multilinear_map.comp_along_composition p c (q (composition.length c)) @[simp] theorem comp_along_composition_apply {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : coe_fn (comp_along_composition q p c) v = coe_fn (q (composition.length c)) (apply_composition p c v) := rfl /-- The norm of `q.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ theorem comp_along_composition_norm {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : norm (comp_along_composition q p c) ≤ norm (q (composition.length c)) * finset.prod finset.univ fun (i : fin (composition.length c)) => norm (p (composition.blocks_fun c i)) := sorry theorem comp_along_composition_nnnorm {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : nnnorm (comp_along_composition q p c) ≤ nnnorm (q (composition.length c)) * finset.prod finset.univ fun (i : fin (composition.length c)) => nnnorm (p (composition.blocks_fun c i)) := sorry /-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.comp_along_composition p c` over all compositions of `n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is `∑'_{k} ∑'_{i₁ + ... + iₖ = n} pₖ (q_{i_1} (...), ..., q_{i_k} (...))`, where one puts all variables `v_0, ..., v_{n-1}` in increasing order in the dots.-/ protected def comp {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := fun (n : ℕ) => finset.sum finset.univ fun (c : composition n) => comp_along_composition q p c /-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero variables, but on different spaces, we can not state this directly, so we state it when applied to arbitrary vectors (which have to be the zero vector). -/ theorem comp_coeff_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) (v' : fin 0 → F) : coe_fn (formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p 0) v = coe_fn (q 0) v' := sorry @[simp] theorem comp_coeff_zero' {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) : coe_fn (formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p 0) v = coe_fn (q 0) fun (i : fin 0) => 0 := comp_coeff_zero 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p v fun (i : fin 0) => 0 /-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be expressed as a direct equality -/ theorem comp_coeff_zero'' {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (q : formal_multilinear_series 𝕜 E F) (p : formal_multilinear_series 𝕜 E E) : formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 E _inst_2 _inst_3 F _inst_4 _inst_5 q p 0 = q 0 := continuous_multilinear_map.ext fun (v : fin 0 → E) => comp_coeff_zero 𝕜 _inst_1 E _inst_2 _inst_3 E _inst_2 _inst_3 F _inst_4 _inst_5 q p v v /-- The first coefficient of a composition of formal multilinear series is the composition of the first coefficients seen as continuous linear maps. -/ theorem comp_coeff_one {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 1 → E) : coe_fn (formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p 1) v = coe_fn (q 1) fun (i : fin 1) => coe_fn (p 1) v := sorry theorem remove_zero_comp_of_pos {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) : formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 (remove_zero q) p n = formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p n := sorry @[simp] theorem comp_remove_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q (remove_zero p) = formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p := sorry /-! ### The identity formal power series We will now define the identity power series, and show that it is a neutral element for left and right composition. -/ /-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1` where it is (the continuous multilinear version of) the identity. -/ def id (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] : formal_multilinear_series 𝕜 E E := sorry /-- The first coefficient of `id 𝕜 E` is the identity. -/ @[simp] theorem id_apply_one (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] (v : fin 1 → E) : coe_fn (id 𝕜 E 1) v = v 0 := rfl /-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent way, as it will often appear in this form. -/ theorem id_apply_one' (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] {n : ℕ} (h : n = 1) (v : fin n → E) : coe_fn (id 𝕜 E n) v = v { val := 0, property := Eq.symm h ▸ zero_lt_one } := eq.drec (fun (v : fin 1 → E) => id_apply_one 𝕜 E v) (Eq.symm h) v /-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/ @[simp] theorem id_apply_ne_one (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] {n : ℕ} (h : n ≠ 1) : id 𝕜 E n = 0 := sorry @[simp] theorem comp_id {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 E _inst_2 _inst_3 F _inst_4 _inst_5 p (id 𝕜 E) = p := sorry @[simp] theorem id_comp {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 F _inst_4 _inst_5 (id 𝕜 F) p = p := sorry /-! ### Summability properties of the composition of formal power series-/ /-- If two formal multilinear series have positive radius of convergence, then the terms appearing in the definition of their composition are also summable (when multiplied by a suitable positive geometric term). -/ theorem comp_summable_nnreal {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (hq : 0 < radius q) (hp : 0 < radius p) : ∃ (r : nnreal), ∃ (H : r > 0), summable fun (i : sigma fun (n : ℕ) => composition n) => nnnorm (comp_along_composition q p (sigma.snd i)) * r ^ sigma.fst i := sorry /-- Bounding below the radius of the composition of two formal multilinear series assuming summability over all compositions. -/ theorem le_comp_radius_of_summable {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : nnreal) (hr : summable fun (i : sigma fun (n : ℕ) => composition n) => nnnorm (comp_along_composition q p (sigma.snd i)) * r ^ sigma.fst i) : ↑r ≤ radius (formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p) := sorry /-! ### Composing analytic functions Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for `g` and `p` is a power series for `f`. This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first the source of the change of variables (`comp_partial_source`), its target (`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before giving the main statement in `comp_partial_sum`. -/ /-- Source set in the change of variables to compute the composition of partial sums of formal power series. See also `comp_partial_sum`. -/ def comp_partial_sum_source (m : ℕ) (M : ℕ) (N : ℕ) : finset (sigma fun (n : ℕ) => fin n → ℕ) := finset.sigma (finset.Ico m M) fun (n : ℕ) => fintype.pi_finset fun (i : fin n) => finset.Ico 1 N @[simp] theorem mem_comp_partial_sum_source_iff (m : ℕ) (M : ℕ) (N : ℕ) (i : sigma fun (n : ℕ) => fin n → ℕ) : i ∈ comp_partial_sum_source m M N ↔ (m ≤ sigma.fst i ∧ sigma.fst i < M) ∧ ∀ (a : fin (sigma.fst i)), 1 ≤ sigma.snd i a ∧ sigma.snd i a < N := sorry /-- Change of variables appearing to compute the composition of partial sums of formal power series -/ def comp_change_of_variables (m : ℕ) (M : ℕ) (N : ℕ) (i : sigma fun (n : ℕ) => fin n → ℕ) (hi : i ∈ comp_partial_sum_source m M N) : sigma fun (n : ℕ) => composition n := sigma.cases_on i (fun (n : ℕ) (f : fin n → ℕ) (hi : sigma.mk n f ∈ comp_partial_sum_source m M N) => sigma.mk (finset.sum finset.univ fun (j : fin n) => f j) (composition.mk (list.of_fn fun (j : fin n) => f j) sorry sorry)) hi @[simp] theorem comp_change_of_variables_length (m : ℕ) (M : ℕ) (N : ℕ) {i : sigma fun (n : ℕ) => fin n → ℕ} (hi : i ∈ comp_partial_sum_source m M N) : composition.length (sigma.snd (comp_change_of_variables m M N i hi)) = sigma.fst i := sorry theorem comp_change_of_variables_blocks_fun (m : ℕ) (M : ℕ) (N : ℕ) {i : sigma fun (n : ℕ) => fin n → ℕ} (hi : i ∈ comp_partial_sum_source m M N) (j : fin (sigma.fst i)) : composition.blocks_fun (sigma.snd (comp_change_of_variables m M N i hi)) { val := ↑j, property := Eq.symm (comp_change_of_variables_length m M N hi) ▸ subtype.property j } = sigma.snd i j := sorry /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a set. -/ def comp_partial_sum_target_set (m : ℕ) (M : ℕ) (N : ℕ) : set (sigma fun (n : ℕ) => composition n) := set_of fun (i : sigma fun (n : ℕ) => composition n) => m ≤ composition.length (sigma.snd i) ∧ composition.length (sigma.snd i) < M ∧ ∀ (j : fin (composition.length (sigma.snd i))), composition.blocks_fun (sigma.snd i) j < N theorem comp_partial_sum_target_subset_image_comp_partial_sum_source (m : ℕ) (M : ℕ) (N : ℕ) (i : sigma fun (n : ℕ) => composition n) (hi : i ∈ comp_partial_sum_target_set m M N) : ∃ (j : sigma fun (n : ℕ) => fin n → ℕ), ∃ (hj : j ∈ comp_partial_sum_source m M N), i = comp_change_of_variables m M N j hj := sorry /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a finset. See also `comp_partial_sum`. -/ def comp_partial_sum_target (m : ℕ) (M : ℕ) (N : ℕ) : finset (sigma fun (n : ℕ) => composition n) := set.finite.to_finset sorry @[simp] theorem mem_comp_partial_sum_target_iff {m : ℕ} {M : ℕ} {N : ℕ} {a : sigma fun (n : ℕ) => composition n} : a ∈ comp_partial_sum_target m M N ↔ m ≤ composition.length (sigma.snd a) ∧ composition.length (sigma.snd a) < M ∧ ∀ (j : fin (composition.length (sigma.snd a))), composition.blocks_fun (sigma.snd a) j < N := sorry /-- `comp_change_of_variables m M N` is a bijection between `comp_partial_sum_source m M N` and `comp_partial_sum_target m M N`, yielding equal sums for functions that correspond to each other under the bijection. As `comp_change_of_variables m M N` is a dependent function, stating that it is a bijection is not directly possible, but the consequence on sums can be stated more easily. -/ theorem comp_change_of_variables_sum {α : Type u_1} [add_comm_monoid α] (m : ℕ) (M : ℕ) (N : ℕ) (f : (sigma fun (n : ℕ) => fin n → ℕ) → α) (g : (sigma fun (n : ℕ) => composition n) → α) (h : ∀ (e : sigma fun (n : ℕ) => fin n → ℕ) (he : e ∈ comp_partial_sum_source m M N), f e = g (comp_change_of_variables m M N e he)) : (finset.sum (comp_partial_sum_source m M N) fun (e : sigma fun (n : ℕ) => fin n → ℕ) => f e) = finset.sum (comp_partial_sum_target m M N) fun (e : sigma fun (n : ℕ) => composition n) => g e := sorry /-- The auxiliary set corresponding to the composition of partial sums asymptotically contains all possible compositions. -/ theorem comp_partial_sum_target_tendsto_at_top : filter.tendsto (fun (N : ℕ) => comp_partial_sum_target 0 N N) filter.at_top filter.at_top := sorry /-- Composing the partial sums of two multilinear series coincides with the sum over all compositions in `comp_partial_sum_target 0 N N`. This is precisely the motivation for the definition of `comp_partial_sum_target`. -/ theorem comp_partial_sum {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) : partial_sum q N (finset.sum (finset.Ico 1 N) fun (i : ℕ) => coe_fn (p i) fun (j : fin i) => z) = finset.sum (comp_partial_sum_target 0 N N) fun (i : sigma fun (n : ℕ) => composition n) => coe_fn (comp_along_composition q p (sigma.snd i)) fun (j : fin (sigma.fst i)) => z := sorry end formal_multilinear_series /-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then `g ∘ f` admits the power series `q.comp p` at `x`. -/ theorem has_fpower_series_at.comp {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {g : F → G} {f : E → F} {q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E} (hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) : has_fpower_series_at (g ∘ f) (formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p) x := sorry /-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is analytic at `x`. -/ theorem analytic_at.comp {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {g : F → G} {f : E → F} {x : E} (hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x := sorry /-! ### Associativity of the composition of formal multilinear series In this paragraph, we us prove the associativity of the composition of formal power series. By definition, ``` (r.comp q).comp p n v = ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...)) = ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v) ``` decomposing `r.comp q` in the same way, we get ``` (r.comp q).comp p n v = ∑_{a : composition n} ∑_{b : composition a.length} r b.length (apply_composition q b (apply_composition p a v)) ``` On the other hand, ``` r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v) ``` Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the `i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term, we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`, where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get ``` r.comp (q.comp p) n v = ∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0), ..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))} r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ)) ``` To show that these terms coincide, we need to explain how to reindex the sums to put them in bijection (and then the terms we are summing will correspond to each other). Suppose we have a composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of length 5 of 13. The content of the blocks may be represented as `0011222333344`. Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a` should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13` made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`. This equivalence is called `composition.sigma_equiv_sigma_pi n` below. We start with preliminary results on compositions, of a very specialized nature, then define the equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of composition of formal multilinear series in `formal_multilinear_series.comp_assoc`. -/ namespace composition /-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in non-dependent terms with lists, requiring that the blocks coincide. -/ theorem sigma_composition_eq_iff {n : ℕ} (i : sigma fun (a : composition n) => composition (length a)) (j : sigma fun (a : composition n) => composition (length a)) : i = j ↔ blocks (sigma.fst i) = blocks (sigma.fst j) ∧ blocks (sigma.snd i) = blocks (sigma.snd j) := sorry /-- Rewriting equality in the dependent type `Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in non-dependent terms with lists, requiring that the lists of blocks coincide. -/ theorem sigma_pi_composition_eq_iff {n : ℕ} (u : sigma fun (c : composition n) => (i : fin (length c)) → composition (blocks_fun c i)) (v : sigma fun (c : composition n) => (i : fin (length c)) → composition (blocks_fun c i)) : u = v ↔ (list.of_fn fun (i : fin (length (sigma.fst u))) => blocks (sigma.snd u i)) = list.of_fn fun (i : fin (length (sigma.fst v))) => blocks (sigma.snd v i) := sorry /-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`. For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/ def gather {n : ℕ} (a : composition n) (b : composition (length a)) : composition n := mk (list.map list.sum (list.split_wrt_composition (blocks a) b)) sorry sorry theorem length_gather {n : ℕ} (a : composition n) (b : composition (length a)) : length (gather a b) = length b := sorry /-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of `a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of `a.gather b`. -/ def sigma_composition_aux {n : ℕ} (a : composition n) (b : composition (length a)) (i : fin (length (gather a b))) : composition (blocks_fun (gather a b) i) := mk (list.nth_le (list.split_wrt_composition (blocks a) b) ↑i sorry) sorry sorry theorem length_sigma_composition_aux {n : ℕ} (a : composition n) (b : composition (length a)) (i : fin (length b)) : length (sigma_composition_aux a b { val := ↑i, property := Eq.symm (length_gather a b) ▸ subtype.property i }) = blocks_fun b i := sorry theorem blocks_fun_sigma_composition_aux {n : ℕ} (a : composition n) (b : composition (length a)) (i : fin (length b)) (j : fin (blocks_fun b i)) : blocks_fun (sigma_composition_aux a b { val := ↑i, property := Eq.symm (length_gather a b) ▸ subtype.property i }) { val := ↑j, property := Eq.symm (length_sigma_composition_aux a b i) ▸ subtype.property j } = blocks_fun a (coe_fn (embedding b i) j) := sorry /-- Auxiliary lemma to prove that the composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a` that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks in `a.gather b`, and the second one to a sum of blocks in the next block of `sigma_composition_aux a b`. This is the content of this lemma. -/ theorem size_up_to_size_up_to_add {n : ℕ} (a : composition n) (b : composition (length a)) {i : ℕ} {j : ℕ} (hi : i < length b) (hj : j < blocks_fun b { val := i, property := hi }) : size_up_to a (size_up_to b i + j) = size_up_to (gather a b) i + size_up_to (sigma_composition_aux a b { val := i, property := Eq.symm (length_gather a b) ▸ hi }) j := sorry /-- Natural equivalence between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a change of variables in the proof that composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is the direct map in the equiv. Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the inverse map of the equiv. -/ def sigma_equiv_sigma_pi (n : ℕ) : (sigma fun (a : composition n) => composition (length a)) ≃ sigma fun (c : composition n) => (i : fin (length c)) → composition (blocks_fun c i) := equiv.mk (fun (i : sigma fun (a : composition n) => composition (length a)) => sigma.mk (gather (sigma.fst i) (sigma.snd i)) (sigma_composition_aux (sigma.fst i) (sigma.snd i))) (fun (i : sigma fun (c : composition n) => (i : fin (length c)) → composition (blocks_fun c i)) => sigma.mk (mk (list.join (list.of_fn fun (j : fin (length (sigma.fst i))) => blocks (sigma.snd i j))) sorry sorry) (mk (list.of_fn fun (j : fin (length (sigma.fst i))) => length (sigma.snd i j)) sorry sorry)) sorry sorry end composition namespace formal_multilinear_series theorem comp_assoc {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] {H : Type u_5} [normed_group H] [normed_space 𝕜 H] (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 H _inst_8 _inst_9 (formal_multilinear_series.comp 𝕜 _inst_1 F _inst_4 _inst_5 G _inst_6 _inst_7 H _inst_8 _inst_9 r q) p = formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 G _inst_6 _inst_7 H _inst_8 _inst_9 r (formal_multilinear_series.comp 𝕜 _inst_1 E _inst_2 _inst_3 F _inst_4 _inst_5 G _inst_6 _inst_7 q p) := sorry
82bce7e235424037b2626d5075247cb8014037b9
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/category/pairwise.lean
cba20b4bb1e2fd0445af510de0edacb8bfc6a273
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
4,291
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.preserves.basic import category_theory.limits.lattice /-! # The category of "pairwise intersections". Given `ι : Type v`, we build the diagram category `pairwise ι` with objects `single i` and `pair i j`, for `i j : ι`, whose only non-identity morphisms are `left : pair i j ⟶ single i` and `right : pair i j ⟶ single j`. We use this later in describing (one formulation of) the sheaf condition. Given any function `U : ι → α`, where `α` is some complete lattice (e.g. `(opens X)ᵒᵖ`), we produce a functor `pairwise ι ⥤ α` in the obvious way, and show that `supr U` provides a colimit cocone over this functor. -/ noncomputable theory universes v u open category_theory open category_theory.limits namespace category_theory /-- An inductive type representing either a single term of a type `ι`, or a pair of terms. We use this as the objects of a category to describe the sheaf condition. -/ inductive pairwise (ι : Type v) | single : ι → pairwise | pair : ι → ι → pairwise variables {ι : Type v} namespace pairwise instance pairwise_inhabited [inhabited ι] : inhabited (pairwise ι) := ⟨single (default ι)⟩ /-- Morphisms in the category `pairwise ι`. The only non-identity morphisms are `left i j : single i ⟶ pair i j` and `right i j : single j ⟶ pair i j`. -/ inductive hom : pairwise ι → pairwise ι → Type v | id_single : Π i, hom (single i) (single i) | id_pair : Π i j, hom (pair i j) (pair i j) | left : Π i j, hom (pair i j) (single i) | right : Π i j, hom (pair i j) (single j) open hom instance hom_inhabited [inhabited ι] : inhabited (hom (single (default ι)) (single (default ι))) := ⟨id_single (default ι)⟩ /-- The identity morphism in `pairwise ι`. -/ def id : Π (o : pairwise ι), hom o o | (single i) := id_single i | (pair i j) := id_pair i j /-- Composition of morphisms in `pairwise ι`. -/ def comp : Π {o₁ o₂ o₃ : pairwise ι} (f : hom o₁ o₂) (g : hom o₂ o₃), hom o₁ o₃ | _ _ _ (id_single i) g := g | _ _ _ (id_pair i j) g := g | _ _ _ (left i j) (id_single _) := left i j | _ _ _ (right i j) (id_single _) := right i j section local attribute [tidy] tactic.case_bash instance : category (pairwise ι) := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, } end variables {α : Type v} (U : ι → α) section variables [semilattice_inf α] /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_obj : pairwise ι → α | (single i) := U i | (pair i j) := U i ⊓ U j /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_map : Π {o₁ o₂ : pairwise ι} (f : o₁ ⟶ o₂), diagram_obj U o₁ ⟶ diagram_obj U o₂ | _ _ (id_single i) := 𝟙 _ | _ _ (id_pair i j) := 𝟙 _ | _ _ (left i j) := hom_of_le inf_le_left | _ _ (right i j) := hom_of_le inf_le_right /-- Given a function `U : ι → α` for `[semilattice_inf α]`, we obtain a functor `pairwise ι ⥤ α`, sending `single i` to `U i` and `pair i j` to `U i ⊓ U j`, and the morphisms to the obvious inequalities. -/ @[simps] def diagram : pairwise ι ⥤ α := { obj := diagram_obj U, map := λ X Y f, diagram_map U f, } end section -- `complete_lattice` is not really needed, as we only ever use `inf`, -- but the appropriate structure has not been defined. variables [complete_lattice α] /-- Auxilliary definition for `cocone`. -/ def cocone_ι_app : Π (o : pairwise ι), diagram_obj U o ⟶ supr U | (single i) := hom_of_le (le_supr U i) | (pair i j) := hom_of_le inf_le_left ≫ hom_of_le (le_supr U i) /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a cocone over `diagram U`. -/ @[simps] def cocone : cocone (diagram U) := { X := supr U, ι := { app := cocone_ι_app U, } } /-- Given a function `U : ι → α` for `[complete_lattice α]`, `infi U` provides a limit cone over `diagram U`. -/ def cocone_is_colimit : is_colimit (cocone U) := { desc := λ s, hom_of_le begin apply complete_lattice.Sup_le, rintros _ ⟨j, rfl⟩, exact le_of_hom (s.ι.app (single j)) end } end end pairwise end category_theory
b93f30cd7fa6d2ef8d3b364665f1eb6f4ae8425c
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/gcd_monoid.lean
d4c956703b0d9bb3275135a38340b2faaaebf38a
[ "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
31,281
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, Jens Wagemaker TODO: Provide a GCD monoid instance for `ℕ`, port GCD facts about nats TODO: Generalize normalization monoids commutative (cancellative) monoids with or without zero TODO: Generalize GCD monoid to not require normalization in all cases -/ import algebra.associated import data.nat.basic import data.int.gcd /-! # Monoids with normalization functions, `gcd`, and `lcm` This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `integral_domain`s. ## Main Definitions * `normalization_monoid` * `gcd_monoid` ## Implementation Notes * `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This definition as currently implemented does casework on `0`. * `gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids without zero. ## TODO * Provide a GCD monoid instance for `ℕ`, port GCD facts about nats, definition of coprime * Generalize normalization monoids to commutative (cancellative) monoids with or without zero * Generalize GCD monoid to not require normalization in all cases ## Tags divisibility, gcd, lcm, normalize -/ variables {α : Type*} set_option old_structure_cmd true /-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_monoid (α : Type*) [nontrivial α] [comm_cancel_monoid_with_zero α] := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 /-- Chooses an element of each associate class, by multiplying by `norm_unit` -/ def normalize : α →* α := { to_fun := λ x, x * norm_unit x, map_one' := by rw [norm_unit_one, units.coe_one, mul_one], map_mul' := λ x y, classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy, by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], } theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm lemma associates.mk_normalize {x : α} : associates.mk (normalize x) = associates.mk x := associates.mk_eq_mk_iff_associated.2 normalize_associated @[simp] lemma normalize_apply {x : α} : normalize x = x * norm_unit x := rfl @[simp] lemma normalize_zero : normalize (0 : α) = 0 := by simp @[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by simp lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ @[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba --can be proven by simp lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := units.dvd_mul_right --can be proven by simp lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := units.mul_right_dvd end normalization_monoid namespace associates variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] local attribute [instance] associated.setoid /-- Maps an element of `associates` back to the normalized element of its associate class -/ protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates /-- GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] extends normalization_monoid α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_monoid.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_monoid.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize.map_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize.map_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize.map_mul, normalize_gcd, one_mul, mul_right_inj' h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd units.coe_dvd (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize.map_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) end lcm namespace gcd_monoid theorem prime_of_irreducible {x : α} (hi: irreducible x) : prime x := ⟨hi.ne_zero, ⟨hi.1, λ a b h, begin cases gcd_dvd_left x a with y hy, cases hi.2 _ _ hy with hu hu; cases hu with u hu, { right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h, rw gcd_mul_right, rw ← hu, apply dvd_of_associated, transitivity (normalize b), symmetry, use u, apply mul_comm, apply normalize_associated, }, { left, rw [hy, ← hu], transitivity, {apply dvd_of_associated, symmetry, use u}, apply gcd_dvd_right, } end ⟩⟩ theorem irreducible_iff_prime {p : α} : irreducible p ↔ prime p := ⟨prime_of_irreducible, irreducible_of_prime⟩ end gcd_monoid end gcd_monoid namespace int section normalization_monoid instance : normalization_monoid ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos (le_refl _), norm_unit_mul := assume a b hna hnb, begin by_cases ha : 0 ≤ a; by_cases hb : 0 ≤ b; simp [ha, hb], exact if_pos (mul_nonneg ha hb), exact if_neg (assume h, hb $ nonneg_of_mul_nonneg_left h $ lt_of_le_of_ne ha hna.symm), exact if_neg (assume h, ha $ nonneg_of_mul_nonneg_right h $ lt_of_le_of_ne hb hnb.symm), exact if_pos (mul_nonneg_of_nonpos_of_nonpos (le_of_not_ge ha) (le_of_not_ge hb)) end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by simp [@neg_lt ℤ _ 1 0])), } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end end normalization_monoid /-- ℤ specific version of least common multiple. -/ def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j) theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl section gcd_monoid theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _ theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _ theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) := by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul] instance : gcd_monoid ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, normalize_gcd := assume a b, normalize_coe_nat _, gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _, .. int.normalization_monoid } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_monoid.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_monoid.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_monoid.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_monoid.lcm i j) = int.lcm i j := rfl end gcd_monoid theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd] @[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _ @[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _ theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero) theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero) theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := by rw [← int.coe_nat_eq_coe_nat_iff, int.coe_nat_zero, coe_gcd, gcd_eq_zero_iff] theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / nat_abs k := by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2]; exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2) theorem gcd_div_gcd_div_gcd {i j : ℤ} (H : 0 < gcd i j) : gcd (i / gcd i j) (j / gcd i j) = 1 := begin rw [gcd_div (gcd_dvd_left i j) (gcd_dvd_right i j)], rw [nat_abs_of_nat, nat.div_self H] end theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j) theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i := nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _) (by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j := by rw [gcd_comm, gcd_eq_left H] theorem ne_zero_of_gcd {x y : ℤ} (hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 := begin contrapose! hc, rw [hc.left, hc.right, gcd_zero_right, nat_abs_zero] end theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) : ∃ (m' n' : ℤ), gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, gcd_div_gcd_div_gcd H, (int.div_mul_cancel (gcd_dvd_left m n)).symm, (int.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) : ∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_gcd_one H in ⟨_, m', n', H, h⟩ theorem pow_dvd_pow_iff {m n : ℤ} {k : ℕ} (k0 : 0 < k) : m ^ k ∣ n ^ k ↔ m ∣ n := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, apply int.nat_abs_dvd_abs_iff.mp, apply (nat.pow_dvd_pow_iff k0).mp, rw [← int.nat_abs_pow, ← int.nat_abs_pow], exact int.nat_abs_dvd_abs_iff.mpr h end /- lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_comm] theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_assoc] @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_left _ _ theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_right _ _ theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := by rw [coe_lcm]; exact lcm_dvd end int theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) := ⟨λ hp, ⟨nat.pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one, λ a b, hp.dvd_mul.1⟩, λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩, λ a h, let ⟨b, hab⟩ := h in (hp.2.2 a b (hab ▸ dvd_refl _)).elim (λ ha, or.inr (nat.dvd_antisymm h ha)) (λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb (hab.symm ▸ dvd_mul_left _ _), (nat.mul_right_inj (show 0 < p, from nat.pos_of_ne_zero hp.1)).1 $ by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩ lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt is_unit_int.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ /-- Maps an associate class of integers consisting of `-n, n` to `n : ℕ` -/ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { intro n, dsimp, rw [associates.out_mk ↑n, ← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs := begin apply (nat.prime.dvd_mul hp).mp, rw ← int.nat_abs_mul, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n := begin rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left], exact int.prime.dvd_mul hp h end lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m := begin cases int.prime.dvd_mul hp h with hp2 hpp, { apply or.intro_left, exact le_antisymm (nat.le_of_dvd two_pos hp2) (nat.prime.two_le hp) }, { apply or.intro_right, rw [pow_two, int.nat_abs_mul] at hpp, exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)} end section unique_unit instance nat.unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } variables [comm_cancel_monoid_with_zero α] [unique (units α)] lemma units_eq_one (u : units α) : u = 1 := subsingleton.elim u 1 variable [nontrivial α] @[priority 100] -- see Note [lower instance priority] instance normalization_monoid_of_unique_units : normalization_monoid α := { norm_unit := λ x, 1, norm_unit_zero := rfl, norm_unit_mul := λ x y hx hy, (mul_one 1).symm, norm_unit_coe_units := λ u, subsingleton.elim _ _ } @[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl @[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x end unique_unit
a2449e734bd488b1faba125c69f6034b58eb1613
93f5d951583b87344f929a9ec18c4f603d920c4a
/src/summary.lean
62febc569a54147e546df2f68ca787475fee23ad
[ "Apache-2.0" ]
permissive
jesse-michael-han/flypitch
824a8c1955deb661943b02146d281932dad39302
b9a25b75f6a6c69bd2913c66a8e32fc67f196335
refs/heads/master
1,625,819,158,405
1,595,824,334,000
1,595,824,334,000
167,225,933
1
0
null
1,548,265,151,000
1,548,265,151,000
null
UTF-8
Lean
false
false
2,359
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import .zfc .completeness .print_formula open fol bSet pSet lattice collapse_algebra /- This file summarizes: - important definitions with #print statements, and - important theorems with duplicated proofs The user is encouraged to use their editor's jump-to-definition feature to inspect the source code of any expressions which are printed or which occur in the proofs below. -/ #print Language #print preterm #print preformula #print term #print formula #print sentence #print soundness #print prf #print provable #print is_consistent #print pSet #print bSet #print L_ZFC #print ZFC #eval print_formula_list ([ axiom_of_emptyset, axiom_of_ordered_pairs, axiom_of_extensionality, axiom_of_union, axiom_of_powerset, axiom_of_infinity, axiom_of_regularity, zorns_lemma ]) #print CH #print CH_f #print 𝔹_cohen #print 𝔹_collapse theorem godel_completeness_theorem {L} (T) (ψ : sentence L) : T ⊢' ψ ↔ T ⊨ ψ := completeness T ψ theorem boolean_valued_soundness_theorem {L} {β} [complete_boolean_algebra β] {T : Theory L} {A : sentence L} (H : T ⊢ A) : T ⊨[β] A := forced_of_bsatisfied $ boolean_formula_soundness H theorem fundamental_theorem_of_forcing {β} [nontrivial_complete_boolean_algebra β] : ⊤ ⊩[V β] ZFC := bSet_models_ZFC β theorem ZFC_is_consistent {β : Type} [nontrivial_complete_boolean_algebra β] : is_consistent ZFC := consis_of_exists_bmodel (bSet_models_ZFC β) theorem CH_unprovable : ¬ (ZFC ⊢' CH_f) := CH_f_unprovable theorem neg_CH_unprovable : ¬ (ZFC ⊢' ∼CH_f) := neg_CH_f_unprovable def independent {L : Language} (T : Theory L) (f : sentence L) : Prop := ¬ T ⊢' f ∧ ¬ T ⊢' ∼f theorem independence_of_CH : independent ZFC CH_f := and.intro CH_unprovable neg_CH_unprovable #print axioms independence_of_CH /- `propext` (propositional extensionality), `classical.choice` (a type-theoretic choice principle), and `quot.sound` (quotients) are the standard axioms in Lean. -/
a1665092dc3b81404e66f6bccf42ca3a346d2bcf
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/polynomial/chebyshev/defs_auto.lean
a6c5e56eefdb61ce94e1bdacd067b731cfe5e1e5
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,849
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.derivative import Mathlib.tactic.ring import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Chebyshev polynomials The Chebyshev polynomials are two families of polynomials indexed by `ℕ`, with integral coefficients. See the file `ring_theory.polynomial.chebyshev.basic` for more properties. ## Main definitions * `polynomial.chebyshev₁`: the Chebyshev polynomials of the first kind. * `polynomial.chebyshev₂`: the Chebyshev polynomials of the second kind. * `polynomial.lambdashev`: a variant on the Chebyshev polynomials that define a Lambda structure on `polynomial ℤ`. ## Main statements * The formal derivative of the Chebyshev polynomials of the first kind is a scalar multiple of the Chebyshev polynomials of the second kind. ## Implementation details In this file we only give definitions and some very elementary simp-lemmas. This way, we can import this file in `analysis.special_functions.trigonometric`, and import that file in turn, in `ring_theory.polynomial.chebyshev.basic`. ## References [Lionel Ponton, _Roots of the Chebyshev polynomials: A purely algebraic approach_] [ponton2020chebyshev] ## TODO * Redefine and/or relate the definition of Chebyshev polynomials to `linear_recurrence`. * Add explicit formula involving square roots for Chebyshev polynomials `ring_theory.polynomial.chebyshev.basic`. * Compute zeroes and extrema of Chebyshev polynomials. * Prove that the roots of the Chebyshev polynomials (except 0) are irrational. * Prove minimax properties of Chebyshev polynomials. * Define a variant of Chebyshev polynomials of the second kind removing the 2 (sometimes Dickson polynomials of the second kind) or even more general Dickson polynomials. * Prove that the adjacency matrices of simply laced Dynkin diagrams are precisely the adjacency matrices of simple connected graphs which annihilate the Dickson polynomials. -/ namespace polynomial /-- `chebyshev₁ n` is the `n`-th Chebyshev polynomial of the first kind -/ def chebyshev₁ (R : Type u_1) [comm_ring R] : ℕ → polynomial R := sorry @[simp] theorem chebyshev₁_zero (R : Type u_1) [comm_ring R] : chebyshev₁ R 0 = 1 := rfl @[simp] theorem chebyshev₁_one (R : Type u_1) [comm_ring R] : chebyshev₁ R 1 = X := rfl theorem chebyshev₁_two (R : Type u_1) [comm_ring R] : chebyshev₁ R (bit0 1) = bit0 1 * X ^ bit0 1 - 1 := sorry @[simp] theorem chebyshev₁_add_two (R : Type u_1) [comm_ring R] (n : ℕ) : chebyshev₁ R (n + bit0 1) = bit0 1 * X * chebyshev₁ R (n + 1) - chebyshev₁ R n := sorry theorem chebyshev₁_of_two_le (R : Type u_1) [comm_ring R] (n : ℕ) (h : bit0 1 ≤ n) : chebyshev₁ R n = bit0 1 * X * chebyshev₁ R (n - 1) - chebyshev₁ R (n - bit0 1) := sorry theorem map_chebyshev₁ {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] (f : R →+* S) (n : ℕ) : map f (chebyshev₁ R n) = chebyshev₁ S n := sorry /-- `lambdashev R n` is equal to `2 * (chebyshev₁ R n).comp (X / 2)`. It is a family of polynomials that satisfies `lambdashev (zmod p) p = X ^ p`, and therefore defines a Lambda structure on `polynomial ℤ`. -/ def lambdashev (R : Type u_1) [comm_ring R] : ℕ → polynomial R := sorry @[simp] theorem lambdashev_zero (R : Type u_1) [comm_ring R] : lambdashev R 0 = bit0 1 := rfl @[simp] theorem lambdashev_one (R : Type u_1) [comm_ring R] : lambdashev R 1 = X := rfl theorem lambdashev_two (R : Type u_1) [comm_ring R] : lambdashev R (bit0 1) = X ^ bit0 1 - bit0 1 := sorry @[simp] theorem lambdashev_add_two (R : Type u_1) [comm_ring R] (n : ℕ) : lambdashev R (n + bit0 1) = X * lambdashev R (n + 1) - lambdashev R n := sorry theorem lambdashev_eq_two_le (R : Type u_1) [comm_ring R] (n : ℕ) (h : bit0 1 ≤ n) : lambdashev R n = X * lambdashev R (n - 1) - lambdashev R (n - bit0 1) := sorry theorem map_lambdashev {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] (f : R →+* S) (n : ℕ) : map f (lambdashev R n) = lambdashev S n := sorry end polynomial namespace polynomial /-- `chebyshev₂ n` is the `n`-th Chebyshev polynomial of the second kind -/ def chebyshev₂ (R : Type u_1) [comm_ring R] : ℕ → polynomial R := sorry @[simp] theorem chebyshev₂_zero (R : Type u_1) [comm_ring R] : chebyshev₂ R 0 = 1 := rfl @[simp] theorem chebyshev₂_one (R : Type u_1) [comm_ring R] : chebyshev₂ R 1 = bit0 1 * X := rfl theorem chebyshev₂_two (R : Type u_1) [comm_ring R] : chebyshev₂ R (bit0 1) = bit0 (bit0 1) * X ^ bit0 1 - 1 := sorry @[simp] theorem chebyshev₂_add_two (R : Type u_1) [comm_ring R] (n : ℕ) : chebyshev₂ R (n + bit0 1) = bit0 1 * X * chebyshev₂ R (n + 1) - chebyshev₂ R n := sorry theorem chebyshev₂_of_two_le (R : Type u_1) [comm_ring R] (n : ℕ) (h : bit0 1 ≤ n) : chebyshev₂ R n = bit0 1 * X * chebyshev₂ R (n - 1) - chebyshev₂ R (n - bit0 1) := sorry theorem chebyshev₂_eq_X_mul_chebyshev₂_add_chebyshev₁ (R : Type u_1) [comm_ring R] (n : ℕ) : chebyshev₂ R (n + 1) = X * chebyshev₂ R n + chebyshev₁ R (n + 1) := sorry theorem chebyshev₁_eq_chebyshev₂_sub_X_mul_chebyshev₂ (R : Type u_1) [comm_ring R] (n : ℕ) : chebyshev₁ R (n + 1) = chebyshev₂ R (n + 1) - X * chebyshev₂ R n := sorry theorem chebyshev₁_eq_X_mul_chebyshev₁_sub_pol_chebyshev₂ (R : Type u_1) [comm_ring R] (n : ℕ) : chebyshev₁ R (n + bit0 1) = X * chebyshev₁ R (n + 1) - (1 - X ^ bit0 1) * chebyshev₂ R n := sorry theorem one_sub_X_pow_two_mul_chebyshev₂_eq_pol_in_chebyshev₁ (R : Type u_1) [comm_ring R] (n : ℕ) : (1 - X ^ bit0 1) * chebyshev₂ R n = X * chebyshev₁ R (n + 1) - chebyshev₁ R (n + bit0 1) := sorry @[simp] theorem map_chebyshev₂ {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] (f : R →+* S) (n : ℕ) : map f (chebyshev₂ R n) = chebyshev₂ S n := sorry theorem chebyshev₁_derivative_eq_chebyshev₂ {R : Type u_1} [comm_ring R] (n : ℕ) : coe_fn derivative (chebyshev₁ R (n + 1)) = (↑n + 1) * chebyshev₂ R n := sorry theorem one_sub_X_pow_two_mul_derivative_chebyshev₁_eq_poly_in_chebyshev₁ {R : Type u_1} [comm_ring R] (n : ℕ) : (1 - X ^ bit0 1) * coe_fn derivative (chebyshev₁ R (n + 1)) = (↑n + 1) * (chebyshev₁ R n - X * chebyshev₁ R (n + 1)) := sorry theorem add_one_mul_chebyshev₁_eq_poly_in_chebyshev₂ {R : Type u_1} [comm_ring R] (n : ℕ) : (↑n + 1) * chebyshev₁ R (n + 1) = X * chebyshev₂ R n - (1 - X ^ bit0 1) * coe_fn derivative (chebyshev₂ R n) := sorry end Mathlib
7d8556163524db5542332460ac541c6b0eb93bc8
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic/Simp/CongrLemmas.lean
a758a8abbe838efe02be9c262e7ea7f22330e630
[ "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
5,200
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.Basic namespace Lean.Meta structure CongrLemma where theoremName : Name funName : Name hypothesesPos : Array Nat priority : Nat deriving Inhabited, Repr structure CongrLemmas where lemmas : SMap Name (List CongrLemma) := {} deriving Inhabited, Repr def CongrLemmas.get (d : CongrLemmas) (declName : Name) : List CongrLemma := match d.lemmas.find? declName with | none => [] | some cs => cs def addCongrLemmaEntry (d : CongrLemmas) (e : CongrLemma) : CongrLemmas := { d with lemmas := match d.lemmas.find? e.funName with | none => d.lemmas.insert e.funName [e] | some es => d.lemmas.insert e.funName <| insert es } where insert : List CongrLemma → List CongrLemma | [] => [e] | e'::es => if e.priority ≥ e'.priority then e::e'::es else e' :: insert es builtin_initialize congrExtension : SimpleScopedEnvExtension CongrLemma CongrLemmas ← registerSimpleScopedEnvExtension { name := `congrExt initial := {} addEntry := addCongrLemmaEntry finalizeImport := fun s => { s with lemmas := s.lemmas.switch } } def mkCongrLemma (declName : Name) (prio : Nat) : MetaM CongrLemma := withReducible do let c ← mkConstWithLevelParams declName let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType c) match type.eq? with | none => throwError "invalid 'congr' theorem, equality expected{indentExpr type}" | some (_, lhs, rhs) => lhs.withApp fun lhsFn lhsArgs => rhs.withApp fun rhsFn rhsArgs => do unless lhsFn.isConst && rhsFn.isConst && lhsFn.constName! == rhsFn.constName! && lhsArgs.size == rhsArgs.size do throwError "invalid 'congr' theorem, equality left/right-hand sides must be applications of the same function{indentExpr type}" let mut foundMVars : MVarIdSet := {} for lhsArg in lhsArgs do unless lhsArg.isSort do unless lhsArg.isMVar do throwError "invalid 'congr' theorem, arguments in the left-hand-side must be variables or sorts{indentExpr lhs}" foundMVars := foundMVars.insert lhsArg.mvarId! let mut i := 0 let mut hypothesesPos := #[] for x in xs, bi in bis do if bi.isExplicit && !foundMVars.contains x.mvarId! then let rhsFn? ← forallTelescopeReducing (← inferType x) fun ys xType => do match xType.eq? with | none => pure none -- skip | some (_, xLhs, xRhs) => let mut j := 0 for y in ys do let yType ← inferType y unless onlyMVarsAt yType foundMVars do throwError "invalid 'congr' theorem, argument #{j+1} of parameter #{i+1} contains unresolved parameter{indentExpr yType}" j := j + 1 unless onlyMVarsAt xLhs foundMVars do throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the left-hand-side contains unresolved parameters{indentExpr xLhs}" let xRhsFn := xRhs.getAppFn unless xRhsFn.isMVar do throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head is not a metavariable{indentExpr xRhs}" unless !foundMVars.contains xRhsFn.mvarId! do throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head was already resolved{indentExpr xRhs}" for arg in xRhs.getAppArgs do unless arg.isFVar do throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side argument is not local variable{indentExpr xRhs}" pure (some xRhsFn) match rhsFn? with | none => pure () | some rhsFn => foundMVars := foundMVars.insert x.mvarId! |>.insert rhsFn.mvarId! hypothesesPos := hypothesesPos.push i i := i + 1 trace[Meta.debug] "c: {c} : {type}" return { theoremName := declName funName := lhsFn.constName! hypothesesPos := hypothesesPos priority := prio } where /-- Return `true` if `t` contains a metavariable that is not in `mvarSet` -/ onlyMVarsAt (t : Expr) (mvarSet : MVarIdSet) : Bool := Option.isNone <| t.find? fun e => e.isMVar && !mvarSet.contains e.mvarId! def addCongrLemma (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let lemma ← mkCongrLemma declName prio congrExtension.add lemma attrKind builtin_initialize registerBuiltinAttribute { name := `congr descr := "congruence theorem" add := fun declName stx attrKind => do let prio ← getAttrParamOptPrio stx[1] discard <| addCongrLemma declName attrKind prio |>.run {} {} } def getCongrLemmas : MetaM CongrLemmas := return congrExtension.getState (← getEnv) end Lean.Meta
c90d5a6900ed279ce8a2822d661c745ad907bd3f
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Server/FileWorker.lean
a3caa6ef1c24bd20df86d2269291b70c06cce7d3
[ "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
17,909
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 Init.System.IO import Std.Data.RBMap import Lean.Environment import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Server.Utils import Lean.Server.Snapshots import Lean.Server.AsyncList import Lean.Server.FileWorker.Utils import Lean.Server.FileWorker.RequestHandling /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Std (RBMap RBMap.empty) open JsonRpc /- Asynchronous snapshot elaboration. -/ section Elab /-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) : ExceptT ElabTaskError IO Snapshot := do cancelTk.check publishProgressAtPos m parentSnap.endPos hOut let maybeSnap ← compileNextCmd m.text.source parentSnap -- TODO(MH): check for interrupt with increased precision cancelTk.check match maybeSnap with | Sum.inl snap => /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ if snap.msgLog.msgs.size > parentSnap.msgLog.msgs.size then publishMessages m snap.msgLog hOut snap | Sum.inr msgLog => publishMessages m msgLog hOut publishProgressDone m hOut throw ElabTaskError.eof /-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) (initial : Bool) : IO (AsyncList ElabTaskError Snapshot) := do if initial && initSnap.msgLog.hasErrors then -- treat header processing errors as fatal so users aren't swamped with followup errors AsyncList.nil else AsyncList.unfoldAsync (nextCmdSnap m . cancelTk hOut) initSnap end Elab -- Pending requests are tracked so they can be cancelled abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) compare structure WorkerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream srcSearchPath : SearchPath docRef : IO.Ref EditableDocument pendingRequestsRef : IO.Ref PendingRequestMap abbrev WorkerM := ReaderT WorkerContext IO /- Worker initialization sequence. -/ section Initialization /-- Use `leanpkg print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`. Compilation progress is reported to `hOut` via LSP notifications. Return the search path for source files. -/ partial def leanpkgSetupSearchPath (leanpkgPath : System.FilePath) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do let leanpkgProc ← Process.spawn { stdin := Process.Stdio.null stdout := Process.Stdio.piped stderr := Process.Stdio.piped cmd := leanpkgPath.toString args := #["print-paths"] ++ imports.map (toString ·.module) } -- progress notification: report latest stderr line let rec processStderr (acc : String) : IO String := do let line ← leanpkgProc.stderr.getLine if line == "" then return acc else publishDiagnostics m #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] hOut processStderr (acc ++ line) let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated let stdout := String.trim (← leanpkgProc.stdout.readToEnd) let stderr ← IO.ofExcept stderr.get if (← leanpkgProc.wait) == 0 then let leanpkgLines := stdout.split (· == '\n') -- ignore any output up to the last two lines -- TODO: leanpkg should instead redirect nested stdout output to stderr let leanpkgLines := leanpkgLines.drop (leanpkgLines.length - 2) match leanpkgLines with | [""] => pure [] -- e.g. no leanpkg.toml | [leanPath, leanSrcPath] => let sp ← getBuiltinSearchPath let sp ← addSearchPathFromEnv sp let sp := System.SearchPath.parse leanPath ++ sp searchPathRef.set sp let srcPath := System.SearchPath.parse leanSrcPath srcPath.mapM realPathNormalized | _ => throwServerError s!"unexpected output from `leanpkg print-paths`:\n{stdout}\nstderr:\n{stderr}" else throwServerError s!"`leanpkg print-paths` failed:\n{stdout}\nstderr:\n{stderr}" def compileHeader (m : DocumentMeta) (hOut : FS.Stream) : IO (Snapshot × SearchPath) := do let opts := {} -- TODO let inputCtx := Parser.mkInputContext m.text.source "<input>" let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx let leanpkgPath ← match (← IO.getEnv "LEAN_SYSROOT") with | some path => pure <| System.FilePath.mk path / "bin" / "leanpkg" | _ => pure <| (← appDir) / "leanpkg" let leanpkgPath := leanpkgPath.withExtension System.FilePath.exeExtension let mut srcSearchPath := [(← appDir) / ".." / "lib" / "lean" / "src"] if let some p := (← IO.getEnv "LEAN_SRC_PATH") then srcSearchPath := srcSearchPath ++ System.SearchPath.parse p let (headerEnv, msgLog) ← try -- NOTE: leanpkg does not exist in stage 0 (yet?) if (← System.FilePath.pathExists leanpkgPath) then let pkgSearchPath ← leanpkgSetupSearchPath leanpkgPath m (Lean.Elab.headerToImports headerStx).toArray hOut srcSearchPath := srcSearchPath ++ pkgSearchPath Elab.processHeader headerStx opts msgLog inputCtx catch e => -- should be from `leanpkg print-paths` let msgs := MessageLog.empty.add { fileName := "<ignored>", pos := ⟨0, 0⟩, data := e.toString } pure (← mkEmptyEnvironment, msgs) publishMessages m msgLog hOut let cmdState := Elab.Command.mkState headerEnv msgLog opts let cmdState := { cmdState with infoState.enabled := true, scopes := [{ header := "", opts := opts }] } let headerSnap := { beginPos := 0 stx := headerStx mpState := headerParserState cmdState := cmdState } return (headerSnap, srcSearchPath) def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream) : IO WorkerContext := do /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ let (headerSnap, srcSearchPath) ← compileHeader meta o let cancelTk ← CancelToken.new let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk o (initial := true) let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩ return { hIn := i hOut := o hLog := e srcSearchPath := srcSearchPath docRef := ←IO.mkRef doc pendingRequestsRef := ←IO.mkRef RBMap.empty } end Initialization section Updates def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : WorkerM Unit := do (←read).pendingRequestsRef.modify map /-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : WorkerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let st ← read let oldDoc ← st.docRef.get let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some ElabTaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (ElabTaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.hOut (initial := true) st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk st.hOut (initial := false) let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ end Updates /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidChange (p : DidChangeTextDocumentParams) : WorkerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc ← (←read).docRef.get let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff def handleCancelRequest (p : CancelParams) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) end NotificationHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : WorkerM paramType := match fromJson? params with | Except.ok parsed => pure parsed | Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}" def handleNotification (method : String) (params : Json) : WorkerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → WorkerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : WorkerM Unit := do let st ← read let rc : Requests.RequestContext := { srcSearchPath := st.srcSearchPath docRef := st.docRef hLog := st.hLog } let t? ← (ExceptT.run <| Requests.handleLspRequest method params rc : IO _) let t₁ ← match t? with | Except.error e => IO.asTask do st.hOut.writeLspResponseError <| e.toLspResponseError id | Except.ok t => (IO.mapTask · t) fun | Except.ok resp => st.hOut.writeLspResponse ⟨id, resp⟩ | Except.error e => st.hOut.writeLspResponseError <| e.toLspResponseError id queueRequest id t₁ end MessageHandling section MainLoop partial def mainLoop : WorkerM Unit := do let st ← read let msg ← st.hIn.readLspMessage let pendingRequests ← st.pendingRequestsRef.get let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : WorkerM PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests st.pendingRequestsRef.set pendingRequests match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => let doc ← st.docRef.get doc.cancelTk.set return () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) : IO UInt32 := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let doc := param.textDocument let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩ let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e try let ctx ← initializeWorker meta i o e ReaderT.run (r := ctx) mainLoop return 0 catch e => IO.eprintln e publishDiagnostics meta #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] o return 1 @[export lean_server_worker_main] def workerMain : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try let exitCode ← initAndRunWorker i o e -- HACK: all `Task`s are currently "foreground", i.e. we join on them on main thread exit, but we definitely don't -- want to do that in the case of the worker processes, which can produce non-terminating tasks evaluating user code o.flush e.flush IO.Process.exit exitCode.toUInt8 catch err => e.putStrLn s!"worker initialization error: {err}" return (1 : UInt32) end Lean.Server.FileWorker
8513a0ede836da6fbc3ad58316013d0f6d4b292a
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/topology/uniform_space/equiv.lean
037462f508c2a553366b0a52cadc32c8cc43b703
[ "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
11,966
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton, Anatole Dedecker -/ import topology.homeomorph import topology.uniform_space.uniform_embedding import topology.uniform_space.pi /-! # Uniform isomorphisms This file defines uniform isomorphisms between two uniform spaces. They are bijections with both directions uniformly continuous. We denote uniform isomorphisms with the notation `≃ᵤ`. # Main definitions * `uniform_equiv α β`: The type of uniform isomorphisms from `α` to `β`. This type can be denoted using the following notation: `α ≃ᵤ β`. -/ open set filter open_locale variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Uniform isomorphism between `α` and `β` -/ @[nolint has_nonempty_instance] -- not all spaces are homeomorphic to each other structure uniform_equiv (α : Type*) (β : Type*) [uniform_space α] [uniform_space β] extends α ≃ β := (uniform_continuous_to_fun : uniform_continuous to_fun) (uniform_continuous_inv_fun : uniform_continuous inv_fun) infix ` ≃ᵤ `:25 := uniform_equiv namespace uniform_equiv variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] instance : has_coe_to_fun (α ≃ᵤ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩ @[simp] lemma uniform_equiv_mk_coe (a : equiv α β) (b c) : ((uniform_equiv.mk a b c) : α → β) = a := rfl /-- Inverse of a uniform isomorphism. -/ protected def symm (h : α ≃ᵤ β) : β ≃ᵤ α := { uniform_continuous_to_fun := h.uniform_continuous_inv_fun, uniform_continuous_inv_fun := h.uniform_continuous_to_fun, to_equiv := h.to_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : α ≃ᵤ β) : α → β := h /-- See Note [custom simps projection] -/ def simps.symm_apply (h : α ≃ᵤ β) : β → α := h.symm initialize_simps_projections uniform_equiv (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv) @[simp] lemma coe_to_equiv (h : α ≃ᵤ β) : ⇑h.to_equiv = h := rfl @[simp] lemma coe_symm_to_equiv (h : α ≃ᵤ β) : ⇑h.to_equiv.symm = h.symm := rfl lemma to_equiv_injective : function.injective (to_equiv : α ≃ᵤ β → α ≃ β) | ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl @[ext] lemma ext {h h' : α ≃ᵤ β} (H : ∀ x, h x = h' x) : h = h' := to_equiv_injective $ equiv.ext H /-- Identity map as a uniform isomorphism. -/ @[simps apply {fully_applied := ff}] protected def refl (α : Type*) [uniform_space α] : α ≃ᵤ α := { uniform_continuous_to_fun := uniform_continuous_id, uniform_continuous_inv_fun := uniform_continuous_id, to_equiv := equiv.refl α } /-- Composition of two uniform isomorphisms. -/ protected def trans (h₁ : α ≃ᵤ β) (h₂ : β ≃ᵤ γ) : α ≃ᵤ γ := { uniform_continuous_to_fun := h₂.uniform_continuous_to_fun.comp h₁.uniform_continuous_to_fun, uniform_continuous_inv_fun := h₁.uniform_continuous_inv_fun.comp h₂.uniform_continuous_inv_fun, to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv } @[simp] lemma trans_apply (h₁ : α ≃ᵤ β) (h₂ : β ≃ᵤ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl @[simp] lemma uniform_equiv_mk_coe_symm (a : equiv α β) (b c) : ((uniform_equiv.mk a b c).symm : β → α) = a.symm := rfl @[simp] lemma refl_symm : (uniform_equiv.refl α).symm = uniform_equiv.refl α := rfl protected lemma uniform_continuous (h : α ≃ᵤ β) : uniform_continuous h := h.uniform_continuous_to_fun @[continuity] protected lemma continuous (h : α ≃ᵤ β) : continuous h := h.uniform_continuous.continuous protected lemma uniform_continuous_symm (h : α ≃ᵤ β) : uniform_continuous (h.symm) := h.uniform_continuous_inv_fun @[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm` protected lemma continuous_symm (h : α ≃ᵤ β) : continuous (h.symm) := h.uniform_continuous_symm.continuous /-- A uniform isomorphism as a homeomorphism. -/ @[simps] protected def to_homeomorph (e : α ≃ᵤ β) : α ≃ₜ β := { continuous_to_fun := e.continuous, continuous_inv_fun := e.continuous_symm, .. e.to_equiv } @[simp] lemma apply_symm_apply (h : α ≃ᵤ β) (x : β) : h (h.symm x) = x := h.to_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (h : α ≃ᵤ β) (x : α) : h.symm (h x) = x := h.to_equiv.symm_apply_apply x protected lemma bijective (h : α ≃ᵤ β) : function.bijective h := h.to_equiv.bijective protected lemma injective (h : α ≃ᵤ β) : function.injective h := h.to_equiv.injective protected lemma surjective (h : α ≃ᵤ β) : function.surjective h := h.to_equiv.surjective /-- Change the uniform equiv `f` to make the inverse function definitionally equal to `g`. -/ def change_inv (f : α ≃ᵤ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ᵤ β := have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm ... = f.symm x : by rw hg x), { to_fun := f, inv_fun := g, left_inv := by convert f.left_inv, right_inv := by convert f.right_inv, uniform_continuous_to_fun := f.uniform_continuous, uniform_continuous_inv_fun := by convert f.symm.uniform_continuous } @[simp] lemma symm_comp_self (h : α ≃ᵤ β) : ⇑h.symm ∘ ⇑h = id := funext h.symm_apply_apply @[simp] lemma self_comp_symm (h : α ≃ᵤ β) : ⇑h ∘ ⇑h.symm = id := funext h.apply_symm_apply @[simp] lemma range_coe (h : α ≃ᵤ β) : range h = univ := h.surjective.range_eq lemma image_symm (h : α ≃ᵤ β) : image h.symm = preimage h := funext h.symm.to_equiv.image_eq_preimage lemma preimage_symm (h : α ≃ᵤ β) : preimage h.symm = image h := (funext h.to_equiv.image_eq_preimage).symm @[simp] lemma image_preimage (h : α ≃ᵤ β) (s : set β) : h '' (h ⁻¹' s) = s := h.to_equiv.image_preimage s @[simp] lemma preimage_image (h : α ≃ᵤ β) (s : set α) : h ⁻¹' (h '' s) = s := h.to_equiv.preimage_image s protected lemma uniform_inducing (h : α ≃ᵤ β) : uniform_inducing h := uniform_inducing_of_compose h.uniform_continuous h.symm.uniform_continuous $ by simp only [symm_comp_self, uniform_inducing_id] lemma comap_eq (h : α ≃ᵤ β) : uniform_space.comap h ‹_› = ‹_› := by ext : 1; exact h.uniform_inducing.comap_uniformity protected lemma uniform_embedding (h : α ≃ᵤ β) : uniform_embedding h := ⟨h.uniform_inducing, h.injective⟩ /-- Uniform equiv given a uniform embedding. -/ noncomputable def of_uniform_embedding (f : α → β) (hf : uniform_embedding f) : α ≃ᵤ (set.range f) := { uniform_continuous_to_fun := uniform_continuous_subtype_mk hf.to_uniform_inducing.uniform_continuous _, uniform_continuous_inv_fun := by simp [hf.to_uniform_inducing.uniform_continuous_iff, uniform_continuous_subtype_coe], to_equiv := equiv.of_injective f hf.inj } /-- If two sets are equal, then they are uniformly equivalent. -/ def set_congr {s t : set α} (h : s = t) : s ≃ᵤ t := { uniform_continuous_to_fun := uniform_continuous_subtype_mk uniform_continuous_subtype_val _, uniform_continuous_inv_fun := uniform_continuous_subtype_mk uniform_continuous_subtype_val _, to_equiv := equiv.set_congr h } /-- Product of two uniform isomorphisms. -/ def prod_congr (h₁ : α ≃ᵤ β) (h₂ : γ ≃ᵤ δ) : α × γ ≃ᵤ β × δ := { uniform_continuous_to_fun := (h₁.uniform_continuous.comp uniform_continuous_fst).prod_mk (h₂.uniform_continuous.comp uniform_continuous_snd), uniform_continuous_inv_fun := (h₁.symm.uniform_continuous.comp uniform_continuous_fst).prod_mk (h₂.symm.uniform_continuous.comp uniform_continuous_snd), to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv } @[simp] lemma prod_congr_symm (h₁ : α ≃ᵤ β) (h₂ : γ ≃ᵤ δ) : (h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl @[simp] lemma coe_prod_congr (h₁ : α ≃ᵤ β) (h₂ : γ ≃ᵤ δ) : ⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl section variables (α β γ) /-- `α × β` is uniformly isomorphic to `β × α`. -/ def prod_comm : α × β ≃ᵤ β × α := { uniform_continuous_to_fun := uniform_continuous_snd.prod_mk uniform_continuous_fst, uniform_continuous_inv_fun := uniform_continuous_snd.prod_mk uniform_continuous_fst, to_equiv := equiv.prod_comm α β } @[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl @[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl /-- `(α × β) × γ` is uniformly isomorphic to `α × (β × γ)`. -/ def prod_assoc : (α × β) × γ ≃ᵤ α × (β × γ) := { uniform_continuous_to_fun := (uniform_continuous_fst.comp uniform_continuous_fst).prod_mk ((uniform_continuous_snd.comp uniform_continuous_fst).prod_mk uniform_continuous_snd), uniform_continuous_inv_fun := (uniform_continuous_fst.prod_mk (uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk (uniform_continuous_snd.comp uniform_continuous_snd), to_equiv := equiv.prod_assoc α β γ } /-- `α × {*}` is uniformly isomorphic to `α`. -/ @[simps apply {fully_applied := ff}] def prod_punit : α × punit ≃ᵤ α := { to_equiv := equiv.prod_punit α, uniform_continuous_to_fun := uniform_continuous_fst, uniform_continuous_inv_fun := uniform_continuous_id.prod_mk uniform_continuous_const } /-- `{*} × α` is uniformly isomorphic to `α`. -/ def punit_prod : punit × α ≃ᵤ α := (prod_comm _ _).trans (prod_punit _) @[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl end /-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/ @[simps { fully_applied := ff }] def fun_unique (ι α : Type*) [unique ι] [uniform_space α] : (ι → α) ≃ᵤ α := { to_equiv := equiv.fun_unique ι α, uniform_continuous_to_fun := Pi.uniform_continuous_proj _ _, uniform_continuous_inv_fun := uniform_continuous_pi.mpr (λ _, uniform_continuous_id) } /-- Uniform isomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/ @[simps { fully_applied := ff }] def {u} pi_fin_two (α : fin 2 → Type u) [Π i, uniform_space (α i)] : (Π i, α i) ≃ᵤ α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, uniform_continuous_to_fun := (Pi.uniform_continuous_proj _ 0).prod_mk (Pi.uniform_continuous_proj _ 1), uniform_continuous_inv_fun := uniform_continuous_pi.mpr $ fin.forall_fin_two.2 ⟨uniform_continuous_fst, uniform_continuous_snd⟩ } /-- Uniform isomorphism between `α² = fin 2 → α` and `α × α`. -/ @[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ᵤ α × α := { to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) } /-- A subset of a uniform space is uniformly isomorphic to its image under a uniform isomorphism. -/ def image (e : α ≃ᵤ β) (s : set α) : s ≃ᵤ e '' s := { uniform_continuous_to_fun := uniform_continuous_subtype_mk (e.uniform_continuous.comp uniform_continuous_subtype_val) (λ x, mem_image_of_mem _ x.2), uniform_continuous_inv_fun := uniform_continuous_subtype_mk (e.symm.uniform_continuous.comp uniform_continuous_subtype_val) (λ x, by simpa using mem_image_of_mem e.symm x.2), to_equiv := e.to_equiv.image s } end uniform_equiv /-- A uniform inducing equiv between uniform spaces is a uniform isomorphism. -/ @[simps] def equiv.to_uniform_equiv_of_uniform_inducing [uniform_space α] [uniform_space β] (f : α ≃ β) (hf : uniform_inducing f) : α ≃ᵤ β := { uniform_continuous_to_fun := hf.uniform_continuous, uniform_continuous_inv_fun := hf.uniform_continuous_iff.2 $ by simpa using uniform_continuous_id, .. f }
83f410d4a2d32b8b6e7b30cbe0c226d805d569bd
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/prod/basic.lean
23378d994e015cad0e2c83032a300b4772365352
[ "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
9,738
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import tactic.basic /-! # Extra facts about `prod` This file defines `prod.swap : α × β → β × α` and proves various simple lemmas about `prod`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} @[simp] lemma prod_map (f : α → γ) (g : β → δ) (p : α × β) : prod.map f g p = (f p.1, g p.2) := rfl namespace prod @[simp] theorem «forall» {p : α × β → Prop} : (∀ x, p x) ↔ (∀ a b, p (a, b)) := ⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩ @[simp] theorem «exists» {p : α × β → Prop} : (∃ x, p x) ↔ (∃ a b, p (a, b)) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ theorem forall' {p : α → β → Prop} : (∀ x : α × β, p x.1 x.2) ↔ ∀ a b, p a b := prod.forall theorem exists' {p : α → β → Prop} : (∃ x : α × β, p x.1 x.2) ↔ ∃ a b, p a b := prod.exists @[simp] lemma snd_comp_mk (x : α) : prod.snd ∘ (prod.mk x : β → α × β) = id := rfl @[simp] lemma fst_comp_mk (x : α) : prod.fst ∘ (prod.mk x : β → α × β) = function.const β x := rfl @[simp] lemma map_mk (f : α → γ) (g : β → δ) (a : α) (b : β) : map f g (a, b) = (f a, g b) := rfl lemma map_fst (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).1 = f (p.1) := rfl lemma map_snd (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).2 = g (p.2) := rfl lemma map_fst' (f : α → γ) (g : β → δ) : (prod.fst ∘ map f g) = f ∘ prod.fst := funext $ map_fst f g lemma map_snd' (f : α → γ) (g : β → δ) : (prod.snd ∘ map f g) = g ∘ prod.snd := funext $ map_snd f g /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions. -/ lemma map_comp_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) : prod.map g g' ∘ prod.map f f' = prod.map (g ∘ f) (g' ∘ f') := rfl /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions, fully applied. -/ lemma map_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) (x : α × γ) : prod.map g g' (prod.map f f' x) = prod.map (g ∘ f) (g' ∘ f') x := rfl @[simp] theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) := ⟨prod.mk.inj, by cc⟩ lemma mk.inj_left {α β : Type*} (a : α) : function.injective (prod.mk a : β → α × β) := by { intros b₁ b₂ h, simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true] using h } lemma mk.inj_right {α β : Type*} (b : β) : function.injective (λ a, prod.mk a b : α → α × β) := by { intros b₁ b₂ h, by simpa only [and_true, eq_self_iff_true, mk.inj_iff] using h } lemma ext_iff {p q : α × β} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 := by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff] @[ext] lemma ext {α β} {p q : α × β} (h₁ : p.1 = q.1) (h₂ : p.2 = q.2) : p = q := ext_iff.2 ⟨h₁, h₂⟩ lemma map_def {f : α → γ} {g : β → δ} : prod.map f g = λ (p : α × β), (f p.1, g p.2) := funext (λ p, ext (map_fst f g p) (map_snd f g p)) lemma id_prod : (λ (p : α × β), (p.1, p.2)) = id := funext $ λ ⟨a, b⟩, rfl lemma map_id : (prod.map (@id α) (@id β)) = id := id_prod lemma fst_surjective [h : nonempty β] : function.surjective (@fst α β) := λ x, h.elim $ λ y, ⟨⟨x, y⟩, rfl⟩ lemma snd_surjective [h : nonempty α] : function.surjective (@snd α β) := λ y, h.elim $ λ x, ⟨⟨x, y⟩, rfl⟩ lemma fst_injective [subsingleton β] : function.injective (@fst α β) := λ x y h, ext h (subsingleton.elim _ _) lemma snd_injective [subsingleton α] : function.injective (@snd α β) := λ x y h, ext (subsingleton.elim _ _) h /-- Swap the factors of a product. `swap (a, b) = (b, a)` -/ def swap : α × β → β × α := λp, (p.2, p.1) @[simp] lemma swap_swap : ∀ x : α × β, swap (swap x) = x | ⟨a, b⟩ := rfl @[simp] lemma fst_swap {p : α × β} : (swap p).1 = p.2 := rfl @[simp] lemma snd_swap {p : α × β} : (swap p).2 = p.1 := rfl @[simp] lemma swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α × β) := funext swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap lemma swap_injective : function.injective (@swap α β) := swap_left_inverse.injective lemma swap_surjective : function.surjective (@swap α β) := swap_left_inverse.surjective lemma swap_bijective : function.bijective (@swap α β) := ⟨swap_injective, swap_surjective⟩ @[simp] lemma swap_inj {p q : α × β} : swap p = swap q ↔ p = q := swap_injective.eq_iff lemma eq_iff_fst_eq_snd_eq : ∀{p q : α × β}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2) | ⟨p₁, p₂⟩ ⟨q₁, q₂⟩ := by simp lemma fst_eq_iff : ∀ {p : α × β} {x : α}, p.1 = x ↔ p = (x, p.2) | ⟨a, b⟩ x := by simp lemma snd_eq_iff : ∀ {p : α × β} {x : β}, p.2 = x ↔ p = (p.1, x) | ⟨a, b⟩ x := by simp theorem lex_def (r : α → α → Prop) (s : β → β → Prop) {p q : α × β} : prod.lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 := ⟨λ h, by cases h; simp *, λ h, match p, q, h with | (a, b), (c, d), or.inl h := lex.left _ _ h | (a, b), (c, d), or.inr ⟨e, h⟩ := by change a = c at e; subst e; exact lex.right _ h end⟩ instance lex.decidable [decidable_eq α] (r : α → α → Prop) (s : β → β → Prop) [decidable_rel r] [decidable_rel s] : decidable_rel (prod.lex r s) := λ p q, decidable_of_decidable_of_iff (by apply_instance) (lex_def r s).symm @[refl] lemma lex.refl_left (r : α → α → Prop) (s : β → β → Prop) [is_refl α r] : ∀ x, prod.lex r s x x | (x₁, x₂) := lex.left _ _ (refl _) instance is_refl_left {r : α → α → Prop} {s : β → β → Prop} [is_refl α r] : is_refl (α × β) (lex r s) := ⟨lex.refl_left _ _⟩ @[refl] lemma lex.refl_right (r : α → α → Prop) (s : β → β → Prop) [is_refl β s] : ∀ x, prod.lex r s x x | (x₁, x₂) := lex.right _ (refl _) instance is_refl_right {r : α → α → Prop} {s : β → β → Prop} [is_refl β s] : is_refl (α × β) (lex r s) := ⟨lex.refl_right _ _⟩ @[trans] lemma lex.trans {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] : ∀ {x y z : α × β}, prod.lex r s x y → prod.lex r s y z → prod.lex r s x z | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.left _ _ hyz₁) := lex.left _ _ (trans hxy₁ hyz₁) | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.right _ hyz₂) := lex.left _ _ hxy₁ | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ _) (lex.left _ _ hyz₁) := lex.left _ _ hyz₁ | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ hxy₂) (lex.right _ hyz₂) := lex.right _ (trans hxy₂ hyz₂) instance {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] : is_trans (α × β) (lex r s) := ⟨λ _ _ _, lex.trans⟩ instance {r : α → α → Prop} {s : β → β → Prop} [is_strict_order α r] [is_antisymm β s] : is_antisymm (α × β) (lex r s) := ⟨λ x₁ x₂ h₁₂ h₂₁, match x₁, x₂, h₁₂, h₂₁ with | (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.left _ _ hr₂ := (irrefl a₁ (trans hr₁ hr₂)).elim | (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.right _ _ := (irrefl _ hr₁).elim | (a₁, b₁), (a₂, b₂), lex.right _ _, lex.left _ _ hr₂ := (irrefl _ hr₂).elim | (a₁, b₁), (a₂, b₂), lex.right _ hs₁, lex.right _ hs₂ := antisymm hs₁ hs₂ ▸ rfl end⟩ instance is_total_left {r : α → α → Prop} {s : β → β → Prop} [is_total α r] : is_total (α × β) (lex r s) := ⟨λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, (is_total.total a₁ a₂).imp (lex.left _ _) (lex.left _ _)⟩ instance is_total_right {r : α → α → Prop} {s : β → β → Prop} [is_trichotomous α r] [is_total β s] : is_total (α × β) (lex r s) := ⟨λ ⟨i, a⟩ ⟨j, b⟩, begin obtain hij | rfl | hji := trichotomous_of r i j, { exact or.inl (lex.left _ _ hij) }, { exact (total_of (s) a b).imp (lex.right _) (lex.right _), }, { exact or.inr (lex.left _ _ hji) } end⟩ end prod open prod namespace function variables {f : α → γ} {g : β → δ} {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} lemma injective.prod_map (hf : injective f) (hg : injective g) : injective (map f g) := λ x y h, ext (hf (ext_iff.1 h).1) (hg $ (ext_iff.1 h).2) lemma surjective.prod_map (hf : surjective f) (hg : surjective g) : surjective (map f g) := λ p, let ⟨x, hx⟩ := hf p.1 in let ⟨y, hy⟩ := hg p.2 in ⟨(x, y), prod.ext hx hy⟩ lemma bijective.prod_map (hf : bijective f) (hg : bijective g) : bijective (map f g) := ⟨hf.1.prod_map hg.1, hf.2.prod_map hg.2⟩ lemma left_inverse.prod_map (hf : left_inverse f₁ f₂) (hg : left_inverse g₁ g₂) : left_inverse (map f₁ g₁) (map f₂ g₂) := λ a, by rw [prod.map_map, hf.comp_eq_id, hg.comp_eq_id, map_id, id] lemma right_inverse.prod_map : right_inverse f₁ f₂ → right_inverse g₁ g₂ → right_inverse (map f₁ g₁) (map f₂ g₂) := left_inverse.prod_map lemma involutive.prod_map {f : α → α} {g : β → β} : involutive f → involutive g → involutive (map f g) := left_inverse.prod_map end function
0765a631354fa16ede076541c3b9491ba17656dc
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/seq/computation.lean
e1324f9536a29630f8fbff4b959d20c5166413a3
[ "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,987
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Coinductive formalization of unbounded computations. -/ import tactic.basic import data.stream.init import logic.relator open function 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_t α (computation α) := ⟨return⟩ -- note [use has_coe_t] /-- `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 h, c.2 h⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : computation α := ⟨stream.const none, λ n a', id⟩ instance : inhabited (computation α) := ⟨empty _⟩ /-- `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] lemma 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 ` ~ `:50 := 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 {s : computation α} {a b : α} : a ∈ s → b ∈ s → a = 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) theorem mem.left_unique : relator.left_unique ((∈) : α → computation α → Prop) := λ a s b, mem_unique /-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/ class terminates (s : computation α) : Prop := (term : ∃ a, a ∈ s) theorem terminates_iff (s : computation α) : terminates s ↔ ∃ a, a ∈ s := ⟨λ h, h.1, terminates.mk⟩ theorem terminates_of_mem {s : computation α} {a : α} (h : a ∈ s) : terminates s := ⟨⟨a, h⟩⟩ 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 { casesI h, 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 nat.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, { ext ⟨⟩; 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), ext ⟨⟩; 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 ` ~ `:50 := 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₂ := by simp only [terminates_iff, 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 (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] lemma 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 (swap R) (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] lemma 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 (swap C) (λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h) cb ca Hc b hb) end computation
929879bbf16c0014cf161db8546ba5fbbb4013cb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/examples/prop_encodable.lean
d2436fd06f034af105355094755ff159e1cadc83
[ "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
3,140
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.W.basic /-! # W types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The file `data/W.lean` shows that if `α` is an an encodable fintype and for every `a : α`, `β a` is encodable, then `W β` is encodable. As an example of how this can be used, we show that the type of propositional formulas with variables labeled from an encodable type is encodable. The strategy is to define a type of labels corresponding to the constructors. From the definition (using `sum`, `unit`, and an encodable type), Lean can infer that it is encodable. We then define a map from propositional formulas to the corresponding `Wfin` type, and show that map has a left inverse. We mark the auxiliary constructions `private`, since their only purpose is to show encodability. -/ namespace prop_encodable /-- Propositional formulas with labels from `α`. -/ inductive prop_form (α : Type*) | var : α → prop_form | not : prop_form → prop_form | and : prop_form → prop_form → prop_form | or : prop_form → prop_form → prop_form /-! The next three functions make it easier to construct functions from a small `fin`. -/ section variable {α : Type*} /-- the trivial function out of `fin 0`. -/ def mk_fn0 : fin 0 → α | ⟨_, h⟩ := absurd h dec_trivial /-- defines a function out of `fin 1` -/ def mk_fn1 (t : α) : fin 1 → α | ⟨0, _⟩ := t | ⟨n+1, h⟩ := absurd h dec_trivial /-- defines a function out of `fin 2` -/ def mk_fn2 (s t : α) : fin 2 → α | ⟨0, _⟩ := s | ⟨1, _⟩ := t | ⟨n+2, h⟩ := absurd h dec_trivial attribute [simp] mk_fn0 mk_fn1 mk_fn2 end namespace prop_form private def constructors (α : Type*) := α ⊕ unit ⊕ unit ⊕ unit local notation `cvar ` a := sum.inl a local notation `cnot` := sum.inr (sum.inl unit.star) local notation `cand` := sum.inr (sum.inr (sum.inr unit.star)) local notation `cor` := sum.inr (sum.inr (sum.inl unit.star)) @[simp] private def arity (α : Type*) : constructors α → nat | (cvar a) := 0 | cnot := 1 | cand := 2 | cor := 2 variable {α : Type*} private def f : prop_form α → W_type (λ i, fin (arity α i)) | (var a) := ⟨cvar a, mk_fn0⟩ | (not p) := ⟨cnot, mk_fn1 (f p)⟩ | (and p q) := ⟨cand, mk_fn2 (f p) (f q)⟩ | (or p q) := ⟨cor, mk_fn2 (f p) (f q)⟩ private def finv : W_type (λ i, fin (arity α i)) → prop_form α | ⟨cvar a, fn⟩ := var a | ⟨cnot, fn⟩ := not (finv (fn ⟨0, dec_trivial⟩)) | ⟨cand, fn⟩ := and (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩)) | ⟨cor, fn⟩ := or (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩)) instance [encodable α] : encodable (prop_form α) := begin haveI : encodable (constructors α), { unfold constructors, apply_instance }, exact encodable.of_left_inverse f finv (by { intro p, induction p; simp [f, finv, *] }) end end prop_form end prop_encodable
df3e1d68e018688516f63797064bcd5b97bcb628
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/conjunctive.lean
1c85ae15c1a0d577eed40327838e31706f9821f9
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
917
lean
import ..u_semiring import ..sql import ..cosette_tactics open SQL open Pred open Expr open Proj lemma CQExample0: forall Γ s1 s2 (a: SQL Γ s1) (b: SQL Γ s2) ty0 ty1 (x: Column ty0 s1) (ya: Column ty1 s1) (yb: Column ty1 s2), denoteSQL ((DISTINCT (SELECT1 (right⋅left⋅x) (FROM1 (product a b) WHERE (equal (uvariable (right⋅left⋅ya)) (uvariable (right⋅right⋅yb)))))) : SQL Γ _) = denoteSQL ((DISTINCT (SELECT1 (right⋅left⋅left⋅x) (FROM1 (product (product a a) b) WHERE (and (equal (uvariable (right⋅left⋅left⋅x)) (uvariable (right⋅left⋅right⋅x))) (equal (uvariable (right⋅left⋅left⋅ya)) (uvariable (right⋅right⋅yb))))))) : SQL Γ _ ) := begin intros, unfold_all_denotations, funext, simp, sorry -- TODO: SDP should be used here end
d6b3d50f63627759ad743fc256910b0c0f3889c6
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Meta/LevelDefEq.lean
672ceeb416975c4ee89c85dfa991d4940af26a7b
[ "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
9,670
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic import Lean.Meta.InferType namespace Lean.Meta private partial def decAux? : Level → MetaM (Option Level) | Level.zero _ => pure none | Level.param _ _ => pure none | Level.mvar mvarId _ => do let mctx ← getMCtx match mctx.getLevelAssignment? mvarId with | some u => decAux? u | none => if (← isReadOnlyLevelMVar mvarId) then pure none else let u ← mkFreshLevelMVar assignLevelMVar mvarId (mkLevelSucc u) pure u | Level.succ u _ => pure u | u => let process (u v : Level) : MetaM (Option Level) := do match (← decAux? u) with | none => pure none | some u => do match (← decAux? v) with | none => pure none | some v => pure $ mkLevelMax u v match u with | Level.max u v _ => process u v /- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/ | Level.imax u v _ => process u v | _ => unreachable! variables {m : Type → Type} [MonadLiftT MetaM m] private def decLevelImp (u : Level) : MetaM (Option Level) := do let mctx ← getMCtx match (← decAux? u) with | some v => pure $ some v | none => do modify fun s => { s with mctx := mctx } pure none def decLevel? (u : Level) : m (Option Level) := liftMetaM $ decLevelImp u def decLevel (u : Level) : m Level := liftMetaM do match (← decLevel? u) with | some u => pure u | none => throwError! "invalid universe level, {u} is not greater than 0" /- This method is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (type : Expr) : m Level := liftMetaM do let u ← getLevel type decLevel u private def strictOccursMaxAux (lvl : Level) : Level → Bool | Level.max u v _ => strictOccursMaxAux lvl u || strictOccursMaxAux lvl v | u => u != lvl && lvl.occurs u /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => strictOccursMaxAux lvl u || strictOccursMaxAux lvl v | _ => false /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff mvarId v $ mkMaxArgsDiff mvarId u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax acc l else acc | l, acc => mkLevelMax acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do let n ← mkFreshLevelMVar assignLevelMVar mvarId $ mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs } mutual private partial def solve (u v : Level) : MetaM LBool := do match u, v with | Level.mvar mvarId _, _ => if (← isReadOnlyLevelMVar mvarId) then pure LBool.undef else if !u.occurs v then assignLevelMVar u.mvarId! v pure LBool.true else if !strictOccursMax u v then solveSelfMax u.mvarId! v pure LBool.true else pure LBool.undef | Level.zero _, Level.max v₁ v₂ _ => Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂) | Level.zero _, Level.imax _ v₂ _ => Bool.toLBool <$> isLevelDefEqAux levelZero v₂ | Level.succ u _, v => match (← Meta.decLevel? v) with | some v => Bool.toLBool <$> isLevelDefEqAux u v | none => pure LBool.undef | _, _ => pure LBool.undef partial def isLevelDefEqAux : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => do if lhs == rhs then pure true else trace[Meta.isLevelDefEq.step]! "{lhs} =?= {rhs}" let lhs' ← instantiateLevelMVars lhs let lhs' := lhs'.normalize let rhs' ← instantiateLevelMVars rhs let rhs' := rhs'.normalize if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else let r ← solve lhs rhs; if r != LBool.undef then pure $ r == LBool.true else let r ← solve rhs lhs; if r != LBool.undef then pure $ r == LBool.true else do let mctx ← getMCtx if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then let ctx ← read if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace[Meta.isLevelDefEq.stuck]! "{lhs} =?= {rhs}" Meta.throwIsDefEqStuck else pure false else postponeIsLevelDefEq lhs rhs; pure true end def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => pure true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => pure false private def getNumPostponed : MetaM Nat := do pure (← getPostponed).size open Std (PersistentArray) private def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} pure ps private def processPostponedStep : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step do let ps ← getResetPostponed for p in ps do unless (← isLevelDefEqAux p.lhs p.rhs) do return false return true private partial def processPostponed (mayPostpone : Bool := true) : MetaM Bool := do if (← getNumPostponed) == 0 then pure true else traceCtx `Meta.isLevelDefEq.postponed do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then pure true else trace[Meta.isLevelDefEq.postponed]! "processing #{numPostponed} postponed is-def-eq level constraints" if !(← processPostponedStep) then pure false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then pure true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed]! "no progress solving pending is-def-eq level constraints" pure mayPostpone loop private def restore (env : Environment) (mctx : MetavarContext) (postponed : PersistentArray PostponedEntry) : MetaM Unit := do setEnv env setMCtx mctx setPostponed postponed /-- `commitWhen x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. Remark: postponed universe level constraints must be solved before returning. Otherwise, we don't know whether `x` really succeeded. -/ @[specialize] def commitWhen (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let env ← getEnv let mctx ← getMCtx let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then pure true else restore env mctx postponed pure false else restore env mctx postponed pure false catch ex => restore env mctx postponed throw ex private def postponedToMessageData (ps : PersistentArray PostponedEntry) : MessageData := do let mut r := MessageData.nil for p in ps do r := msg!"{r}\n{p.lhs} =?= {p.rhs}" pure r @[specialize] def withoutPostponingUniverseConstraintsImp {α} (x : MetaM α) : MetaM α := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false)) do throwError! "stuck at solving universe constraints{MessageData.nestD (postponedToMessageData (← getPostponed))}" setPostponed postponed pure a catch ex => setPostponed postponed throw ex @[inline] def withoutPostponingUniverseConstraints {α m} [MonadControlT MetaM m] [Monad m] : m α → m α := mapMetaM $ withoutPostponingUniverseConstraintsImp def isLevelDefEq (u v : Level) : m Bool := liftMetaM do traceCtx `Meta.isLevelDefEq do let b ← commitWhen (mayPostpone := true) $ Meta.isLevelDefEqAux u v trace[Meta.isLevelDefEq]! "{u} =?= {v} ... {if b then "success" else "failure"}" pure b def isExprDefEq (t s : Expr) : m Bool := liftMetaM do traceCtx `Meta.isDefEq $ do let b ← commitWhen (mayPostpone := true) $ Meta.isExprDefEqAux t s trace[Meta.isDefEq]! "{t} =?= {s} ... {if b then "success" else "failure"}" pure b abbrev isDefEq (t s : Expr) : m Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : m Bool := liftMetaM do try isExprDefEq a b catch _ => pure false abbrev isDefEqGuarded (t s : Expr) : m Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : m Bool := liftMetaM do approxDefEq $ isDefEq t s builtin_initialize registerTraceClass `Meta.isLevelDefEq registerTraceClass `Meta.isLevelDefEq.step registerTraceClass `Meta.isLevelDefEq.postponed end Lean.Meta
f433daf05da30286e195ed6269c1dc4eef9b3cd5
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Parser/Command.lean
41f0058b748f36196e95f7edefd797ea699f7c8f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
14,603
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term import Lean.Parser.Do namespace Lean namespace Parser /-- Syntax quotation for terms. -/ @[builtinTermParser] def Term.quot := leading_parser "`(" >> incQuotDepth termParser >> ")" @[builtinTermParser] def Term.precheckedQuot := leading_parser "`" >> Term.quot namespace Command /-- Syntax quotation for (sequences of) commands. The identical syntax for term quotations takes priority, so ambiguous quotations like `` `($x $y) `` will be parsed as an application, not two commands. Use `` `($x:command $y:command) `` instead. Multiple commands will be put in a `` `null `` node, but a single command will not (so that you can directly match against a quotation in a command kind's elaborator). -/ @[builtinTermParser low] def quot := leading_parser "`(" >> incQuotDepth (many1Unbox commandParser) >> ")" /-- A mutual block may be broken in different cliques, we identify them using an `ident` (an element of the clique) We provide two kinds of hints to the termination checker: 1- A wellfounded relation (`p` is `termParser`) 2- A tactic for proving the recursive applications are "decreasing" (`p` is `tacticSeq`) -/ def terminationHintMany (p : Parser) := leading_parser atomic (lookahead (ident >> " => ")) >> many1Indent (group (ppLine >> ident >> " => " >> p >> optional ";")) def terminationHint1 (p : Parser) := leading_parser p def terminationHint (p : Parser) := terminationHintMany p <|> terminationHint1 p def terminationByCore := leading_parser "termination_by' " >> terminationHint termParser def decreasingBy := leading_parser "decreasing_by " >> terminationHint Tactic.tacticSeq def terminationByElement := leading_parser ppLine >> (ident <|> Term.hole) >> many (ident <|> Term.hole) >> " => " >> termParser >> optional ";" def terminationBy := leading_parser ppLine >> "termination_by " >> many1Indent terminationByElement def terminationSuffix := optional (terminationBy <|> terminationByCore) >> optional decreasingBy @[builtinCommandParser] def moduleDoc := leading_parser ppDedent $ "/-!" >> commentBody >> ppLine def namedPrio := leading_parser (atomic ("(" >> nonReservedSymbol "priority") >> " := " >> priorityParser >> ")") def optNamedPrio := optional (ppSpace >> namedPrio) def «private» := leading_parser "private " def «protected» := leading_parser "protected " def visibility := «private» <|> «protected» def «noncomputable» := leading_parser "noncomputable " def «unsafe» := leading_parser "unsafe " def «partial» := leading_parser "partial " def «nonrec» := leading_parser "nonrec " def declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional («partial» <|> «nonrec») def declId := leading_parser ident >> optional (".{" >> sepBy1 ident ", " >> "}") def declSig := leading_parser many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.typeSpec def optDeclSig := leading_parser many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.optType def declValSimple := leading_parser " :=" >> ppHardLineUnlessUngrouped >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def whereStructField := leading_parser Term.letDecl def whereStructInst := leading_parser " where" >> sepBy1Indent (ppGroup whereStructField) "; " (allowTrailingSep := true) >> optional Term.whereDecls /- Remark: we should not use `Term.whereDecls` at `declVal` because `Term.whereDecls` is defined using `Term.letRecDecl` which may contain attributes. Issue #753 showns an example that fails to be parsed when we used `Term.whereDecls`. -/ def declVal := withAntiquot (mkAntiquot "declVal" `Lean.Parser.Command.declVal (isPseudoKind := true)) <| declValSimple <|> declValEqns <|> whereStructInst def «abbrev» := leading_parser "abbrev " >> declId >> ppIndent optDeclSig >> declVal def optDefDeriving := optional (atomic ("deriving " >> notSymbol "instance") >> sepBy1 ident ", ") def «def» := leading_parser "def " >> declId >> ppIndent optDeclSig >> declVal >> optDefDeriving >> terminationSuffix def «theorem» := leading_parser "theorem " >> declId >> ppIndent declSig >> declVal >> terminationSuffix def «opaque» := leading_parser "opaque " >> declId >> ppIndent declSig >> optional declValSimple /- As `declSig` starts with a space, "instance" does not need a trailing space if we put `ppSpace` in the optional fragments. -/ def «instance» := leading_parser Term.attrKind >> "instance" >> optNamedPrio >> optional (ppSpace >> declId) >> ppIndent declSig >> declVal >> terminationSuffix def «axiom» := leading_parser "axiom " >> declId >> ppIndent declSig /- As `declSig` starts with a space, "example" does not need a trailing space. -/ def «example» := leading_parser "example" >> ppIndent declSig >> declVal def ctor := leading_parser "\n| " >> ppIndent (declModifiers true >> rawIdent >> optDeclSig) def derivingClasses := sepBy1 (group (ident >> optional (" with " >> Term.structInst))) ", " def optDeriving := leading_parser optional (ppLine >> atomic ("deriving " >> notSymbol "instance") >> derivingClasses) def computedField := leading_parser declModifiers true >> ident >> " : " >> termParser >> Term.matchAlts def computedFields := leading_parser "with" >> manyIndent (ppLine >> ppGroup computedField) /-- In Lean, every concrete type other than the universes and every type constructor other than dependent arrows is an instance of a general family of type constructions known as inductive types. It is remarkable that it is possible to construct a substantial edifice of mathematics based on nothing more than the type universes, dependent arrow types, and inductive types; everything else follows from those. Intuitively, an inductive type is built up from a specified list of constructor. For example, `List α` is the list of elements of type `α`, and is defined as follows ``` inductive List (α : Type u) where | nil | cons (head : α) (tail : List α) ``` A list of elements of type `α` is either the empty list, `nil`, or an element `head : α` followed by a list `tail : List α`. For more information about [inductive types](https://leanprover.github.io/theorem_proving_in_lean4/inductive_types.html). -/ def «inductive» := leading_parser "inductive " >> declId >> optDeclSig >> optional (symbol " :=" <|> " where") >> many ctor >> optional (ppDedent ppLine >> computedFields) >> optDeriving def classInductive := leading_parser atomic (group (symbol "class " >> "inductive ")) >> declId >> ppIndent optDeclSig >> optional (symbol " :=" <|> " where") >> many ctor >> optDeriving def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> ppIndent optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser manyIndent (ppLine >> checkColGe >> ppGroup (structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder)) def structCtor := leading_parser atomic (declModifiers true >> ident >> " :: ") def structureTk := leading_parser "structure " def classTk := leading_parser "class " def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def «structure» := leading_parser (structureTk <|> classTk) >> declId >> many (ppSpace >> Term.bracketedBinder) >> optional «extends» >> Term.optType >> optional ((symbol " := " <|> " where ") >> optional structCtor >> structFields) >> optDeriving @[builtinCommandParser] def declaration := leading_parser declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «opaque» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure») @[builtinCommandParser] def «deriving» := leading_parser "deriving " >> "instance " >> derivingClasses >> " for " >> sepBy1 ident ", " @[builtinCommandParser] def noncomputableSection := leading_parser "noncomputable " >> "section " >> optional ident @[builtinCommandParser] def «section» := leading_parser "section " >> optional ident @[builtinCommandParser] def «namespace» := leading_parser "namespace " >> ident @[builtinCommandParser] def «end» := leading_parser "end " >> optional ident @[builtinCommandParser] def «variable» := leading_parser "variable" >> many1 (ppSpace >> Term.bracketedBinder) @[builtinCommandParser] def «universe» := leading_parser "universe " >> many1 ident @[builtinCommandParser] def check := leading_parser "#check " >> termParser @[builtinCommandParser] def check_failure := leading_parser "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check @[builtinCommandParser] def reduce := leading_parser "#reduce " >> termParser @[builtinCommandParser] def eval := leading_parser "#eval " >> termParser @[builtinCommandParser] def synth := leading_parser "#synth " >> termParser @[builtinCommandParser] def exit := leading_parser "#exit" @[builtinCommandParser] def print := leading_parser "#print " >> (ident <|> strLit) @[builtinCommandParser] def printAxioms := leading_parser "#print " >> nonReservedSymbol "axioms " >> ident @[builtinCommandParser] def «resolve_name» := leading_parser "#resolve_name " >> ident @[builtinCommandParser] def «init_quot» := leading_parser "init_quot" def optionValue := nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit @[builtinCommandParser] def «set_option» := leading_parser "set_option " >> ident >> ppSpace >> optionValue def eraseAttr := leading_parser "-" >> rawIdent @[builtinCommandParser] def «attribute» := leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "] " >> many1 ident @[builtinCommandParser] def «export» := leading_parser "export " >> ident >> " (" >> many1 ident >> ")" def openHiding := leading_parser atomic (ident >> "hiding") >> many1 (checkColGt >> ident) def openRenamingItem := leading_parser ident >> unicodeSymbol " → " " -> " >> checkColGt >> ident def openRenaming := leading_parser atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", " def openOnly := leading_parser atomic (ident >> " (") >> many1 ident >> ")" def openSimple := leading_parser many1 (checkColGt >> ident) def openScoped := leading_parser "scoped " >> many1 (checkColGt >> ident) def openDecl := withAntiquot (mkAntiquot "openDecl" `Lean.Parser.Command.openDecl (isPseudoKind := true)) <| openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped @[builtinCommandParser] def «open» := leading_parser withPosition ("open " >> openDecl) @[builtinCommandParser] def «mutual» := leading_parser "mutual " >> many1 (ppLine >> notSymbol "end" >> commandParser) >> ppDedent (ppLine >> "end") >> terminationSuffix def initializeKeyword := leading_parser "initialize " <|> "builtin_initialize " @[builtinCommandParser] def «initialize» := leading_parser declModifiers false >> initializeKeyword >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «in» := trailing_parser withOpen (" in " >> commandParser) @[builtinCommandParser] def addDocString := leading_parser docComment >> "add_decl_doc" >> ident /-- This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`. It is meant for bootstrapping purposes only. -/ @[builtinCommandParser] def genInjectiveTheorems := leading_parser "gen_injective_theorems% " >> ident @[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false @[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true builtin_initialize register_parser_alias (kind := ``declModifiers) "declModifiers" declModifiersF register_parser_alias (kind := ``declModifiers) "nestedDeclModifiers" declModifiersT register_parser_alias declId register_parser_alias declSig register_parser_alias declVal register_parser_alias optDeclSig register_parser_alias openDecl register_parser_alias docComment end Command namespace Term /-- `open Foo in e` is like `open Foo` but scoped to a single term. It makes the given namespaces available in the term `e`. -/ @[builtinTermParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> withOpenDecl (" in " >> termParser) /-- `set_option opt val in e` is like `set_option opt val` but scoped to a single term. It sets the option `opt` to the value `val` in the term `e`. -/ @[builtinTermParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> termParser end Term namespace Tactic /-- `open Foo in tacs` (the tactic) acts like `open Foo` at command level, but it opens a namespace only within the tactics `tacs`. -/ @[builtinTacticParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> withOpenDecl (" in " >> tacticSeq) /-- `set_option opt val in tacs` (the tactic) acts like `set_option opt val` at command level, but it sets the option only within the tactics `tacs`. -/ @[builtinTacticParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> tacticSeq end Tactic end Parser end Lean
7c394153e5b978e424a1c9b195b06c83a25c0829
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/notation2.lean
ba057e6d8fc7d5448bb7988c43ce7ad55a4da37a
[ "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
265
lean
-- inductive List (T : Type) : Type | nil {} : List | cons : T → List → List open List notation h :: t := cons h t notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l infixr `::` := cons check (1:num) :: 2 :: nil check (1:num) :: 2 :: 3 :: 4 :: 5 :: nil
f5402770e9a784c06e72b68291049629301200be
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/dedekind_domain.lean
2c5c29a90d349519c5278d60c15c91c752f98126
[ "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
5,708
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.discrete_valuation_ring import ring_theory.fractional_ideal import ring_theory.ideal.over /-! # Dedekind domains This file defines the notion of a Dedekind domain (or Dedekind ring), giving three equivalent definitions (TODO: and shows that they are equivalent). ## Main definitions - `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is not a field, Noetherian, integrally closed in its field of fractions and has Krull dimension exactly one. `is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions. - `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that is not a field, Noetherian, and the localization at every nonzero prime ideal is a discrete valuation ring. - `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain that is not a field, and every nonzero fractional ideal is invertible. - `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of fractions. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [integral_domain A] [field K] /-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/ def ring.dimension_le_one : Prop := ∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal open ideal ring namespace ring lemma dimension_le_one.principal_ideal_ring [is_principal_ideal_ring A] : dimension_le_one A := λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero } lemma dimension_le_one.integral_closure [nontrivial R] [algebra R A] (h : dimension_le_one R) : dimension_le_one (integral_closure R A) := begin intros p ne_bot prime, haveI := prime, refine integral_closure.is_maximal_of_is_maximal_comap p (h _ (integral_closure.comap_ne_bot ne_bot) _), apply is_prime.comap end end ring /-- A Dedekind domain is an integral domain that is Noetherian, integrally closed, and has Krull dimension exactly one (`not_is_field` and `dimension_le_one`). The integral closure condition is independent of the choice of field of fractions: use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`. This is the default implementation, but there are equivalent definitions, `is_dedekind_domain_dvr` and `is_dedekind_domain_inv`. TODO: Prove that these are actually equivalent definitions. -/ class is_dedekind_domain : Prop := (not_is_field : ¬ is_field A) (is_noetherian_ring : is_noetherian_ring A) (dimension_le_one : dimension_le_one A) (is_integrally_closed : integral_closure A (fraction_ring A) = ⊥) /-- An integral domain is a Dedekind domain iff and only if it is not a field, is Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field. In particular, this definition does not depend on the choice of this fraction field. -/ lemma is_dedekind_domain_iff (f : fraction_map A K) : is_dedekind_domain A ↔ (¬ is_field A) ∧ is_noetherian_ring A ∧ dimension_le_one A ∧ integral_closure A f.codomain = ⊥ := ⟨λ ⟨hf, hr, hd, hi⟩, ⟨hf, hr, hd, by rw [←integral_closure_map_alg_equiv (fraction_ring.alg_equiv_of_quotient f), hi, algebra.map_bot]⟩, λ ⟨hf, hr, hd, hi⟩, ⟨hf, hr, hd, by rw [←integral_closure_map_alg_equiv (fraction_ring.alg_equiv_of_quotient f).symm, hi, algebra.map_bot]⟩⟩ /-- A Dedekind domain is an integral domain that is not a field, is Noetherian, and the localization at every nonzero prime is a discrete valuation ring. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_dvr : Prop := (not_is_field : ¬ is_field A) (is_noetherian_ring : is_noetherian_ring A) (is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime → discrete_valuation_ring (localization.at_prime P)) /-- A Dedekind domain is an integral domain that is not a field such that every fractional ideal has an inverse. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_inv : Prop := (not_is_field : ¬ is_field A) (mul_inv_cancel : ∀ I ≠ (⊥ : fractional_ideal (fraction_ring.of A)), I * I⁻¹ = 1) section open ring.fractional_ideal lemma is_dedekind_domain_inv_iff (f : fraction_map A K) : is_dedekind_domain_inv A ↔ (¬ is_field A) ∧ (∀ I ≠ (⊥ : fractional_ideal f), I * I⁻¹ = 1) := begin split; rintros ⟨hf, hi⟩; use hf; intros I hI, { have := hi (map (fraction_ring.alg_equiv_of_quotient f).symm.to_alg_hom I) (map_ne_zero _ hI), erw [← map_inv, ← fractional_ideal.map_mul] at this, convert congr_arg (map (fraction_ring.alg_equiv_of_quotient f).to_alg_hom) this; simp only [alg_equiv.to_alg_hom_eq_coe, map_symm_map, map_one] }, { have := hi (map (fraction_ring.alg_equiv_of_quotient f).to_alg_hom I) (map_ne_zero _ hI), erw [← map_inv, ← fractional_ideal.map_mul] at this, convert congr_arg (map (fraction_ring.alg_equiv_of_quotient f).symm.to_alg_hom) this; simp only [alg_equiv.to_alg_hom_eq_coe, map_map_symm, map_one] } end end
652ce4a3ef9ac0738eebb8c93564054c76e40772
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/prod.lean
8915b85a9de0dad9b9c281c4bc95a3359c03d2c6
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,643
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad -/ prelude import init.logic universes u v section variables {α : Type u} {β : Type v} @[simp] lemma prod.mk.eta : ∀{p : α × β}, (p.1, p.2) = p | (a, b) := rfl instance [inhabited α] [inhabited β] : inhabited (prod α β) := ⟨(default α, default β)⟩ instance [h₁ : decidable_eq α] [h₂ : decidable_eq β] : decidable_eq (α × β) | (a, b) (a', b') := match (h₁ a a') with | (is_true e₁) := match (h₂ b b') with | (is_true e₂) := is_true (eq.rec_on e₁ (eq.rec_on e₂ rfl)) | (is_false n₂) := is_false (assume h, prod.no_confusion h (λ e₁' e₂', absurd e₂' n₂)) end | (is_false n₁) := is_false (assume h, prod.no_confusion h (λ e₁' e₂', absurd e₁' n₁)) end instance [has_lt α] [has_lt β] : has_lt (α × β) := ⟨λ s t, s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)⟩ instance prod_has_decidable_lt [has_lt α] [has_lt β] [decidable_eq α] [decidable_eq β] [decidable_rel ((<) : α → α → Prop)] [decidable_rel ((<) : β → β → Prop)] : Π s t : α × β, decidable (s < t) := λ t s, or.decidable lemma prod.lt_def [has_lt α] [has_lt β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl end def {u₁ u₂ v₁ v₂} prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) (x : α₁ × β₁) : α₂ × β₂ := (f x.1, g x.2)
231545b258123bdbf624d06bbae2bca431f2ca4f
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.30.lean
40d9ee59a044bbe0445a47e7e5688fc481e6aa4f
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
1,353
lean
import standard import data.nat open nat decidable definition ball (n : nat) (P : nat → Prop) : Prop := ∀ x, x < n → P x definition ball_zero (P : nat → Prop) : ball zero P := λ x Hlt, absurd Hlt !not_lt_zero variables {n : nat} {P : nat → Prop} definition ball_of_ball_succ (H : ball (succ n) P) : ball n P := λ x Hlt, H x (lt.step Hlt) definition ball_succ_of_ball (H₁ : ball n P) (H₂ : P n) : ball (succ n) P := λ (x : nat) (Hlt : x < succ n), or.elim (eq_or_lt_of_le (le_of_lt_succ Hlt)) (λ he : x = n, eq.rec_on (eq.rec_on he rfl) H₂) (λ hlt : x < n, H₁ x hlt) definition not_ball_of_not (H₁ : ¬ P n) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (H n (lt.base n)) H₁ definition not_ball_succ_of_not_ball (H₁ : ¬ ball n P) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (ball_of_ball_succ H) H₁ definition dec_ball [instance] (H : decidable_pred P) : Π (n : nat), decidable (ball n P) | dec_ball 0 := inl (ball_zero P) | dec_ball (a+1) := match dec_ball a with | inl iH := match H a with | inl Pa := inl (ball_succ_of_ball iH Pa) | inr nPa := inr (not_ball_of_not nPa) end | inr niH := inr (not_ball_succ_of_not_ball niH) end -- BEGIN example : ∀ x : nat, x ≤ 4 → x ≠ 6 := dec_trivial example : ¬ ∀ x, x ≤ 5 → ∀ y, y < x → y * y ≠ x := dec_trivial -- END