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
88527c12a4b34c87880154eb9ecfc6ffd484bd44
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/metric_space/gromov_hausdorff_realized.lean
8e7271bd5b0a4edd3724d2bdea38d82b1543fbb6
[ "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
27,464
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance import topology.continuous_function.bounded /-! # The Gromov-Hausdorff distance is realized In this file, we construct of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces. Given two nonempty compact metric spaces `X` and `Y`, we define `optimal_GH_coupling X Y` as a compact metric space, together with two isometric embeddings `optimal_GH_injl` and `optimal_GH_injr` respectively of `X` and `Y` into `optimal_GH_coupling X Y`. The main property of the optimal coupling is that the Hausdorff distance between `X` and `Y` in `optimal_GH_coupling X Y` is smaller than the corresponding distance in any other coupling. We do not prove completely this fact in this file, but we show a good enough approximation of this fact in `Hausdorff_dist_optimal_le_HD`, that will suffice to obtain the full statement once the Gromov-Hausdorff distance is properly defined, in `Hausdorff_dist_optimal`. The key point in the construction is that the set of possible distances coming from isometric embeddings of `X` and `Y` in metric spaces is a set of equicontinuous functions. By Arzela-Ascoli, it is compact, and one can find such a distance which is minimal. This distance defines a premetric space structure on `X ⊕ Y`. The corresponding metric quotient is `optimal_GH_coupling X Y`. -/ noncomputable theory open_locale classical topological_space nnreal universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union `X ⊕ Y` of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] @[reducible] private def prod_space_fun : Type* := ((X ⊕ Y) × (X ⊕ Y)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((X ⊕ Y) × (X ⊕ Y)) ℝ private def max_var : ℝ≥0 := 2 * ⟨diam (univ : set X), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set Y), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var X Y := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on `X ⊕ Y` that are candidates distances to realize the minimum of the Hausdorff distances between `X` and `Y` in a coupling -/ def candidates : set (prod_space_fun X Y) := {f | (((((∀ x y : X, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀ x y : Y, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀ x y, f (x, y) = f (y, x))) ∧ (∀ x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀ x, f (x, x) = 0)) ∧ (∀ x y, f (x, y) ≤ max_var X Y) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb X Y) := {f : Cb X Y | f.to_fun ∈ candidates X Y} end definitions --section section constructions variables {X : Type u} {Y : Type v} [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] {f : prod_space_fun X Y} {x y z t : X ⊕ Y} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var X Y := calc dist x y ≤ diam (univ : set (X ⊕ Y)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set X) ∪ inr '' (univ : set Y)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set X)) + dist (inl (default X)) (inr (default Y)) + diam (inr '' (univ : set Y)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set X) + (dist (default X) (default X) + 1 + dist (default Y) (default Y)) + diam (univ : set Y) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set X) + 1 + 1 * diam (univ : set Y) : by simp ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates X Y) : f (x, y) = f (y, x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates X Y) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates X Y) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates X Y) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates X Y) (x y: X) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates X Y) (x y : Y) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates X Y) : f (x, y) ≤ max_var X Y := fA.2 x y /-- candidates are bounded by `max_var X Y` -/ private lemma candidates_dist_bound (fA : f ∈ candidates X Y) : ∀ {x y : X ⊕ Y}, f (x, y) ≤ max_var X Y * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq X Y, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var X Y * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var X Y : candidates_le_max_var fA ... = max_var X Y * 1 : by simp ... ≤ max_var X Y * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var X Y : candidates_le_max_var fA ... = max_var X Y * 1 : by simp ... ≤ max_var X Y * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq X Y, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var X Y * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates X Y) : f (x, y) - f (z, t) ≤ 2 * max_var X Y * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var X Y * dist x z + max_var X Y * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var X Y * max (dist x z) (dist t y) + max_var X Y * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var X Y)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var X Y)), end ... = 2 * max_var X Y * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var X Y * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates X Y) : lipschitz_with (2 * max_var X Y) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : Cb X Y := bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩ lemma candidates_b_of_candidates_mem (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : candidates_b_of_candidates f fA ∈ candidates_b X Y := fA /-- The distance on `X ⊕ Y` is a candidate -/ private lemma dist_mem_candidates : (λp : (X ⊕ Y) × (X ⊕ Y), dist p.1 p.2) ∈ candidates X Y := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end /-- The distance on `X ⊕ Y` as a candidate -/ def candidates_b_dist (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [inhabited X] [metric_space Y] [compact_space Y] [inhabited Y] : Cb X Y := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist X Y ∈ candidates_b X Y := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b X Y).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/ private lemma closed_candidates_b : is_closed (candidates_b X Y) := begin have I1 : ∀ x y, is_closed {f : Cb X Y | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀ x y, is_closed {f : Cb X Y | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀ x y, is_closed {f : Cb X Y | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀ x y z, is_closed {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀ x, is_closed {f : Cb X Y | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀ x y, is_closed {f : Cb X Y | f (x, y) ≤ max_var X Y} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b X Y = (⋂x y, {f : Cb X Y | f ((@inl X Y x), (@inl X Y y)) = dist x y}) ∩ (⋂x y, {f : Cb X Y | f ((@inr X Y x), (@inr X Y y)) = dist x y}) ∩ (⋂x y, {f : Cb X Y | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb X Y | f (x, x) = 0}) ∩ (⋂x y, {f : Cb X Y | f (x, y) ≤ max_var X Y}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed.inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows. -/ private lemma compact_candidates_b : is_compact (candidates_b X Y) := begin refine arzela_ascoli₂ (Icc 0 (max_var X Y)) is_compact_Icc (candidates_b X Y) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var X Y * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var X Y : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var X Y * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb X Y) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on `ℝ`, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb X Y} (C : ℝ) {x : X} : bdd_below (range (λ (y : Y), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb X Y) (C : ℝ) : bdd_above (range (λ (x : X), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default Y)) + C : cinfi_le (HD_below_aux1 C) (default Y) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb X Y} (C : ℝ) {y : Y} : bdd_below (range (λ (x : X), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb X Y) (C : ℝ) : bdd_above (range (λ (y : Y), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default X), inr y) + C : cinfi_le (HD_below_aux2 C) (default X) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on `HD (dist)`. This means that when looking for minimizers it will be sufficient to look for functions with `HD(f)` bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist X Y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist X Y (inl x, inr y)) ≤ candidates_b_dist X Y (inl x, inr (default Y)) := cinfi_le (by simpa using HD_below_aux1 0) (default Y), have B : dist (inl x) (inr (default Y)) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc dist (inl x) (inr (default Y)) = dist x (default X) + 1 + dist (default Y) (default Y) : rfl ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist X Y (inl x, inr y)) ≤ candidates_b_dist X Y (inl (default X), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default X), have B : dist (inl (default X)) (inr y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc dist (inl (default X)) (inr y) = dist (default X) (default X) + 1 + dist (default Y) y : rfl ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb X Y) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀ x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : Y), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb X Y) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀ y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:X, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb X Y) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb X Y → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃ f ∈ candidates_b X Y, ∀ g ∈ candidates_b X Y, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb X Y := classical.some (exists_minimizer X Y) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist X Y ∈ candidates_b X Y := by cases (classical.some_spec (exists_minimizer X Y)); assumption private lemma HD_optimal_GH_dist_le (g : Cb X Y) (hg : g ∈ candidates_b X Y) : HD (optimal_GH_dist X Y) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer X Y) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on `X ⊕ Y`, on which the predistance is given by the candidate. Then, we will identify points at `0` predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : pseudo_metric_space (X ⊕ Y) := { dist := λp q, optimal_GH_dist X Y (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b X Y), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b X Y), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b X Y) } local attribute [instance] premetric_optimal_GH_dist pseudo_metric.dist_setoid /-- A metric space which realizes the optimal coupling between `X` and `Y` -/ @[derive metric_space, nolint has_inhabited_instance] definition optimal_GH_coupling : Type* := pseudo_metric_quot (X ⊕ Y) /-- Injection of `X` in the optimal coupling between `X` and `Y` -/ def optimal_GH_injl (x : X) : optimal_GH_coupling X Y := ⟦inl x⟧ /-- The injection of `X` in the optimal coupling between `X` and `Y` is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl X Y) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b X Y) _ _, end /-- Injection of `Y` in the optimal coupling between `X` and `Y` -/ def optimal_GH_injr (y : Y) : optimal_GH_coupling X Y := ⟦inr y⟧ /-- The injection of `Y` in the optimal coupling between `X` and `Y` is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr X Y) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b X Y) _ _, end /-- The optimal coupling between two compact spaces `X` and `Y` is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling X Y) := ⟨begin have : (univ : set (optimal_GH_coupling X Y)) = (optimal_GH_injl X Y '' univ) ∪ (optimal_GH_injr X Y '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl X Y x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr X Y x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl X Y).continuous).union (compact_univ.image (isometry_optimal_GH_injr X Y).continuous) end⟩ /-- For any candidate `f`, `HD(f)` is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b X Y) : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le X Y f h), have A : ∀ x ∈ range (optimal_GH_injl X Y), ∃ y ∈ range (optimal_GH_injr X Y), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr X Y z', mem_range_self _], have : (optimal_GH_dist X Y) (inl z, inr z') ≤ r, by { rw hz', exact le_of_lt hr' }, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty X with ⟨xX, _⟩, have : optimal_GH_injl X Y xX ∈ range (optimal_GH_injl X Y) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl X Y z', mem_range_self _], have : (optimal_GH_dist X Y) (inl z', inr z) ≤ r, by { rw hz', exact le_of_lt hr' }, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
92d0b3b7c561918df3521948e3b0a642348ed08f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/closed.lean
a2cf4f46df1f3fb02d715d5a42917980b1ad0630
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
12,252
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.sheaf_of_types import order.closure /-! # Closed sieves > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A natural closure operator on sieves is a closure operator on `sieve X` for each `X` which commutes with pullback. We show that a Grothendieck topology `J` induces a natural closure operator, and define what the closed sieves are. The collection of `J`-closed sieves forms a presheaf which is a sheaf for `J`, and further this presheaf can be used to determine the Grothendieck topology from the sheaf predicate. Finally we show that a natural closure operator on sieves induces a Grothendieck topology, and hence that natural closure operators are in bijection with Grothendieck topologies. ## Main definitions * `category_theory.grothendieck_topology.close`: Sends a sieve `S` on `X` to the set of arrows which it covers. This has all the usual properties of a closure operator, as well as commuting with pullback. * `category_theory.grothendieck_topology.closure_operator`: The bundled `closure_operator` given by `category_theory.grothendieck_topology.close`. * `category_theory.grothendieck_topology.closed`: A sieve `S` on `X` is closed for the topology `J` if it contains every arrow it covers. * `category_theory.functor.closed_sieves`: The presheaf sending `X` to the collection of `J`-closed sieves on `X`. This is additionally shown to be a sheaf for `J`, and if this is a sheaf for a different topology `J'`, then `J' ≤ J`. * `category_theory.grothendieck_topology.topology_of_closure_operator`: A closure operator on the set of sieves on every object which commutes with pullback additionally induces a Grothendieck topology, giving a bijection with `category_theory.grothendieck_topology.closure_operator`. ## Tags closed sieve, closure, Grothendieck topology ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] -/ universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables (J₁ J₂ : grothendieck_topology C) namespace grothendieck_topology /-- The `J`-closure of a sieve is the collection of arrows which it covers. -/ @[simps] def close {X : C} (S : sieve X) : sieve X := { arrows := λ Y f, J₁.covers S f, downward_closed' := λ Y Z f hS, J₁.arrow_stable _ _ hS } /-- Any sieve is smaller than its closure. -/ lemma le_close {X : C} (S : sieve X) : S ≤ J₁.close S := λ Y g hg, J₁.covering_of_eq_top (S.pullback_eq_top_of_mem hg) /-- A sieve is closed for the Grothendieck topology if it contains every arrow it covers. In the case of the usual topology on a topological space, this means that the open cover contains every open set which it covers. Note this has no relation to a closed subset of a topological space. -/ def is_closed {X : C} (S : sieve X) : Prop := ∀ ⦃Y : C⦄ (f : Y ⟶ X), J₁.covers S f → S f /-- If `S` is `J₁`-closed, then `S` covers exactly the arrows it contains. -/ lemma covers_iff_mem_of_closed {X : C} {S : sieve X} (h : J₁.is_closed S) {Y : C} (f : Y ⟶ X) : J₁.covers S f ↔ S f := ⟨h _, J₁.arrow_max _ _⟩ /-- Being `J`-closed is stable under pullback. -/ lemma is_closed_pullback {X Y : C} (f : Y ⟶ X) (S : sieve X) : J₁.is_closed S → J₁.is_closed (S.pullback f) := λ hS Z g hg, hS (g ≫ f) (by rwa [J₁.covers_iff, sieve.pullback_comp]) /-- The closure of a sieve `S` is the largest closed sieve which contains `S` (justifying the name "closure"). -/ lemma le_close_of_is_closed {X : C} {S T : sieve X} (h : S ≤ T) (hT : J₁.is_closed T) : J₁.close S ≤ T := λ Y f hf, hT _ (J₁.superset_covering (sieve.pullback_monotone f h) hf) /-- The closure of a sieve is closed. -/ lemma close_is_closed {X : C} (S : sieve X) : J₁.is_closed (J₁.close S) := λ Y g hg, J₁.arrow_trans g _ S hg (λ Z h hS, hS) /-- The sieve `S` is closed iff its closure is equal to itself. -/ lemma is_closed_iff_close_eq_self {X : C} (S : sieve X) : J₁.is_closed S ↔ J₁.close S = S := begin split, { intro h, apply le_antisymm, { intros Y f hf, rw ← J₁.covers_iff_mem_of_closed h, apply hf }, { apply J₁.le_close } }, { intro e, rw ← e, apply J₁.close_is_closed } end lemma close_eq_self_of_is_closed {X : C} {S : sieve X} (hS : J₁.is_closed S) : J₁.close S = S := (J₁.is_closed_iff_close_eq_self S).1 hS /-- Closing under `J` is stable under pullback. -/ lemma pullback_close {X Y : C} (f : Y ⟶ X) (S : sieve X) : J₁.close (S.pullback f) = (J₁.close S).pullback f := begin apply le_antisymm, { refine J₁.le_close_of_is_closed (sieve.pullback_monotone _ (J₁.le_close S)) _, apply J₁.is_closed_pullback _ _ (J₁.close_is_closed _) }, { intros Z g hg, change _ ∈ J₁ _, rw ← sieve.pullback_comp, apply hg } end @[mono] lemma monotone_close {X : C} : monotone (J₁.close : sieve X → sieve X) := λ S₁ S₂ h, J₁.le_close_of_is_closed (h.trans (J₁.le_close _)) (J₁.close_is_closed S₂) @[simp] lemma close_close {X : C} (S : sieve X) : J₁.close (J₁.close S) = J₁.close S := le_antisymm (J₁.le_close_of_is_closed le_rfl (J₁.close_is_closed S)) (J₁.monotone_close (J₁.le_close _)) /-- The sieve `S` is in the topology iff its closure is the maximal sieve. This shows that the closure operator determines the topology. -/ lemma close_eq_top_iff_mem {X : C} (S : sieve X) : J₁.close S = ⊤ ↔ S ∈ J₁ X := begin split, { intro h, apply J₁.transitive (J₁.top_mem X), intros Y f hf, change J₁.close S f, rwa h }, { intro hS, rw eq_top_iff, intros Y f hf, apply J₁.pullback_stable _ hS } end /-- A Grothendieck topology induces a natural family of closure operators on sieves. -/ @[simps {rhs_md := semireducible}] def closure_operator (X : C) : closure_operator (sieve X) := closure_operator.mk' J₁.close (λ S₁ S₂ h, J₁.le_close_of_is_closed (h.trans (J₁.le_close _)) (J₁.close_is_closed S₂)) J₁.le_close (λ S, J₁.le_close_of_is_closed le_rfl (J₁.close_is_closed S)) @[simp] lemma closed_iff_closed {X : C} (S : sieve X) : S ∈ (J₁.closure_operator X).closed ↔ J₁.is_closed S := (J₁.is_closed_iff_close_eq_self S).symm end grothendieck_topology /-- The presheaf sending each object to the set of `J`-closed sieves on it. This presheaf is a `J`-sheaf (and will turn out to be a subobject classifier for the category of `J`-sheaves). -/ @[simps] def functor.closed_sieves : Cᵒᵖ ⥤ Type (max v u) := { obj := λ X, {S : sieve X.unop // J₁.is_closed S}, map := λ X Y f S, ⟨S.1.pullback f.unop, J₁.is_closed_pullback f.unop _ S.2⟩ } /-- The presheaf of `J`-closed sieves is a `J`-sheaf. The proof of this is adapted from [MM92], Chatper III, Section 7, Lemma 1. -/ lemma classifier_is_sheaf : presieve.is_sheaf J₁ (functor.closed_sieves J₁) := begin intros X S hS, rw ← presieve.is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, refine ⟨_, _⟩, { rintro x ⟨M, hM⟩ ⟨N, hN⟩ hM₂ hN₂, ext, dsimp only [subtype.coe_mk], rw [← J₁.covers_iff_mem_of_closed hM, ← J₁.covers_iff_mem_of_closed hN], have q : ∀ ⦃Z : C⦄ (g : Z ⟶ X) (hg : S g), M.pullback g = N.pullback g, { intros Z g hg, apply congr_arg subtype.val ((hM₂ g hg).trans (hN₂ g hg).symm) }, have MSNS : M ⊓ S = N ⊓ S, { ext Z g, rw [sieve.inter_apply, sieve.inter_apply, and_comm (N g), and_comm], apply and_congr_right, intro hg, rw [sieve.pullback_eq_top_iff_mem, sieve.pullback_eq_top_iff_mem, q g hg] }, split, { intro hf, rw J₁.covers_iff, apply J₁.superset_covering (sieve.pullback_monotone f inf_le_left), rw ← MSNS, apply J₁.arrow_intersect f M S hf (J₁.pullback_stable _ hS) }, { intro hf, rw J₁.covers_iff, apply J₁.superset_covering (sieve.pullback_monotone f inf_le_left), rw MSNS, apply J₁.arrow_intersect f N S hf (J₁.pullback_stable _ hS) } }, { intros x hx, rw presieve.compatible_iff_sieve_compatible at hx, let M := sieve.bind S (λ Y f hf, (x f hf).1), have : ∀ ⦃Y⦄ (f : Y ⟶ X) (hf : S f), M.pullback f = (x f hf).1, { intros Y f hf, apply le_antisymm, { rintro Z u ⟨W, g, f', hf', (hg : (x f' hf').1 _), c⟩, rw [sieve.pullback_eq_top_iff_mem, ←(show (x (u ≫ f) _).1 = (x f hf).1.pullback u, from congr_arg subtype.val (hx f u hf))], simp_rw ← c, rw (show (x (g ≫ f') _).1 = _, from congr_arg subtype.val (hx f' g hf')), apply sieve.pullback_eq_top_of_mem _ hg }, { apply sieve.le_pullback_bind S (λ Y f hf, (x f hf).1) } }, refine ⟨⟨_, J₁.close_is_closed M⟩, _⟩, { intros Y f hf, ext1, dsimp, rw [← J₁.pullback_close, this _ hf], apply le_antisymm (J₁.le_close_of_is_closed le_rfl (x f hf).2) (J₁.le_close _) } }, end /-- If presheaf of `J₁`-closed sieves is a `J₂`-sheaf then `J₁ ≤ J₂`. Note the converse is true by `classifier_is_sheaf` and `is_sheaf_of_le`. -/ lemma le_topology_of_closed_sieves_is_sheaf {J₁ J₂ : grothendieck_topology C} (h : presieve.is_sheaf J₁ (functor.closed_sieves J₂)) : J₁ ≤ J₂ := λ X S hS, begin rw ← J₂.close_eq_top_iff_mem, have : J₂.is_closed (⊤ : sieve X), { intros Y f hf, trivial }, suffices : (⟨J₂.close S, J₂.close_is_closed S⟩ : subtype _) = ⟨⊤, this⟩, { rw subtype.ext_iff at this, exact this }, apply (h S hS).is_separated_for.ext, { intros Y f hf, ext1, dsimp, rw [sieve.pullback_top, ← J₂.pullback_close, S.pullback_eq_top_of_mem hf, J₂.close_eq_top_iff_mem], apply J₂.top_mem }, end /-- If being a sheaf for `J₁` is equivalent to being a sheaf for `J₂`, then `J₁ = J₂`. -/ lemma topology_eq_iff_same_sheaves {J₁ J₂ : grothendieck_topology C} : J₁ = J₂ ↔ (∀ (P : Cᵒᵖ ⥤ Type (max v u)), presieve.is_sheaf J₁ P ↔ presieve.is_sheaf J₂ P) := begin split, { rintro rfl, intro P, refl }, { intro h, apply le_antisymm, { apply le_topology_of_closed_sieves_is_sheaf, rw h, apply classifier_is_sheaf }, { apply le_topology_of_closed_sieves_is_sheaf, rw ← h, apply classifier_is_sheaf } } end /-- A closure (increasing, inflationary and idempotent) operation on sieves that commutes with pullback induces a Grothendieck topology. In fact, such operations are in bijection with Grothendieck topologies. -/ @[simps] def topology_of_closure_operator (c : Π (X : C), closure_operator (sieve X)) (hc : Π ⦃X Y : C⦄ (f : Y ⟶ X) (S : sieve X), c _ (S.pullback f) = (c _ S).pullback f) : grothendieck_topology C := { sieves := λ X, {S | c X S = ⊤}, top_mem' := λ X, top_unique ((c X).le_closure _), pullback_stable' := λ X Y S f hS, begin rw set.mem_set_of_eq at hS, rw [set.mem_set_of_eq, hc, hS, sieve.pullback_top], end, transitive' := λ X S hS R hR, begin rw set.mem_set_of_eq at hS, rw [set.mem_set_of_eq, ←(c X).idempotent, eq_top_iff, ←hS], apply (c X).monotone (λ Y f hf, _), rw [sieve.pullback_eq_top_iff_mem, ←hc], apply hR hf, end } /-- The topology given by the closure operator `J.close` on a Grothendieck topology is the same as `J`. -/ lemma topology_of_closure_operator_self : topology_of_closure_operator J₁.closure_operator (λ X Y, J₁.pullback_close) = J₁ := begin ext X S, apply grothendieck_topology.close_eq_top_iff_mem, end lemma topology_of_closure_operator_close (c : Π (X : C), closure_operator (sieve X)) (pb : Π ⦃X Y : C⦄ (f : Y ⟶ X) (S : sieve X), c Y (S.pullback f) = (c X S).pullback f) (X : C) (S : sieve X) : (topology_of_closure_operator c pb).close S = c X S := begin ext, change c _ (sieve.pullback f S) = ⊤ ↔ c _ S f, rw [pb, sieve.pullback_eq_top_iff_mem], end end category_theory
02cae5835006541331da5c8c6d815266da3d0a30
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/calc.lean
f0e336f433a689009ecc6658964f801e9da84c64
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
376
lean
import standard using num namespace foo variable le : num → num → Prop axiom le_trans {a b c : num} : le a b → le b c → le a c calc_trans le_trans infix `≤`:50 := le end namespace foo theorem T {a b c d : num} : a ≤ b → b ≤ c → c ≤ d → a ≤ d := assume H1 H2 H3, calc a ≤ b : H1 ... ≤ c : H2 ... ≤ d : H3 end
af5c7d2d707d2490142b6e4abf3eafd767ff3988
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/witt_vector/frobenius.lean
a0d22a0ece08af261dcd84bfef3fbfb8f1c031f0
[ "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
14,079
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 data.nat.multiplicity import ring_theory.witt_vector.basic import ring_theory.witt_vector.is_poly import field_theory.perfect_closure /-! ## The Frobenius operator If `R` has characteristic `p`, then there is a ring endomorphism `frobenius R p` that raises `r : R` to the power `p`. By applying `witt_vector.map` to `frobenius R p`, we obtain a ring endomorphism `𝕎 R →+* 𝕎 R`. It turns out that this endomorphism can be described by polynomials over `ℤ` that do not depend on `R` or the fact that it has characteristic `p`. In this way, we obtain a Frobenius endomorphism `witt_vector.frobenius_fun : 𝕎 R → 𝕎 R` for every commutative ring `R`. Unfortunately, the aforementioned polynomials can not be obtained using the machinery of `witt_structure_int` that was developed in `structure_polynomial.lean`. We therefore have to define the polynomials by hand, and check that they have the required property. In case `R` has characteristic `p`, we show in `frobenius_fun_eq_map_frobenius` that `witt_vector.frobenius_fun` is equal to `witt_vector.map (frobenius R p)`. ### Main definitions and results * `frobenius_poly`: the polynomials that describe the coefficients of `frobenius_fun`; * `frobenius_fun`: the Frobenius endomorphism on Witt vectors; * `frobenius_fun_is_poly`: the tautological assertion that Frobenius is a polynomial function; * `frobenius_fun_eq_map_frobenius`: the fact that in characteristic `p`, Frobenius is equal to `witt_vector.map (frobenius R p)`. TODO: Show that `witt_vector.frobenius_fun` is a ring homomorphism, and bundle it into `witt_vector.frobenius`. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace witt_vector variables {p : ℕ} {R S : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] local notation `𝕎` := witt_vector p -- type as `\bbW` noncomputable theory open mv_polynomial finset open_locale big_operators variables (p) include hp /-- The rational polynomials that give the coefficients of `frobenius x`, in terms of the coefficients of `x`. These polynomials actually have integral coefficients, see `frobenius_poly` and `map_frobenius_poly`. -/ def frobenius_poly_rat (n : ℕ) : mv_polynomial ℕ ℚ := bind₁ (witt_polynomial p ℚ ∘ λ n, n + 1) (X_in_terms_of_W p ℚ n) lemma bind₁_frobenius_poly_rat_witt_polynomial (n : ℕ) : bind₁ (frobenius_poly_rat p) (witt_polynomial p ℚ n) = (witt_polynomial p ℚ (n+1)) := begin delta frobenius_poly_rat, rw [← bind₁_bind₁, bind₁_X_in_terms_of_W_witt_polynomial, bind₁_X_right], end /-- An auxiliary definition, to avoid an excessive amount of finiteness proofs for `multiplicity p n`. -/ private def pnat_multiplicity (n : ℕ+) : ℕ := (multiplicity p n).get $ multiplicity.finite_nat_iff.mpr $ ⟨ne_of_gt hp.1.one_lt, n.2⟩ local notation `v` := pnat_multiplicity /-- An auxiliary polynomial over the integers, that satisfies `p * (frobenius_poly_aux p n) + X n ^ p = frobenius_poly p n`. This makes it easy to show that `frobenius_poly p n` is congruent to `X n ^ p` modulo `p`. -/ noncomputable def frobenius_poly_aux : ℕ → mv_polynomial ℕ ℤ | n := X (n + 1) - ∑ i : fin n, have _ := i.is_lt, ∑ j in range (p ^ (n - i)), (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * (frobenius_poly_aux i) ^ (j + 1) * C ↑((p ^ (n - i)).choose (j + 1) / (p ^ (n - i - v p ⟨j + 1, nat.succ_pos j⟩)) * ↑p ^ (j - v p ⟨j + 1, nat.succ_pos j⟩) : ℕ) lemma frobenius_poly_aux_eq (n : ℕ) : frobenius_poly_aux p n = X (n + 1) - ∑ i in range n, ∑ j in range (p ^ (n - i)), (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * (frobenius_poly_aux p i) ^ (j + 1) * C ↑((p ^ (n - i)).choose (j + 1) / (p ^ (n - i - v p ⟨j + 1, nat.succ_pos j⟩)) * ↑p ^ (j - v p ⟨j + 1, nat.succ_pos j⟩) : ℕ) := by { rw [frobenius_poly_aux, ← fin.sum_univ_eq_sum_range] } /-- The polynomials that give the coefficients of `frobenius x`, in terms of the coefficients of `x`. -/ def frobenius_poly (n : ℕ) : mv_polynomial ℕ ℤ := X n ^ p + C ↑p * (frobenius_poly_aux p n) /- Our next goal is to prove ``` lemma map_frobenius_poly (n : ℕ) : mv_polynomial.map (int.cast_ring_hom ℚ) (frobenius_poly p n) = frobenius_poly_rat p n ``` This lemma has a rather long proof, but it mostly boils down to applying induction, and then using the following two key facts at the right point. -/ /-- A key divisibility fact for the proof of `witt_vector.map_frobenius_poly`. -/ lemma map_frobenius_poly.key₁ (n j : ℕ) (hj : j < p ^ (n)) : p ^ (n - v p ⟨j + 1, j.succ_pos⟩) ∣ (p ^ n).choose (j + 1) := begin apply multiplicity.pow_dvd_of_le_multiplicity, have aux : (multiplicity p ((p ^ n).choose (j + 1))).dom, { rw [← multiplicity.finite_iff_dom, multiplicity.finite_nat_iff], exact ⟨hp.1.ne_one, nat.choose_pos hj⟩, }, rw [← enat.coe_get aux, enat.coe_le_coe, tsub_le_iff_left, ← enat.coe_le_coe, nat.cast_add, pnat_multiplicity, enat.coe_get, enat.coe_get, add_comm], exact (hp.1.multiplicity_choose_prime_pow hj j.succ_pos).ge, end /-- A key numerical identity needed for the proof of `witt_vector.map_frobenius_poly`. -/ lemma map_frobenius_poly.key₂ {n i j : ℕ} (hi : i < n) (hj : j < p ^ (n - i)) : j - (v p ⟨j + 1, j.succ_pos⟩) + n = i + j + (n - i - v p ⟨j + 1, j.succ_pos⟩) := begin generalize h : (v p ⟨j + 1, j.succ_pos⟩) = m, suffices : m ≤ n - i ∧ m ≤ j, { rw [tsub_add_eq_add_tsub this.2, add_comm i j, add_tsub_assoc_of_le (this.1.trans (nat.sub_le n i)), add_assoc, tsub_right_comm, add_comm i, tsub_add_cancel_of_le (le_tsub_of_add_le_right ((le_tsub_iff_left hi.le).mp this.1))] }, split, { rw [← h, ← enat.coe_le_coe, pnat_multiplicity, enat.coe_get, ← hp.1.multiplicity_choose_prime_pow hj j.succ_pos], apply le_add_left, refl }, { obtain ⟨c, hc⟩ : p ^ m ∣ j + 1, { rw [← h], exact multiplicity.pow_multiplicity_dvd _, }, obtain ⟨c, rfl⟩ : ∃ k : ℕ, c = k + 1, { apply nat.exists_eq_succ_of_ne_zero, rintro rfl, simpa only using hc }, rw [mul_add, mul_one] at hc, apply nat.le_of_lt_succ, calc m < p ^ m : nat.lt_pow_self hp.1.one_lt m ... ≤ j + 1 : by { rw ← tsub_eq_of_eq_add_rev hc, apply nat.sub_le } } end lemma map_frobenius_poly (n : ℕ) : mv_polynomial.map (int.cast_ring_hom ℚ) (frobenius_poly p n) = frobenius_poly_rat p n := begin rw [frobenius_poly, ring_hom.map_add, ring_hom.map_mul, ring_hom.map_pow, map_C, map_X, ring_hom.eq_int_cast, int.cast_coe_nat, frobenius_poly_rat], apply nat.strong_induction_on n, clear n, intros n IH, rw [X_in_terms_of_W_eq], simp only [alg_hom.map_sum, alg_hom.map_sub, alg_hom.map_mul, alg_hom.map_pow, bind₁_C_right], have h1 : (↑p ^ n) * (⅟ (↑p : ℚ) ^ n) = 1 := by rw [←mul_pow, mul_inv_of_self, one_pow], rw [bind₁_X_right, function.comp_app, witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ, sum_range_succ, tsub_self, add_tsub_cancel_left, pow_zero, pow_one, pow_one, sub_mul, add_mul, add_mul, mul_right_comm, mul_right_comm (C (↑p ^ (n + 1))), ←C_mul, ←C_mul, pow_succ, mul_assoc ↑p (↑p ^ n), h1, mul_one, C_1, one_mul, add_comm _ (X n ^ p), add_assoc, ←add_sub, add_right_inj, frobenius_poly_aux_eq, ring_hom.map_sub, map_X, mul_sub, sub_eq_add_neg, add_comm _ (C ↑p * X (n + 1)), ←add_sub, add_right_inj, neg_eq_iff_neg_eq, neg_sub], simp only [ring_hom.map_sum, mul_sum, sum_mul, ←sum_sub_distrib], apply sum_congr rfl, intros i hi, rw mem_range at hi, rw [← IH i hi], clear IH, rw [add_comm (X i ^ p), add_pow, sum_range_succ', pow_zero, tsub_zero, nat.choose_zero_right, one_mul, nat.cast_one, mul_one, mul_add, add_mul, nat.succ_sub (le_of_lt hi), nat.succ_eq_add_one (n - i), pow_succ, pow_mul, add_sub_cancel, mul_sum, sum_mul], apply sum_congr rfl, intros j hj, rw mem_range at hj, rw [ring_hom.map_mul, ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_pow, ring_hom.map_pow, ring_hom.map_pow, ring_hom.map_pow, map_C, map_X, mul_pow], rw [mul_comm (C ↑p ^ i), mul_comm _ ((X i ^ p) ^ _), mul_comm (C ↑p ^ (j + 1)), mul_comm (C ↑p)], simp only [mul_assoc], apply congr_arg, apply congr_arg, rw [←C_eq_coe_nat], simp only [←ring_hom.map_pow, ←C_mul], rw C_inj, simp only [inv_of_eq_inv, ring_hom.eq_int_cast, inv_pow₀, int.cast_coe_nat, nat.cast_mul], rw [rat.coe_nat_div _ _ (map_frobenius_poly.key₁ p (n - i) j hj)], simp only [nat.cast_pow, pow_add, pow_one], suffices : ((p ^ (n - i)).choose (j + 1) * p ^ (j - v p ⟨j + 1, j.succ_pos⟩) * p * p ^ n : ℚ) = p ^ j * p * ((p ^ (n - i)).choose (j + 1) * p ^ i) * p ^ (n - i - v p ⟨j + 1, j.succ_pos⟩), { have aux : ∀ k : ℕ, (p ^ k : ℚ) ≠ 0, { intro, apply pow_ne_zero, exact_mod_cast hp.1.ne_zero }, simpa [aux, -one_div] with field_simps using this.symm }, rw [mul_comm _ (p : ℚ), mul_assoc, mul_assoc, ← pow_add, map_frobenius_poly.key₂ p hi hj], ring_exp end lemma frobenius_poly_zmod (n : ℕ) : mv_polynomial.map (int.cast_ring_hom (zmod p)) (frobenius_poly p n) = X n ^ p := begin rw [frobenius_poly, ring_hom.map_add, ring_hom.map_pow, ring_hom.map_mul, map_X, map_C], simp only [int.cast_coe_nat, add_zero, ring_hom.eq_int_cast, zmod.nat_cast_self, zero_mul, C_0], end @[simp] lemma bind₁_frobenius_poly_witt_polynomial (n : ℕ) : bind₁ (frobenius_poly p) (witt_polynomial p ℤ n) = (witt_polynomial p ℤ (n+1)) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_bind₁, map_frobenius_poly, bind₁_frobenius_poly_rat_witt_polynomial, map_witt_polynomial], end variables {p} /-- `frobenius_fun` is the function underlying the ring endomorphism `frobenius : 𝕎 R →+* frobenius 𝕎 R`. -/ def frobenius_fun (x : 𝕎 R) : 𝕎 R := mk p $ λ n, mv_polynomial.aeval x.coeff (frobenius_poly p n) lemma coeff_frobenius_fun (x : 𝕎 R) (n : ℕ) : coeff (frobenius_fun x) n = mv_polynomial.aeval x.coeff (frobenius_poly p n) := by rw [frobenius_fun, coeff_mk] variables (p) /-- `frobenius_fun` is tautologically a polynomial function. See also `frobenius_is_poly`. -/ @[is_poly] lemma frobenius_fun_is_poly : is_poly p (λ R _Rcr, @frobenius_fun p R _ _Rcr) := ⟨⟨frobenius_poly p, by { introsI, funext n, apply coeff_frobenius_fun }⟩⟩ variable {p} @[ghost_simps] lemma ghost_component_frobenius_fun (n : ℕ) (x : 𝕎 R) : ghost_component n (frobenius_fun x) = ghost_component (n + 1) x := by simp only [ghost_component_apply, frobenius_fun, coeff_mk, ← bind₁_frobenius_poly_witt_polynomial, aeval_bind₁] /-- If `R` has characteristic `p`, then there is a ring endomorphism that raises `r : R` to the power `p`. By applying `witt_vector.map` to this endomorphism, we obtain a ring endomorphism `frobenius R p : 𝕎 R →+* 𝕎 R`. The underlying function of this morphism is `witt_vector.frobenius_fun`. -/ def frobenius : 𝕎 R →+* 𝕎 R := { to_fun := frobenius_fun, map_zero' := begin refine is_poly.ext ((frobenius_fun_is_poly p).comp (witt_vector.zero_is_poly)) ((witt_vector.zero_is_poly).comp (frobenius_fun_is_poly p)) _ _ 0, ghost_simp end, map_one' := begin refine is_poly.ext ((frobenius_fun_is_poly p).comp (witt_vector.one_is_poly)) ((witt_vector.one_is_poly).comp (frobenius_fun_is_poly p)) _ _ 0, ghost_simp end, map_add' := by ghost_calc _ _; ghost_simp, map_mul' := by ghost_calc _ _; ghost_simp } lemma coeff_frobenius (x : 𝕎 R) (n : ℕ) : coeff (frobenius x) n = mv_polynomial.aeval x.coeff (frobenius_poly p n) := coeff_frobenius_fun _ _ @[ghost_simps] lemma ghost_component_frobenius (n : ℕ) (x : 𝕎 R) : ghost_component n (frobenius x) = ghost_component (n + 1) x := ghost_component_frobenius_fun _ _ variables (p) /-- `frobenius` is tautologically a polynomial function. -/ @[is_poly] lemma frobenius_is_poly : is_poly p (λ R _Rcr, @frobenius p R _ _Rcr) := frobenius_fun_is_poly _ section char_p variables [char_p R p] @[simp] lemma coeff_frobenius_char_p (x : 𝕎 R) (n : ℕ) : coeff (frobenius x) n = (x.coeff n) ^ p := begin rw [coeff_frobenius], -- outline of the calculation, proofs follow below calc aeval (λ k, x.coeff k) (frobenius_poly p n) = aeval (λ k, x.coeff k) (mv_polynomial.map (int.cast_ring_hom (zmod p)) (frobenius_poly p n)) : _ ... = aeval (λ k, x.coeff k) (X n ^ p : mv_polynomial ℕ (zmod p)) : _ ... = (x.coeff n) ^ p : _, { conv_rhs { rw [aeval_eq_eval₂_hom, eval₂_hom_map_hom] }, apply eval₂_hom_congr (ring_hom.ext_int _ _) rfl rfl }, { rw frobenius_poly_zmod }, { rw [alg_hom.map_pow, aeval_X] } end lemma frobenius_eq_map_frobenius : @frobenius p R _ _ = map (_root_.frobenius R p) := begin ext x n, simp only [coeff_frobenius_char_p, map_coeff, frobenius_def], end @[simp] lemma frobenius_zmodp (x : 𝕎 (zmod p)) : (frobenius x) = x := by simp only [ext_iff, coeff_frobenius_char_p, zmod.pow_card, eq_self_iff_true, forall_const] variables (p R) /-- `witt_vector.frobenius` as an equiv. -/ @[simps {fully_applied := ff}] def frobenius_equiv [perfect_ring R p] : witt_vector p R ≃+* witt_vector p R := { to_fun := witt_vector.frobenius, inv_fun := map (pth_root R p), left_inv := λ f, ext $ λ n, by { rw frobenius_eq_map_frobenius, exact pth_root_frobenius _ }, right_inv := λ f, ext $ λ n, by { rw frobenius_eq_map_frobenius, exact frobenius_pth_root _ }, ..(witt_vector.frobenius : witt_vector p R →+* witt_vector p R) } lemma frobenius_bijective [perfect_ring R p] : function.bijective (@witt_vector.frobenius p R _ _) := (frobenius_equiv p R).bijective end char_p end witt_vector
b034b6ac8a006a2ddc6b46f34f46db2a6a4ac948
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/metric_space/hausdorff_distance.lean
5408f0366c299d7902a1118a4215c2eac13ef771
[ "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
32,615
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.isometry import topology.instances.ennreal import analysis.specific_limits /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist`. -/ noncomputable theory open_locale classical nnreal ennreal topological_space universes u v w open classical set function topological_space filter namespace emetric section inf_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-! ### Distance of a point to a set as a function into `ℝ≥0∞`. -/ /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ℝ≥0∞ := ⨅ y ∈ s, edist x y @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := infi_emptyset lemma le_inf_edist {d} : d ≤ inf_edist x s ↔ ∀ y ∈ s, d ≤ edist x y := by simp only [inf_edist, le_infi_iff] /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := infi_union /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := infi_singleton /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := binfi_le _ h /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := nonpos_iff_eq_zero.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is monotonous with respect to inclusion -/ lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := infi_le_infi_of_subset h /-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/ lemma exists_edist_lt_of_inf_edist_lt {r : ℝ≥0∞} (h : inf_edist x s < r) : ∃y∈s, edist x y < r := by simpa only [inf_edist, infi_lt_iff] using h /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := calc (⨅ z ∈ s, edist x z) ≤ ⨅ z ∈ s, edist y z + edist x y : binfi_le_binfi $ λ z hz, (edist_triangle _ _ _).trans_eq (add_comm _ _) ... = (⨅ z ∈ s, edist y z) + edist x y : by simp only [ennreal.infi_add] /-- The edist to a set depends continuously on the point -/ @[continuity] lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _, refine ennreal.le_of_forall_pos_le_add (λε εpos h, _), have εpos' : (0 : ℝ≥0∞) < ε := by simpa, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2 := ennreal.lt_add_right h (ennreal.half_pos εpos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff.1 ycs (ε/2) (ennreal.half_pos εpos') with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h, λh, emetric.mem_closure_iff.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_inf_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact h.closure_eq end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := by simp only [inf_edist, infi_image, hΦ.edist_eq] lemma _root_.is_open.exists_Union_is_closed {U : set α} (hU : is_open U) : ∃ F : ℕ → set α, (∀ n, is_closed (F n)) ∧ (∀ n, F n ⊆ U) ∧ ((⋃ n, F n) = U) ∧ (monotone F) := begin obtain ⟨a, a_pos, a_lt_one⟩ : ∃ (a : ℝ≥0∞), 0 < a ∧ a < 1 := exists_between (ennreal.zero_lt_one), let F := λ (n : ℕ), (λ x, inf_edist x Uᶜ) ⁻¹' (Ici (a^n)), have F_subset : ∀ n, F n ⊆ U, { assume n x hx, by_contra h, rw [← mem_compl_iff, mem_iff_inf_edist_zero_of_closed (is_open.is_closed_compl hU)] at h, have : 0 < inf_edist x Uᶜ := lt_of_lt_of_le (ennreal.pow_pos a_pos _) hx, rw h at this, exact lt_irrefl _ this }, refine ⟨F, λ n, is_closed.preimage continuous_inf_edist is_closed_Ici, F_subset, _, _⟩, show monotone F, { assume m n hmn x hx, simp only [mem_Ici, mem_preimage] at hx ⊢, apply le_trans (ennreal.pow_le_pow_of_le_one a_lt_one.le hmn) hx }, show (⋃ n, F n) = U, { refine subset.antisymm (by simp only [Union_subset_iff, F_subset, forall_const]) (λ x hx, _), have : ¬(x ∈ Uᶜ), by simpa using hx, rw mem_iff_inf_edist_zero_of_closed (is_open.is_closed_compl hU) at this, have B : 0 < inf_edist x Uᶜ, by simpa [pos_iff_ne_zero] using this, have : filter.tendsto (λ n, a^n) at_top (𝓝 0) := ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 a_lt_one, rcases ((tendsto_order.1 this).2 _ B).exists with ⟨n, hn⟩, simp only [mem_Union, mem_Ici, mem_preimage], exact ⟨n, hn.le⟩ }, end end inf_edist --section /-! ### The Hausdorff distance as a function into `ℝ≥0∞`. -/ /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ @[irreducible] def Hausdorff_edist {α : Type u} [pseudo_emetric_space α] (s t : set α) : ℝ≥0∞ := (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) lemma Hausdorff_edist_def {α : Type u} [pseudo_emetric_space α] (s t : set α) : Hausdorff_edist s t = (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) := by rw Hausdorff_edist section Hausdorff_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin simp only [Hausdorff_edist_def, sup_idem, ennreal.supr_eq_zero], exact λ x hx, inf_edist_zero_of_mem hx end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, sup_le_iff, supr_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans _ le_sup_left, exact le_bsupr x h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ℝ≥0∞} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃y∈t, edist x y < r := exists_edist_lt_of_inf_edist_lt $ calc inf_edist x t ≤ Hausdorff_edist s t : inf_edist_le_Hausdorff_edist_of_mem h ... < r : H /-- The distance from `x` to `s` or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_pos_le_add $ λε εpos h, begin have εpos' : (0 : ℝ≥0∞) < ε := by simpa, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1 (ennreal.half_pos εpos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2 (ennreal.half_pos εpos'), rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add dxy.le dyz.le ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := by simp only [Hausdorff_edist_def, supr_image, inf_edist_image h] /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { intros z hz, exact ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { intros z hz, exact ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [sup_le_iff, supr_le_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xs) _, show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xu) _ ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := calc Hausdorff_edist s t = 0 ↔ s ⊆ closure t ∧ t ⊆ closure s : by simp only [Hausdorff_edist_def, ennreal.sup_eq_zero, ennreal.supr_eq_zero, ← mem_closure_iff_inf_edist_zero, subset_def] ... ↔ closure s = closure t : ⟨λ h, subset.antisymm (closure_minimal h.1 is_closed_closure) (closure_minimal h.2 is_closed_closure), λ h, ⟨h ▸ subset_closure, h.symm ▸ subset_closure⟩⟩ /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_closure] /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, hs.closure_eq, ht.closure_eq] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) : t.nonempty := t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) : s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-! Now, we turn to the same notions in metric spaces. To avoid the difficulties related to `Inf` and `Sup` on `ℝ` (which is only conditionally complete), we use the notions in `ℝ≥0∞` formulated in terms of the edistance, and coerce them to `ℝ`. Then their properties follow readily from the corresponding properties in `ℝ≥0∞`, modulo some tedious rewriting of inequalities from one to the other. -/ namespace metric section variables {α : Type u} {β : Type v} [pseudo_metric_space α] [pseudo_metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-! ### Distance of a point to a set as a function into `ℝ`. -/ /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) : inf_dist x t ≤ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_le_inf_edist_of_subset h end /-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/ lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s.nonempty) : ∃y∈s, dist x y < r := begin have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h, have : inf_edist x s < ennreal.of_real r, { rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h, simp }, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy, exact ⟨y, ys, hy⟩, end /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { by simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { apply inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ lemma uniform_continuous_inf_dist_pt : uniform_continuous (λx, inf_dist x s) := (lipschitz_inf_dist_pt s).uniform_continuous /-- The minimal distance to a set is continuous in point -/ @[continuity] lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma mem_iff_inf_dist_zero_of_closed (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := begin have := @mem_closure_iff_inf_dist_zero _ _ s x hs, rwa h.closure_eq at this end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] /-! ### Distance of a point to a set as a function into `ℝ≥0`. -/ /-- The minimal distance of a point to a set as a `ℝ≥0` -/ def inf_nndist (x : α) (s : set α) : ℝ≥0 := ennreal.to_nnreal (inf_edist x s) @[simp] lemma coe_inf_nndist : (inf_nndist x s : ℝ) = inf_dist x s := rfl /-- The minimal distance to a set (as `ℝ≥0`) is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_nndist_pt (s : set α) : lipschitz_with 1 (λx, inf_nndist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set (as `ℝ≥0`) is uniformly continuous in point -/ lemma uniform_continuous_inf_nndist_pt (s : set α) : uniform_continuous (λx, inf_nndist x s) := (lipschitz_inf_nndist_pt s).uniform_continuous /-- The minimal distance to a set (as `ℝ≥0`) is continuous in point -/ lemma continuous_inf_nndist_pt (s : set α) : continuous (λx, inf_nndist x s) := (uniform_continuous_inf_nndist_pt s).continuous /-! ### The Hausdorff distance as a function into `ℝ`. -/ /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance. -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt this (by simp [lt_top_iff_ne_top])) end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h1 : Hausdorff_edist s t = ⊤, by rwa [Hausdorff_dist, h1, ennreal.top_to_real], cases s.eq_empty_or_nonempty with hs hs, by rwa [hs, Hausdorff_dist_empty'], cases t.eq_empty_or_nonempty with ht ht, by rwa [ht, Hausdorff_dist_empty], have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : by simp [ennreal.add_lt_top]; simp [ennreal.lt_top_iff_ne_top, h, fin], rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin (lt_top_iff_ne_top.1 Dtu), ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section end metric --namespace
b73e054e4e2f2385b35441da8cb3242b97bde749
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/15_Formal_Languages/00_intro.lean
63da87baec65bb9db58cb2d9a17da0ad7203ee96
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
14,517
lean
/- A logic is a "formal language" that has a mathematically defined syntax and a mathematically defined semantics. We now drill down on the notions of the syntax and semantics of a formal language. The syntax of a language defines the set of valid expressions in the language. In predicate logic, for example, ∀ p: Person, ∃ m : Person, motherOf p m is syntactically well formed, but ()∀ ∃ r() is not. The semantics of a language then assigns a meaning each "well formed" expression in the language. When the formal language is a logic, the syntax defines a language of propositions, predicates, etc., while a semantics tells us how to evaluate the truth of any such expression. -/ /- In this unit we formalize the syntax and semantics of what we call propositional (as opposed to predicate) logic. Propositional logic is a very simple logic. It essentially mirrors (is "isomorphic to") the language of Boolean expressions. There are only a few kinds of expressions in propositional logic. These constitute the syntax of this formal language. * "literal expressions" for true and false * "variable expressions" * "not expressions" * "and expressions" * "or expressions" * etc. The semantics then gives us a way to decide what each expression in a language means. In propositional logic an expression means ("is") either true or false. Here are the rules. * literal true evaluates to true * literal false evaluates to false * the value of an "and" expression, e1 ∧ e2, is the Boolean conjunction of the values of e1 and e2, resp. * the value of a "not" expression, ¬ e, is the Boolean negation of the value of e * this leaves the question of the value of a variable expression. For this we need an additional idea: that of an interpretation. An interpretation is an assignment of Boolean values to each of the variables that might appear in some expression. Now, to evaluate a variable expression, X, we just "look up" its value in a given interpretation. A variable expression will thus have different values under different interpretations. Thus, expressions, in general, because they generally involve variables, will have different values under different interpretations. We now show you how not only to make these ideas precise, but how to automate them, in Lean. You are about to implement your own simple automated logical reasoning system! -/ -- Syntax /- We formalize the syntax of a language with an inductive definition of the set of valid expressions. An expression in propositional logic is built from a (1) a logical constant, true or false, (2) a propositional (you can think "Boolean") variable, or (3) a logical connective (and, or, not, etc) and one or more smaller expressions. -/ /- To formalize this idea, we need to define what we mean by a variable. We do with with a new type, pVar, where each such variable holds a ℕ value that distinguishes it from any other propVar. -/ inductive pVar : Type | mk : ℕ → pVar -- Examples #check (pVar.mk 0) -- Nice names for a few pVars def X := pVar.mk 0 def Y := pVar.mk 1 def Z := pVar.mk 2 def W := pVar.mk 3 /- Now we formalize a language of expressions in propositional logic. -/ inductive pExp : Type | mk_lit_pexp : bool → pExp | mk_var_pexp : pVar → pExp | mk_not_pexp : pExp → pExp | mk_and_pexp : pExp → pExp → pExp open pExp -- Examples of expressions def false_exp := mk_lit_pexp ff #check false_exp def true_exp := mk_lit_pexp tt def X_exp := mk_var_pexp X def Y_exp := mk_var_pexp Y def Z_exp := mk_var_pexp Z #reduce Z_exp def not_X_exp := mk_not_pexp X_exp def and_X_Y_exp := mk_and_pexp X_exp Y_exp def and_X_Z_exp := mk_and_pexp X_exp Z_exp #reduce and_X_Z_exp -- syntactic sugar! notation e1 ∧ e2 := mk_and_pexp e1 e2 notation ¬ e := mk_not_pexp e -- expressions using our notation! def not_X_exp' := ¬ X_exp def and_X_Y_exp' := X_exp ∧ Y_exp def and_X_Z_exp' := X_exp ∧ Z_exp -- Quiz def tf := (mk_lit_pexp tt) ∧ (mk_lit_pexp ff) def nt := ¬ (mk_lit_pexp tt) def nxy := ¬ (X_exp ∧ Y_exp) def foo := nt ∧ nxy def bar := (¬ nxy) ∧ foo def baz : pExp := tf def jab := ¬ (X_exp ∧ Y_exp) #reduce jab -- Semantics /- To formalize a semantics for our realization of propositional logic, we need to formally define what we mean by an interpretation. An interpretation in propositional logic is a function from propositional variables to corresponding (Boolean) truth values. An interpretation tells us what each variable "means" -- i.e., whether it means true, or false. We now define a name for the type of an interpretation (pVar → bool). Then we present several examples of interpretations. -/ def pInterp := pVar → bool -- an "all false" interpretation def falseInterp (v : pVar) : bool := ff -- an "all true" interpretation def trueInterp (v : pVar) := tt -- X = tt, Y=ff, Z=tt, _ = ff def anInterp: pInterp := λ(v: pVar), match v with | (pVar.mk 0) := tt -- X | (pVar.mk 1) := ff -- Y | (pVar.mk 2) := tt -- Z | _ := ff -- otherwise end -- Semantics /- We now define a semantics for our language in the form of a function that, when given any expression in our language *and* an interpretation for the variables that might appear in it, evaluates its truth value and returns it as a result. The definition is by cases, i.e., with one rule for each possible form (constructor) of expression. Note: Lean "overloads" logical operator notations, such as ∧, ∨, and ¬. Here they are applied not to values of type Prop, but to values of type bool, where they have their usual means from Boolean algebra. -/ def pEval : pExp → pInterp → bool -- how to evaluate literal expression | (mk_lit_pexp b) i := b -- how to evaluate variable expression | (mk_var_pexp v) i := i v -- how to evaluate a "not" expression | (mk_not_pexp e) i := bnot (pEval e i) -- how to evaluate an "and" expression | (mk_and_pexp e1 e2) i := band (pEval e1 i) (pEval e2 i) /- And now we have a formal language, with a syntax, interpretations, and semantics. Let's evaluate some of our expressions under varying interpretations. -/ -- literal expressions /- #reduce pEval tt_exp falseInterp #reduce pEval tt_exp trueInterp #reduce pEval tt_exp anInterp #reduce pEval ff_exp falseInterp #reduce pEval ff_exp trueInterp #reduce pEval ff_exp anInterp -/ -- variable expressions #reduce pEval X_exp falseInterp #reduce pEval X_exp trueInterp #reduce pEval X_exp anInterp #reduce pEval Y_exp falseInterp #reduce pEval Y_exp trueInterp #reduce pEval Y_exp anInterp #reduce pEval Z_exp falseInterp #reduce pEval Z_exp trueInterp #reduce pEval Z_exp anInterp #reduce pEval (mk_var_pexp W) falseInterp #reduce pEval (mk_var_pexp W) trueInterp #reduce pEval (mk_var_pexp W) anInterp -- We don't have to give variables names #reduce pEval (mk_var_pexp (pVar.mk 10)) anInterp -- not expression #reduce pEval not_X_exp falseInterp #reduce pEval not_X_exp trueInterp #reduce pEval not_X_exp anInterp -- and expressio #reduce pEval and_X_Z_exp falseInterp #reduce pEval and_X_Z_exp trueInterp #reduce pEval and_X_Z_exp anInterp #reduce pEval and_X_Z_exp' falseInterp #reduce pEval and_X_Z_exp' trueInterp #reduce pEval and_X_Z_exp' anInterp #reduce pEval and_X_Y_exp anInterp /- So there you have it: a complete formal definition of the syntax, interpretation, and semantics of propositional logic, in Lean, with a nice "surface syntax," to boot. (Ok, it's complete except for the definitions for the other logical connectives. You will add some of them in homework and on the exam.) -/ /- From here, we can define richer functions, such as functions that analyze expressions; and we can even state and prove theorems about our language. -/ /- Let's define a function that returns the set of variables in a given pExp. This will be useful in the future. -/ /- We start by defining a recursive helper function that adds all the variables in given expression to the given, often already non-empty, set of variables. Understand the type and purpose of this function, then go on to read the following main function. Study its purpose, type, and implementation, then come back for a deeper look at how this function is implemented. Learn to use functions knowing only their type and purpose, ignoring, at least at first, their implementation details. Pratice mental abstracting. We implement (prove) this recursive function (type) by case analysis on possible forms of the given pExp. -/ def vars_in_exp_helper: pExp → set pVar → set pVar -- literal expressions add no variables to the set | (mk_lit_pexp _) s := s -- a variable expression adds variable v to the set | (mk_var_pexp v) s := s ∪ { v } -- a (not e) expression adds the variables in e | (mk_not_pexp e) s := s ∪ (vars_in_exp_helper e s) -- an (and e1 e2), add the variables in e1 and e2 | (mk_and_pexp e1 e2) s := s ∪ (vars_in_exp_helper e1 s) ∪ (vars_in_exp_helper e2 s) /- Main function: a non-recursive function that passes an initially empty set of variables to the helper function and then gets back a set of all, and only, the variables in the given expression. -/ def vars_in_exp (e: pExp) : set pVar := vars_in_exp_helper e ({}: set pVar) /- Examples of its use -/ #reduce vars_in_exp and_X_Y_exp -- A predicate defining the set { X, Y /- Another example -/ #reduce vars_in_exp and_X_Z_exp /- EXERCISE: Write a function that when given an expression, e, returns the "nesting depth" of the expression. The nesting depth of a literal or variable expression is 1. The depth of a (not e) expression is 1 + the depth of e. And the depth of an (and e1 e2) expression is 1 + the max of the depths of e1 and e2. You can use the Lean-provided max function in your answer. -/ #reduce max 5 7 #reduce max 7 5 /- We can also prove theorems about our language in general. Here's a proof that evaluation under a given interpretation is "deterministic:: it always produces the same result. This is really just a corollary of the facts that (1) functions in Lean are single valued and (2) we defined the semantics of expressions with a function. There's one and only one answer for the value of any given expression. -/ theorem pEval_deterministic : ∀ e : pExp, ∀ i : pInterp, ∀ v1 v2 : bool, v1 = pEval e i → v2 = pEval e i → v1 = v2 := begin intros e i v1 v2 h_v1 h_v2, rw h_v1, rw h_v2, end /- We can also prove theorems ("reason about") particular expressions, or certain classes of expressions, in our language. For example, if X_exp is any variable expression, then the expression (X_exp ∧ (¬ X_exp)) is false under any interpretation. We can easily prove this proposition. -/ theorem contra : ∀ V : pVar, ∀ i : pInterp, pEval ((mk_var_pexp V) ∧ ¬ (mk_var_pexp V)) i = ff := begin intros X i, simp [pEval], -- case analysis on result of function! cases (i X), left, apply rfl, right, apply rfl, end /- Note that it is quantified over all possible interpretations: over all possible functions from pVar → bool. Lean supports what is called higher order predicate logic. Quantifying over functions and relations is ok in a higher-order predicate logic. It is not allowed in the first-order predicate logic of everyday math and computer science. Here you can see that it gives you great expressive power to be able to quantify over functions. It gives us a way to say, "under any possible interpretation", which is exactly what we need to be able to say to define satisfiability, validity, unsatisfiability, etc. -/ /- Exercise: Prove that for any variable, V, the logical expression (mk_var_exp V) ∨ (¬ (mk_var_exp V)) always evaluates to true. -/ def valid (e : pExp) : Prop := ∀ i : pInterp, pEval e i = tt /- An expression in propositional logic is unsatisfiable if it does'ot evaluate to true under any interpretation. -/ def unsatisfiable (e : pExp) : Prop := ∀ i, pEval e i = ff /- You could also have said there does not exist an i that makes (pEval e i) = tt. -/ /- An interpretation that makes an expression, e, evaluate to true, is said to be a "model" of that expression. Here's a predicate asserting that i is a model of e. -/ def isModel (i: pInterp) (e : pExp) := pEval e i = tt /- An expression is said to be satisfiable if there is at least one interpretation under which it evaluates to true. -/ def satisfiable (e : pExp) : Prop := ∃ i, isModel i e /- Example: X ∧ ¬ X is unsatisfiable. -/ example : unsatisfiable (X_exp ∧ (¬ (X_exp))) := begin unfold unsatisfiable, intro i, rw pEval, -- you can do this rw pEval, -- and do it again cases (pEval X_exp i), -- cool! trivial, trivial, end /- EXERCISE: Once you've extended our logic with an or operator, formulize and prove the proposition that (our rendering of) X ∨ (¬ X) is valid. EXERCISE: Prove the proposition that (X ∨ Y) ∧ Z is satisfiable. Hint: You'll need a witness. There is an element of search involved in solving a problem like this. -/ /- EXERCISE: Write a SAT solver based on what we've done here. -/ -- m'th bit from right in binary rep of n def mrbn: ℕ → ℕ → bool | 0 n := n % 2 = 1 | (nat.succ m') n := mrbn m' (n/2) /- smoke test #reduce mrbn 0 15 #reduce mrbn 2 15 #reduce mrbn 2 15 #reduce mrbn 3 15 #reduce mrbn 4 15 #reduce mrbn 5 15 -/ /- The mth canonical interpretation among the 2^n-1 interpretations for a set of variables of size n. The values of the first n-indexed variables in the mth interpretation are determined by the bits in the binary representation of m. The leftmost bit gives the value for the variable with index 0. Each bit to the left gives the value of the next indexed variable. All subsequent values are ff. m thus effectively enumerates the 2^n interpretations on the n first variables in the index set of all variables. -/ def mthInterpOf2toN (m n: ℕ) : pInterp := if (m >= 2^n) then falseInterp else λ v : pVar, match v with | (pVar.mk i) := if i >= n then ff else (mrbn i m) end /- Examples: -/ #reduce pEval and_X_Y_exp (mthInterpOf2toN 3 3) -- unincorporated #reduce mthInterpOf2toN 3 5 def first_n_true_inter (n : ℕ) : pInterp := λ v, match v with | (pVar.mk n') := if n' < n then tt else ff end def all_models (e : pExp) := { m | isModel m e} def sat_solve (e : pExp) : option pInterp := none
bd1f9cd8cc7318997ae64a1982cbcd17e4b65dfe
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/notes/9.10.19.lean
ceda658f92592ddf211568bff279f6abc60ae892
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
2,934
lean
/- Natural Language: The language that we all speak. Not the language that machines operate using. There is too much ambiguity in natural language. It is not checkable by machines. Formal Language: ex Python, boolean algebra. Well defined language with no ambiguity. Some formal languages are based off of the structure of natural language(ex. cobol) -/ /- General Information for Lean -/ #check 1 /-the check command checks the type of the thing that follows-/ #eval 1 /-evaluates the following. A literal will just evaluate to itself-/ #eval tt /- tt == true, ff == false-/ #eval ff #check tt def n := 1 /-This is known as an identifier-/ /-lean is a functional language so saving a new value to n is not possible. No mutable state-/ -- def n :=2 #eval 1 --outputs 1 def n1 : ℕ := (1 : ℕ) -- natural number symbol is made using \nat def b1 : bool := (tt : bool) --this is the syntax we use when we want lean to --check out types #check λ (b : bool), tt /-b is an input of type bool that always returns true-/ #reduce λ (b : bool), tt /- λ states that what follows is a function-/ #check λ (b : bool), ff #check λ (b : bool), b /-a function that outputs whatever is input as long as it is of type bool-/ #check (λ (b : bool), ff) (tt) /-This is called an application term-/ /-An application term has two parts. The first is the function expression(λ (b : bool), ff). The second is the argument expression(tt)-/ def f : bool → bool := λ (b : bool), ff #eval f ff #eval f tt def neg : bool → bool := λ (b : bool), match b with | ff := tt | tt := ff end /-Predicate Logic Syntax vs Semantics Syntax = grammatical structure Semantics = The meanings of symbol arrangement Terms in Lean Literal: Identifier ("variable"): Lambda("function"): Application(fn applie to arguments): -/ -- Function types #check bool → bool --unary #check bool → bool → bool --binary #check nat → nat --unary #check ℕ → ℕ → ℕ #check ℕ → (ℕ → ℕ) -- arrow rt assoc -- Function Values: lambda abstractions -- take any bool, b; always return ff def always_false : bool → bool := λ b : bool, tt -- take any bool, b; always return b def ident_bool : bool → bool := λ b : bool, b def weed : (bool → bool) → (ℕ → bool) := λ (a : bool → bool), λ( n : ℕ), ff #check (weed always_false) 5 #eval (weed always_false) 5 def inc_by : ℕ → (ℕ → nat) := λ n : ℕ , λ m : ℕ, m +n --this is the same as the inc_by method just in a better form def inc_by' (n m: ℕ ) : ℕ := m + n #check inc_by #check inc_by 3 #check (inc_by 3) 4 #eval (inc_by 3) 4 -- take a bool and return its complement def neg_bool (b: bool) : bool := match b with | ff := tt | tt := ff end
f0753686175269c309c0eb5c6786d11250c70f9c
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/library/data/list/basic.lean
b2b097f3a2d2da36e2799e0252d0007e91ce8a94
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,173
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.list.basic Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura Basic properties of lists. -/ import logic tools.helper_tactics data.nat.basic open eq.ops helper_tactics nat prod function inductive list (T : Type) : Type := | nil {} : list T | cons : T → list T → list T namespace list notation h :: t := cons h t notation `[` l:(foldr `,` (h t, cons h t) nil `]`) := l variable {T : Type} /- append -/ definition append : list T → list T → list T | [] l := l | (h :: s) t := h :: (append s t) notation l₁ ++ l₂ := append l₁ l₂ theorem append_nil_left (t : list T) : [] ++ t = t theorem append_cons (x : T) (s t : list T) : (x::s) ++ t = x::(s ++ t) theorem append_nil_right : ∀ (t : list T), t ++ [] = t | [] := rfl | (a :: l) := calc (a :: l) ++ [] = a :: (l ++ []) : rfl ... = a :: l : append_nil_right l theorem append.assoc : ∀ (s t u : list T), s ++ t ++ u = s ++ (t ++ u) | [] t u := rfl | (a :: l) t u := show a :: (l ++ t ++ u) = (a :: l) ++ (t ++ u), by rewrite (append.assoc l t u) /- length -/ definition length : list T → nat | [] := 0 | (a :: l) := length l + 1 theorem length_nil : length (@nil T) = 0 theorem length_cons (x : T) (t : list T) : length (x::t) = length t + 1 theorem length_append : ∀ (s t : list T), length (s ++ t) = length s + length t | [] t := calc length ([] ++ t) = length t : rfl ... = length [] + length t : zero_add | (a :: s) t := calc length (a :: s ++ t) = length (s ++ t) + 1 : rfl ... = length s + length t + 1 : length_append ... = (length s + 1) + length t : add.succ_left ... = length (a :: s) + length t : rfl -- add_rewrite length_nil length_cons /- concat -/ definition concat : Π (x : T), list T → list T | a [] := [a] | a (b :: l) := b :: concat a l theorem concat_nil (x : T) : concat x [] = [x] theorem concat_cons (x y : T) (l : list T) : concat x (y::l) = y::(concat x l) theorem concat_eq_append (a : T) : ∀ (l : list T), concat a l = l ++ [a] | [] := rfl | (b :: l) := show b :: (concat a l) = (b :: l) ++ (a :: []), by rewrite concat_eq_append -- add_rewrite append_nil append_cons /- reverse -/ definition reverse : list T → list T | [] := [] | (a :: l) := concat a (reverse l) theorem reverse_nil : reverse (@nil T) = [] theorem reverse_cons (x : T) (l : list T) : reverse (x::l) = concat x (reverse l) theorem reverse_singleton (x : T) : reverse [x] = [x] theorem reverse_append : ∀ (s t : list T), reverse (s ++ t) = (reverse t) ++ (reverse s) | [] t2 := calc reverse ([] ++ t2) = reverse t2 : rfl ... = (reverse t2) ++ [] : append_nil_right ... = (reverse t2) ++ (reverse []) : by rewrite reverse_nil | (a2 :: s2) t2 := calc reverse ((a2 :: s2) ++ t2) = concat a2 (reverse (s2 ++ t2)) : rfl ... = concat a2 (reverse t2 ++ reverse s2) : reverse_append ... = (reverse t2 ++ reverse s2) ++ [a2] : concat_eq_append ... = reverse t2 ++ (reverse s2 ++ [a2]) : append.assoc ... = reverse t2 ++ concat a2 (reverse s2) : concat_eq_append ... = reverse t2 ++ reverse (a2 :: s2) : rfl theorem reverse_reverse : ∀ (l : list T), reverse (reverse l) = l | [] := rfl | (a :: l) := calc reverse (reverse (a :: l)) = reverse (concat a (reverse l)) : rfl ... = reverse (reverse l ++ [a]) : concat_eq_append ... = reverse [a] ++ reverse (reverse l) : reverse_append ... = reverse [a] ++ l : reverse_reverse ... = a :: l : rfl theorem concat_eq_reverse_cons (x : T) (l : list T) : concat x l = reverse (x :: reverse l) := calc concat x l = concat x (reverse (reverse l)) : reverse_reverse ... = reverse (x :: reverse l) : rfl /- head and tail -/ definition head [h : inhabited T] : list T → T | [] := arbitrary T | (a :: l) := a theorem head_cons [h : inhabited T] (a : T) (l : list T) : head (a::l) = a theorem head_append [h : inhabited T] (t : list T) : ∀ {s : list T}, s ≠ [] → head (s ++ t) = head s | [] H := absurd rfl H | (a :: s) H := show head (a :: (s ++ t)) = head (a :: s), by rewrite head_cons definition tail : list T → list T | [] := [] | (a :: l) := l theorem tail_nil : tail (@nil T) = [] theorem tail_cons (a : T) (l : list T) : tail (a::l) = l theorem cons_head_tail [h : inhabited T] {l : list T} : l ≠ [] → (head l)::(tail l) = l := list.cases_on l (assume H : [] ≠ [], absurd rfl H) (take x l, assume H : x::l ≠ [], rfl) /- list membership -/ definition mem : T → list T → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l notation e ∈ s := mem e s theorem mem_nil (x : T) : x ∈ [] ↔ false := iff.rfl theorem mem_cons (x : T) (l : list T) : x ∈ x :: l := or.inl rfl theorem mem_cons_iff (x y : T) (l : list T) : x ∈ y::l ↔ (x = y ∨ x ∈ l) := iff.rfl theorem mem_or_mem_of_mem_append {x : T} {s t : list T} : x ∈ s ++ t → x ∈ s ∨ x ∈ t := list.induction_on s or.inr (take y s, assume IH : x ∈ s ++ t → x ∈ s ∨ x ∈ t, assume H1 : x ∈ y::s ++ t, have H2 : x = y ∨ x ∈ s ++ t, from H1, have H3 : x = y ∨ x ∈ s ∨ x ∈ t, from or_of_or_of_imp_right H2 IH, iff.elim_right or.assoc H3) theorem mem_append_of_mem_or_mem {x : T} {s t : list T} : x ∈ s ∨ x ∈ t → x ∈ s ++ t := list.induction_on s (take H, or.elim H false.elim (assume H, H)) (take y s, assume IH : x ∈ s ∨ x ∈ t → x ∈ s ++ t, assume H : x ∈ y::s ∨ x ∈ t, or.elim H (assume H1, or.elim H1 (take H2 : x = y, or.inl H2) (take H2 : x ∈ s, or.inr (IH (or.inl H2)))) (assume H1 : x ∈ t, or.inr (IH (or.inr H1)))) theorem mem_append_iff (x : T) (s t : list T) : x ∈ s ++ t ↔ x ∈ s ∨ x ∈ t := iff.intro mem_or_mem_of_mem_append mem_append_of_mem_or_mem local attribute mem [reducible] local attribute append [reducible] theorem mem_split {x : T} {l : list T} : x ∈ l → ∃s t : list T, l = s ++ (x::t) := list.induction_on l (take H : x ∈ [], false.elim (iff.elim_left !mem_nil H)) (take y l, assume IH : x ∈ l → ∃s t : list T, l = s ++ (x::t), assume H : x ∈ y::l, or.elim H (assume H1 : x = y, exists.intro [] (!exists.intro (H1 ▸ rfl))) (assume H1 : x ∈ l, obtain s (H2 : ∃t : list T, l = s ++ (x::t)), from IH H1, obtain t (H3 : l = s ++ (x::t)), from H2, have H4 : y :: l = (y::s) ++ (x::t), from H3 ▸ rfl, !exists.intro (!exists.intro H4))) definition decidable_mem [instance] [H : decidable_eq T] (x : T) (l : list T) : decidable (x ∈ l) := list.rec_on l (decidable.inr (not_of_iff_false !mem_nil)) (take (h : T) (l : list T) (iH : decidable (x ∈ l)), show decidable (x ∈ h::l), from decidable.rec_on iH (assume Hp : x ∈ l, decidable.rec_on (H x h) (assume Heq : x = h, decidable.inl (or.inl Heq)) (assume Hne : x ≠ h, decidable.inl (or.inr Hp))) (assume Hn : ¬x ∈ l, decidable.rec_on (H x h) (assume Heq : x = h, decidable.inl (or.inl Heq)) (assume Hne : x ≠ h, have H1 : ¬(x = h ∨ x ∈ l), from assume H2 : x = h ∨ x ∈ l, or.elim H2 (assume Heq, absurd Heq Hne) (assume Hp, absurd Hp Hn), have H2 : ¬x ∈ h::l, from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) H1, decidable.inr H2))) theorem mem_of_ne_of_mem {x y : T} {l : list T} (H₁ : x ≠ y) (H₂ : x ∈ y :: l) : x ∈ l := or.elim H₂ (λe, absurd e H₁) (λr, r) definition sublist (l₁ l₂ : list T) := ∀ ⦃a : T⦄, a ∈ l₁ → a ∈ l₂ infix `⊆`:50 := sublist lemma nil_sub (l : list T) : [] ⊆ l := λ b i, false.elim (iff.mp (mem_nil b) i) lemma sub.refl (l : list T) : l ⊆ l := λ b i, i lemma sub.trans {l₁ l₂ l₃ : list T} (H₁ : l₁ ⊆ l₂) (H₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := λ b i, H₂ (H₁ i) lemma sub_cons (a : T) (l : list T) : l ⊆ a::l := λ b i, or.inr i lemma cons_sub_cons {l₁ l₂ : list T} (a : T) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) := λ b Hin, or.elim Hin (λ e : b = a, or.inl e) (λ i : b ∈ l₁, or.inr (s i)) lemma sub_append_left (l₁ l₂ : list T) : l₁ ⊆ l₁++l₂ := λ b i, iff.mp' (mem_append_iff b l₁ l₂) (or.inl i) lemma sub_append_right (l₁ l₂ : list T) : l₂ ⊆ l₁++l₂ := λ b i, iff.mp' (mem_append_iff b l₁ l₂) (or.inr i) /- find -/ section variable [H : decidable_eq T] include H definition find : T → list T → nat | a [] := 0 | a (b :: l) := if a = b then 0 else succ (find a l) theorem find_nil (x : T) : find x [] = 0 theorem find_cons (x y : T) (l : list T) : find x (y::l) = if x = y then 0 else succ (find x l) theorem find.not_mem {l : list T} {x : T} : ¬x ∈ l → find x l = length l := list.rec_on l (assume P₁ : ¬x ∈ [], _) (take y l, assume iH : ¬x ∈ l → find x l = length l, assume P₁ : ¬x ∈ y::l, have P₂ : ¬(x = y ∨ x ∈ l), from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) P₁, have P₃ : ¬x = y ∧ ¬x ∈ l, from (iff.elim_left not_or_iff_not_and_not P₂), calc find x (y::l) = if x = y then 0 else succ (find x l) : !find_cons ... = succ (find x l) : if_neg (and.elim_left P₃) ... = succ (length l) : {iH (and.elim_right P₃)} ... = length (y::l) : !length_cons⁻¹) end /- nth element -/ definition nth [h : inhabited T] : list T → nat → T | [] n := arbitrary T | (a :: l) 0 := a | (a :: l) (n+1) := nth l n theorem nth_zero [h : inhabited T] (a : T) (l : list T) : nth (a :: l) 0 = a theorem nth_succ [h : inhabited T] (a : T) (l : list T) (n : nat) : nth (a::l) (n+1) = nth l n open decidable definition decidable_eq {A : Type} [H : decidable_eq A] : ∀ l₁ l₂ : list A, decidable (l₁ = l₂) | [] [] := inl rfl | [] (b::l₂) := inr (λ H, list.no_confusion H) | (a::l₁) [] := inr (λ H, list.no_confusion H) | (a::l₁) (b::l₂) := match H a b with | inl Hab := match decidable_eq l₁ l₂ with | inl He := inl (eq.rec_on Hab (eq.rec_on He rfl)) | inr Hn := inr (λ H, list.no_confusion H (λ Hab Ht, absurd Ht Hn)) end | inr Hnab := inr (λ H, list.no_confusion H (λ Hab Ht, absurd Hab Hnab)) end section combinators variables {A B C : Type} definition map (f : A → B) : list A → list B | [] := [] | (a :: l) := f a :: map l theorem map_nil (f : A → B) : map f [] = [] theorem map_cons (f : A → B) (a : A) (l : list A) : map f (a :: l) = f a :: map f l theorem map_map (g : B → C) (f : A → B) : ∀ l : list A, map g (map f l) = map (g ∘ f) l | [] := rfl | (a :: l) := show (g ∘ f) a :: map g (map f l) = map (g ∘ f) (a :: l), by rewrite (map_map l) theorem len_map (f : A → B) : ∀ l : list A, length (map f l) = length l | [] := rfl | (a :: l) := show length (map f l) + 1 = length l + 1, by rewrite (len_map l) definition map₂ (f : A → B → C) : list A → list B → list C | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys definition foldl (f : A → B → A) : A → list B → A | a [] := a | a (b :: l) := foldl (f a b) l definition foldr (f : A → B → B) : B → list A → B | b [] := b | b (a :: l) := f a (foldr b l) section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative parameters {α : Type} {f : α → α → α} hypothesis (Hcomm : ∀ a b, f a b = f b a) hypothesis (Hassoc : ∀ a b c, f a (f b c) = f (f a b) c) include Hcomm Hassoc theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := Hcomm a b | a b (c::l) := begin change (foldl f (f (f a b) c) l = f b (foldl f (f a c) l)), rewrite -foldl_eq_of_comm_of_assoc, change (foldl f (f (f a b) c) l = foldl f (f (f a c) b) l), have H₁ : f (f a b) c = f (f a c) b, by rewrite [-Hassoc, -Hassoc, Hcomm b c], rewrite H₁ end theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := begin rewrite foldl_eq_of_comm_of_assoc, esimp, change (f b (foldl f a l) = f b (foldr f a l)), rewrite foldl_eq_foldr end end foldl_eq_foldr definition all (p : A → Prop) (l : list A) : Prop := foldr (λ a r, p a ∧ r) true l definition any (p : A → Prop) (l : list A) : Prop := foldr (λ a r, p a ∨ r) false l definition decidable_all (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (all p l) | [] := decidable_true | (a :: l) := match H a with | inl Hp₁ := match decidable_all l with | inl Hp₂ := inl (and.intro Hp₁ Hp₂) | inr Hn₂ := inr (not_and_of_not_right (p a) Hn₂) end | inr Hn := inr (not_and_of_not_left (all p l) Hn) end definition decidable_any (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (any p l) | [] := decidable_false | (a :: l) := match H a with | inl Hp := inl (or.inl Hp) | inr Hn₁ := match decidable_any l with | inl Hp₂ := inl (or.inr Hp₂) | inr Hn₂ := inr (not_or Hn₁ Hn₂) end end definition zip (l₁ : list A) (l₂ : list B) : list (A × B) := map₂ (λ a b, (a, b)) l₁ l₂ definition unzip : list (A × B) → list A × list B | [] := ([], []) | ((a, b) :: l) := match unzip l with | (la, lb) := (a :: la, b :: lb) end theorem unzip_nil : unzip (@nil (A × B)) = ([], []) theorem unzip_cons (a : A) (b : B) (l : list (A × B)) : unzip ((a, b) :: l) = match unzip l with (la, lb) := (a :: la, b :: lb) end theorem zip_unzip : ∀ (l : list (A × B)), zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l | [] := rfl | ((a, b) :: l) := begin rewrite unzip_cons, have r : zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l, from zip_unzip l, revert r, apply (prod.cases_on (unzip l)), intros [la, lb, r], rewrite -r end end combinators /- flat -/ variable {A : Type} definition flat (l : list (list A)) : list A := foldl append nil l end list attribute list.decidable_eq [instance] attribute list.decidable_mem [instance] attribute list.decidable_any [instance] attribute list.decidable_all [instance]
0753d2323ebdcdcaeb03247d3b82e4c5e8face89
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0202.lean
2c81f3b5b4e88841d8a1fa4b6f309ef7dd7fee09
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
166
lean
constants α β : Type constant F : Type → Type constant G : Type → Type → Type #check α #check F α #check F nat #check G α #check G α β #check G α nat
135e8910719cd16434d919a0cf9a02ade3c3041c
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/Tactic/Calc.lean
245984a90503df1bbecb1a71fb23882df5bc4f05
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
1,824
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Calc import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic open Meta def elabCalcSteps (steps : Array Syntax) : TacticM Expr := do /- If error recovery is disabled, we disable `Term.withoutErrToSorry` -/ if (← read).recover then go else Term.withoutErrToSorry go where go : TermElabM Expr := do let e ← Term.elabCalcSteps steps Term.synthesizeSyntheticMVars (mayPostpone := false) instantiateMVars e /-- Elaborator for the `calc` tactic mode variant. -/ @[builtin_tactic calcTactic] def evalCalc : Tactic := fun stx => do withMainContext do let steps := #[stx[1]] ++ stx[2].getArgs let (val, mvarIds) ← withCollectingNewGoalsFrom (tagSuffix := `calc) do let val ← elabCalcSteps steps let valType ← inferType val let target ← getMainTarget if (← isDefEq valType target) then return val else let throwFailed {α} : TacticM α := throwError "'calc' tactic failed, has type{indentExpr valType}\nbut it is expected to have type{indentExpr target}" let some (_, _, rhs) ← Term.getCalcRelation? valType | throwFailed let some (r, _, rhs') ← Term.getCalcRelation? target | throwFailed let lastStep := mkApp2 r rhs rhs' let lastStepGoal ← mkFreshExprSyntheticOpaqueMVar lastStep (tag := (← getMainTag) ++ `calc.step) let (val, valType) ← Term.mkCalcTrans val valType lastStepGoal lastStep unless (← isDefEq valType target) do throwFailed return val let val ← instantiateMVars val let mvarId ← getMainGoal mvarId.assign val replaceMainGoal mvarIds
0c6fec87fbdfe1185def233509f8fd88a8681211
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/HW/hw2_a_few_easy_pieces.lean
c3585b4dc01d99de942bb98469f384b99d01e73d
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
5,654
lean
/- UVa CS Discrete Math (Sullivan) Homework #2 -/ /- Note: We distribute homework assignments and even exams as Lean files, as we do now for this assignment. You will answer the questions in one of two ways: by writing an answer in a comment block (such as this one), or by writing mathematical logic (which is what "Lean code" is). For this assignment you will write all your answers as simple comments. -/ /- This assignment has three questions, each with several parts. Be sure to read and answer all parts of all of the questions. Make a copy of this file in your "mywork" directory the read and answer the questions by editing this fie. When you are done, *save it*, then upload it to Collab. That is how you will submit work in this class. Be sure to double check your submission to be sure you uploaded the right file. -/ /- QUESTION #1 (7 Parts, A - G) A. How many functions are there that take one argument of type Boolean (one bit, if you prefer) and that return one value, also of type Boolean? Hint: We discussed this in class. Answer here (inside this comment block): 4 B. How many functions are there that take two arguments of type Boolean and that return one value of type Boolean? Hint: we discussed this in class, too. Answer here: 16 C. How many functions are there that take three bits of input and that return a one bit result? Hint: We discussed this, too. Answer here: 256 D. Give a general formula that you believe to be valid describing the number of functions that take n bits, for any natural number, n, and that return one bit. Use the ^ character to represent exponentiation. Answer:(2^(n))^2 E. How many functions are there that take three bits of input and that return *two* bits as a result? Hint: think about both how many possible combinations of input bits there are. To define a function, you need to specify which two-bit return value is associated with each combination of input values. The number of functions will be the number of ways in which you can assign output values for each combination of input values. Give your answer in a form that involves 3 (inputs) and 2 (output bits). Answer here: 4096 F. How many functions are there that take 64 bits of input and return a 64 bit result? Give your answer as an algebraic expression. The number is too big to write it out explicitly. Answer here: (2^(64))^(2^(64)) G. How many functions are there that take n bits of input and return m bits of output, where n and m are natural numbers? Give an algebraic expression as your answer, involving the variables m and n. Answer here: (2^n)^(2^m) -/ /- QUESTION #2 (Three parts, A - C) Suppose you are asked to write a program, P(x), taking one argument, x, a "natural number", and that it must satisfy a specification, S(x), that defines a function in a pure functional programming language. A. Using simple English to express your answer, what proposition that must be true for P to be accepted as a correct implementation of S. Hint: We discussed this in class. Answer: P must satisfy specification s for every possible value of x. B. Why is testing alone generally inadequate to prove pthe correctness of such a program, P? Answer: There are often too many testing variations to prove by testing alone C. What kind of mathematical "thing" would be needed to show beyond a reasonable doubt that P satisfies S? You can give a one-word answer. Answer: proof -/ /- QUESTION #3 (Four parts, A - D) Consider a new data type, cool, that has three possible values: true (T), false (F), and don't know (D). And now consider the following conjecture: For any natural number, n, the number of combinations of values of n variables of type cool is 3^n. Give a proof of this conjecture by induction. A. What is the first conjecture you must prove? Hint: substitute a specific value for n into the conjecture and rewrite it with that value in place of n. Answer: You have to prove the base case. In our situation that would be n=0. When n = 0, the number of combinations should be 1. If we plug 0 into the equation 3^n we get the value 1 out. The base case is established. B. Prove it. Hint: One approach to proving that two terms are equal is simply to reduce each term to its simplest form, and then show that the reduced terms are exactly the same. In other words, just simplify the expressions on each side of an equals to to show that the values are identical. Answer here: We know that in mathematics the number of variations of zero variables is 1. If we have n = 0, the number of variables should be 1. When we plug n = 0 into 3^n it evaluates to 1. We can see that our base case meets our expected output. C. What is the second conjecture that you must prove to complete your proof by induction? Answer here: If the states of n variables is 3^n then the states of (n+1) is equal to 3^(n+1). In simpler terms, adding another variable should increase the number of possible combinations by 3 times. D. Prove it. Hint, to prove a proposition of the form, P → Q, or P implies Q, you start by *assuming* that P is true (whatever proposition it happens to be), and then you show that in the context of this assumption, that proposition Q must be true. In other words, you want to prove that IF P is true THEN Q must be true, too. Answer here: If we assume that 3^n equals the number of combinations, then it must be true for 3^(n+1). 3^(n+1) is equal to (3^n)*3. We can use use another example in which we know the expected output to demonstrate this. The combinations with 1 variable should be 3. 3^(1) = 3^(0)*3, 3^(0)=1, therefore, 3^1 = 3. -/
190e042f38e948e0c2d6aa5c8cf42a84898c8d16
d1bbf1801b3dcb214451d48214589f511061da63
/src/ring_theory/polynomial/cyclotomic.lean
2902bc4b3a5e2aec818ddaa7af10aad04b274b20
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,850
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Riccardo Brasca -/ import field_theory.splitting_field import ring_theory.roots_of_unity import algebra.polynomial.big_operators import number_theory.arithmetic_function import data.polynomial.lifts import analysis.complex.roots_of_unity import field_theory.separable /-! # Cyclotomic polynomials. For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. * `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for `cyclotomic n R` over an abstract fraction field for `polynomial R`. * `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is `R = ℂ`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `minpoly_primitive_root_eq_cyclotomic` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ open_locale classical big_operators noncomputable theory universe u namespace polynomial section cyclotomic' section integral_domain variables {R : Type*} [integral_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : ℕ) (R : Type*) [integral_domain R] : polynomial R := ∏ μ in primitive_roots n R, (X - C μ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [integral_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [integral_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [integral_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : ℕ) (R : Type*) [integral_domain R] : cyclotomic' n R ≠ 0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, cyclotomic'_zero, nat.totient_zero, nat_degree_one] }, rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h hpos, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } end integral_domain section field variables {K : Type*} [field K] /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : X ^ n - 1 = ∏ ζ in nth_roots_finset n K, (X - C ζ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : K)).monic := monic_X_pow_sub_C (1 : K) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C K _ _ n hpos 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := begin by_cases hzero : n = 0, { simp only [hzero, ring_hom.map_one, splits_zero, pow_zero, sub_self] }, rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C], exact nat.pos_of_ne_zero hzero end /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bind, { simp only [is_primitive_root.nth_roots_one_eq_bind_primitive_roots hpos h] }, intros x hx y hy hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hx hy, refine is_primitive_root.disjoint _ _ hdiff, { exact @nat.pos_of_mem_divisors n x (nat.mem_divisors.2 hx) }, { exact @nat.pos_of_mem_divisors n y (nat.mem_divisors.2 hy) } end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {ζ : K} {n : ℕ} (hpos: 0 < n) (h : is_primitive_root ζ n) : cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : (∃ (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), revert h ζ, apply nat.strong_induction_on n, intros k hk z hzeta, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_one, ring_hom.coe_of, and_self], }, by_cases hone : k = 1, { use X - 1, simp only [hone, cyclotomic'_one K, set.mem_univ, pnat.one_coe, subsemiring.coe_top, eq_self_iff_true, map_X, map_one, ring_hom.coe_of, and_self, map_sub] }, let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos hzeta hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : polynomial ℤ := (X ^ k - 1) /ₘ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos hzeta), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq, simp only [lifts, ring_hom.coe_of, ring_hom.mem_srange], use Q₁, rw [(map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) : (∃! (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic h, rw exists_unique, use [P, hP.1], intros Q hQ, have mapinj : function.injective (map (int.cast_ring_hom K)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, rw [function.injective] at mapinj, apply mapinj, rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : ℕ) (R : Type*) [ring R] : polynomial R := if h : n = 0 then 1 else map (int.cast_ring_hom R) (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) : cyclotomic n ℤ = (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/ lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧ (cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, map_one, and_self] }, rw int_cyclotomic_rw hzero, exact classical.some_spec (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n hzero)) end lemma int_cyclotomic_unique {n : ℕ} {P : polynomial ℤ} (h : map (int.cast_ring_hom ℂ) P = cyclotomic' n ℂ) : P = cyclotomic n ℤ := begin have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ, { simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, map_one, map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ, { simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, map_add, map_X, map_one] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_add, map_X, map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, apply monic_map, exact (int_cyclotomic_spec n).2.2 end /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 := monic.ne_zero (cyclotomic.monic n R) /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, norm_cast at hdeg, exact hdeg end /-- The degree of `cyclotomic n R` is positive. -/ lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] : 0 < (cyclotomic n R).degree := by { rw degree_cyclotomic n R; exact_mod_cast (nat.totient_pos hpos) } /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1, { have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ), simp only [int_cyclotomic_spec, map_pow, nat.cast_id, map_X, map_one, ring_hom.coe_of, map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [map_pow, map_X, map_one, map_sub] }, have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R) (λ i, cyclotomic i ℤ), integer] end section arithmetic_function open nat.arithmetic_function open_locale arithmetic_function /-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R` using Möbius inversion. -/ lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] [nontrivial R] {K : Type*} [field K] (f : fraction_map (polynomial R) K) : f.to_map (cyclotomic n R) = ∏ i in n.divisors_antidiagonal, (f.to_map (X ^ i.snd - 1)) ^ μ i.fst := begin have h : ∀ (n : ℕ), 0 < n → ∏ i in nat.divisors n, f.to_map (cyclotomic i R) = f.to_map (X ^ n - 1), { intros n hn, rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] }, rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos; rw [ne.def, fraction_map.to_map_eq_zero_iff], { apply cyclotomic_ne_zero }, { apply monic.ne_zero, apply monic_X_pow_sub_C _ (ne_of_gt hn) } end end arithmetic_function /-- We have `cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides `∏ i in nat.proper_divisors n, cyclotomic i R`. -/ lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n) (hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R := begin replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2 ⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩, rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm (nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)), finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one (nat.pos_of_mem_proper_divisors hm)], exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩ end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [field K] {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) := begin rw ←cyclotomic', revert h ζ, apply nat.strong_induction_on n, intros k hk z hz, cases nat.eq_zero_or_pos k with hzero hpos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ (field.to_nontrivial K) _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end /-- Any `n`-th primitive root of unity is a root of `cyclotomic n ℤ`.-/ lemma is_root_cyclotomic {n : ℕ} {K : Type*} [field K] (hpos : 0 < n) {μ : K} (h : is_primitive_root μ n) : is_root (cyclotomic n K) μ := begin rw [← mem_roots (cyclotomic_ne_zero n K), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ} (hpos: 0 < n) (P : polynomial R) : P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 := begin split, { intro hcycl, rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n), ← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], exact prod_cyclotomic_eq_X_pow_sub_one hpos R }, { intro hP, have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ _ hpos, (div_mod_by_monic_unique P 0 prod_monic _).1], split, { rwa [zero_add, mul_comm] }, rw [degree_zero, bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) }, end /-- If `p` is prime, then `cyclotomic p R = geom_series X p`. -/ lemma cyclotomic_eq_geom_series {R : Type*} [comm_ring R] [nontrivial R] {p : ℕ} (hp : nat.prime p) : cyclotomic p R = geom_series X p := begin symmetry, refine (eq_cyclotomic_iff hp.pos _).mpr _, simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one], end /-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/ lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) : (cyclotomic n R).coeff 0 = 1 := begin induction n using nat.strong_induction_on with n hi, have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1, { rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2 (lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _), cyclotomic_one R], have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j, { intros j hj, apply nat.succ_le_of_lt, exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp (nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) }, have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1, { intros j hj, exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) }, have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1, { rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr, simp only [finset.prod_const_one] }, simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] }, have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0, { rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn), nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn), finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod, mul_neg_eq_neg_mul_symm, mul_one] }, have hzero : (X ^ n - 1).coeff 0 = (-1 : R), { rw coeff_zero_eq_eval_zero _, simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow, eval_sub] }, rw hzero at heq, exact neg_inj.mp (eq.symm heq) end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are coprime. -/ lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : a.coprime p := begin apply nat.coprime.symm, rw [nat.prime.coprime_iff_not_dvd hprime], by_contra h, replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h, rw [is_root.def, ring_hom.eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot, by_cases hone : n = 1, { simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero, one_ne_zero, coeff_sub] at hroot, exact hroot }, rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne (nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot, exact one_ne_zero hroot end end cyclotomic section order /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo `p` divides `n`. -/ lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n := begin apply order_of_dvd_of_pow_eq_one, suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : polynomial (zmod p)) = 0, { simp only [eval_X, eval_one, eval_pow, eval_sub, ring_hom.eq_nat_cast] at hpow, apply units.coe_eq_one.1, simp only [sub_eq_zero.mp hpow, zmod.cast_unit_of_coprime, units.coe_pow] }, rw [is_root.def] at hroot, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul] end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime that does not divide `n`, then the multiplicative order of `a` modulo `p` is exactly `n`. -/ lemma order_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hn : ¬ p ∣ n) (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) = n := begin set m := order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)), have ha := coprime_of_root_cyclotomic hpos hroot, have hdivcycl : map (int.cast_ring_hom (zmod p)) (X - a) ∣ (cyclotomic n (zmod p)), { replace hrootdiv := dvd_iff_is_root.2 hroot, simp only [C_eq_nat_cast, ring_hom.eq_nat_cast] at hrootdiv, simp only [hrootdiv, map_nat_cast, map_X, map_sub] }, by_contra hdiff, have hdiv : map (int.cast_ring_hom (zmod p)) (X - a) ∣ ∏ i in nat.proper_divisors n, cyclotomic i (zmod p), { suffices hdivm : map (int.cast_ring_hom (zmod p)) (X - a) ∣ X ^ m - 1, { exact dvd_trans hdivm (X_pow_sub_one_dvd_prod_cyclotomic (zmod p) hpos (order_of_root_cyclotomic_dvd hpos hroot) hdiff) }, rw [map_sub, map_X, map_nat_cast, ← C_eq_nat_cast, dvd_iff_is_root, is_root.def, eval_sub, eval_pow, eval_one, eval_X, sub_eq_zero, ← zmod.cast_unit_of_coprime a ha, ← units.coe_pow, units.coe_eq_one], exact pow_order_of_eq_one (zmod.unit_of_coprime a ha) }, have habs : (map (int.cast_ring_hom (zmod p)) (X - a)) ^ 2 ∣ X ^ n - 1, { obtain ⟨P, hP⟩ := hdivcycl, obtain ⟨Q, hQ⟩ := hdiv, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, hP, hQ], exact ⟨P * Q, by ring⟩ }, have hnzero : ↑n ≠ (0 : (zmod p)), { intro ha, exact hn (int.coe_nat_dvd.1 ((zmod.int_coe_zmod_eq_zero_iff_dvd n p).1 ha)) }, rw [pow_two] at habs, replace habs := squarefree_X_pow_sub_C (1 : (zmod p)) hnzero one_ne_zero (map (int.cast_ring_hom (zmod p)) (X - a)) habs, simp only [map_nat_cast, map_X, map_sub] at habs, replace habs := degree_eq_zero_of_is_unit habs, rw [← C_eq_nat_cast, degree_X_sub_C] at habs, norm_cast at habs end end order end polynomial section minimial_polynomial open is_primitive_root polynomial complex /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ lemma minpoly_primitive_root_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : minpoly (is_integral h hpos) ∣ cyclotomic n ℤ := begin apply minpoly.integer_dvd (is_integral h hpos) (cyclotomic.monic n ℤ).is_primitive, simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h end /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma minpoly_primitive_root_eq_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℤ = minpoly (is_integral h hpos) := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n ℤ) (minpoly_primitive_root_dvd_cyclotomic h hpos) _, simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h hpos end /-- `cyclotomic n ℤ` is irreducible. -/ lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) := begin have h0 := (ne_of_lt hpos).symm, rw [minpoly_primitive_root_eq_cyclotomic (is_primitive_root_exp n h0) hpos], exact minpoly.irreducible (is_integral (is_primitive_root_exp n h0) hpos) end end minimial_polynomial
c5202e38d69f0fd5e360cf979e5fda8b660aa187
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/zmod/basic.lean
172ce32ee76e77ad2a793a21797a6f2f8faed10e
[ "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,786
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq import algebra.char_p import data.nat.totient import ring_theory.ideal.operations /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat nat.modeq int /-- Negation on `fin n` -/ def has_neg (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, begin have npos : 0 < n := lt_of_le_of_lt (nat.zero_le _) a.2, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 npos, have := int.mod_lt (-(a.1 : ℤ)) h, rw [(abs_of_nonneg (int.coe_nat_nonneg n))] at this, rwa [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)] end⟩⟩ /-- Additive commutative semigroup structure on `fin (n+1)`. -/ def add_comm_semigroup (n : ℕ) : add_comm_semigroup (fin (n+1)) := { add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % (n+1) + c) ≡ (a + (b + c) % (n+1)) [MOD (n+1)], from calc ((a + b) % (n+1) + c) ≡ a + b + c [MOD (n+1)] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD (n+1)] : by rw add_assoc ... ≡ (a + (b + c) % (n+1)) [MOD (n+1)] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % (n+1) = (b + a) % (n+1), by rw add_comm), ..fin.has_add } /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ def comm_semigroup (n : ℕ) : comm_semigroup (fin (n+1)) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc ... ≡ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm), ..fin.has_mul } local attribute [instance] fin.add_comm_semigroup fin.comm_semigroup private lemma one_mul_aux (n : ℕ) (a : fin (n+1)) : (1 : fin (n+1)) * a = a := begin cases n with n, { exact subsingleton.elim _ _ }, { have h₁ : (a : ℕ) % n.succ.succ = a := nat.mod_eq_of_lt a.2, apply fin.ext, simp only [coe_mul, coe_one, h₁, one_mul], } end private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add ... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) /-- Commutative ring structure on `fin (n+1)`. -/ def comm_ring (n : ℕ) : comm_ring (fin (n+1)) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % (n+1) = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % (n+1)).to_nat + a) % (n+1) = 0, from int.coe_nat_inj begin have npos : 0 < n+1 := lt_of_le_of_lt (nat.zero_le _) ha, have hn : ((n+1) : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 npos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.has_zero, ..fin.has_one, ..fin.has_neg (n+1), ..fin.add_comm_semigroup n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type | 0 := ℤ | (n+1) := fin (n+1) namespace zmod instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n) | 0 _ := false.elim $ nat.not_lt_zero 0 ‹0 < 0› | (n+1) _ := fin.fintype (n+1) lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { exact fintype.card_fin (n+1) } end instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance has_repr : Π (n : ℕ), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ instance comm_ring : Π (n : ℕ), comm_ring (zmod n) | 0 := int.comm_ring | (n+1) := fin.comm_ring n instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩ /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val : Π {n : ℕ}, zmod n → ℕ | 0 := int.nat_abs | (n+1) := (coe : fin (n + 1) → ℕ) lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, exact fin.is_lt a end @[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0 | 0 := rfl | (n+1) := rfl lemma val_cast_nat {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n := begin casesI n, { rw [nat.mod_zero, int.nat_cast_eq_coe_nat], exact int.nat_abs_of_nat a, }, rw ← fin.of_nat_eq_coe, refl end instance (n : ℕ) : char_p (zmod n) n := { cast_eq_zero_iff := begin intro k, cases n, { simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], }, rw [fin.eq_iff_veq], show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _, rw [val_cast_nat, val_zero, nat.dvd_iff_mod_eq_zero], end } @[simp] lemma cast_self (n : ℕ) : (n : zmod n) = 0 := char_p.cast_eq_zero (zmod n) n @[simp] lemma cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 := by rw [← nat.cast_add_one, cast_self (n + 1)] section universal_property variables {n : ℕ} {R : Type*} section variables [has_zero R] [has_one R] [has_add R] [has_neg R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast : Π {n : ℕ}, zmod n → R | 0 := int.cast | (n+1) := λ i, i.val -- see Note [coercion into rings] @[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩ @[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 := by { cases n; refl } end lemma nat_cast_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) := begin assume i, casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { change fin (n + 1) at i, refine ⟨i, _⟩, rw [fin.ext_iff, fin.coe_coe_eq_self] } end lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) := begin assume i, cases n, { exact ⟨i, int.cast_id i⟩ }, { rcases nat_cast_surjective i with ⟨k, rfl⟩, refine ⟨k, _⟩, norm_cast } end lemma cast_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a := begin rcases nat_cast_surjective a with ⟨k, rfl⟩, symmetry, rw [val_cast_nat, ← sub_eq_zero, ← nat.cast_sub, char_p.cast_eq_zero_iff (zmod n) n], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end @[simp, norm_cast] lemma cast_id : ∀ n (i : zmod n), ↑i = i | 0 i := int.cast_id i | (n+1) i := cast_val i variables [ring R] @[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, refl end section char_dvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variables {n} {m : ℕ} [char_p R m] @[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 := begin casesI n, { exact int.cast_one }, show ((1 % (n+1) : ℕ) : R) = 1, cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim }, rw nat.mod_eq_of_lt, { exact nat.cast_one }, exact nat.lt_of_sub_eq_succ rfl end lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b := begin casesI n, { apply int.cast_add }, simp only [coe_coe], symmetry, erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b := begin casesI n, { apply int.cast_mul }, simp only [coe_coe], symmetry, erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/ def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R := { to_fun := coe, map_zero' := cast_zero, map_one' := cast_one h, map_add' := cast_add h, map_mul' := cast_mul h } @[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl @[simp, norm_cast] lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b := (cast_hom h R).map_sub a b @[simp, norm_cast] lemma cast_neg (h : m ∣ n) (a : zmod n) : ((-a : zmod n) : R) = -a := (cast_hom h R).map_neg a @[simp, norm_cast] lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := (cast_hom h R).map_pow a k @[simp, norm_cast] lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k := (cast_hom h R).map_nat_cast k @[simp, norm_cast] lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k := (cast_hom h R).map_int_cast k end char_dvd section char_eq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [char_p R n] @[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 := cast_one (dvd_refl _) @[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b := cast_add (dvd_refl _) a b @[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b := cast_mul (dvd_refl _) a b @[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b := cast_sub (dvd_refl _) a b @[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := cast_pow (dvd_refl _) a k @[simp, norm_cast] lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k := cast_nat_cast (dvd_refl _) k @[simp, norm_cast] lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k := cast_int_cast (dvd_refl _) k variables (R) lemma cast_hom_injective : function.injective (zmod.cast_hom (dvd_refl n) R) := begin rw ring_hom.injective_iff, intro x, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective x, rw [ring_hom.map_int_cast, char_p.int_cast_eq_zero_iff R n, char_p.int_cast_eq_zero_iff (zmod n) n], exact id end lemma cast_hom_bijective [fintype R] (h : fintype.card R = n) : function.bijective (zmod.cast_hom (dvd_refl n) R) := begin haveI : fact (0 < n) := begin rw [nat.pos_iff_ne_zero], unfreezingI { rintro rfl }, exact fintype.card_eq_zero_iff.mp h 0 end, rw [fintype.bijective_iff_injective_and_card, zmod.card, h, eq_self_iff_true, and_true], apply zmod.cast_hom_injective end /-- The unique ring isomorphism between `zmod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ noncomputable def ring_equiv [fintype R] (h : fintype.card R = n) : zmod n ≃+* R := ring_equiv.of_bijective _ (zmod.cast_hom_bijective R h) end char_eq end universal_property lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] := char_p.int_coe_eq_int_coe_iff (zmod c) c a b lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] := begin convert zmod.int_coe_eq_int_coe_iff a b c, simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd], end lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a := begin change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a, rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff], end lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a := begin change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a, rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff], end @[push_cast, simp] lemma cast_mod_int (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) := begin rw zmod.int_coe_eq_int_coe_iff, apply int.modeq.mod_modeq, end @[simp] lemma coe_to_nat (p : ℕ) : ∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z | (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat] | -[1+n] h := false.elim h lemma val_injective (n : ℕ) [fact (0 < n)] : function.injective (zmod.val : zmod n → ℕ) := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹_› }, assume a b h, ext, exact h end lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n := by rw [← nat.cast_one, val_cast_nat] lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 := by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt ‹1 < n› } lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { apply fin.val_add } end lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n := begin cases n, { rw nat.mod_zero, apply int.nat_abs_mul }, { apply fin.val_mul } end instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) := ⟨⟨0, 1, assume h, zero_ne_one $ calc 0 = (0 : zmod n).val : by rw val_zero ... = (1 : zmod n).val : congr_arg zmod.val h ... = 1 : val_one n ⟩⟩ /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : Π (n : ℕ), zmod n → zmod n | 0 i := int.sign i | (n+1) i := nat.gcd_a i.val (n+1) instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩ lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0 | 0 := int.sign_zero | (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0, by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl } lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * a⁻¹ = nat.gcd a.val n := begin cases n, { calc a * a⁻¹ = a * int.sign a : rfl ... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat] ... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl }, { set k := n.succ, calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [cast_self, zero_mul, add_zero] ... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) : by { push_cast, rw cast_val, refl } ... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, } end @[simp] lemma cast_mod_nat (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := begin cases n, { simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], }, { rw [fin.ext_iff, nat.modeq, ← val_cast_nat, ← val_cast_nat], exact iff.rfl, } end lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (x * x⁻¹ : zmod n) = 1 := begin rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h, rw [mul_inv_eq_gcd, val_cast_nat, h, nat.cast_one], end /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] lemma cast_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (u : zmod n).val n := begin cases n, { rcases int.units_eq_one_or u with rfl|rfl; exact dec_trivial }, apply nat.modeq.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val, have := units.ext_iff.1 (mul_right_inv u), rw [units.coe_one] at this, rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this, rw [← cast_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))], rw [units.coe_mul, val_mul, cast_mod_nat], end @[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) : (u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) := begin have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u), rw [← mul_inv_eq_gcd, nat.cast_one] at this, let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩, have h : u = u', { apply units.ext, refl }, rw h, refl end lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * a⁻¹ = 1 := begin rcases h with ⟨u, rfl⟩, rw [inv_coe_unit, u.mul_inv], end lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} := { to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩, inv_fun := λ x, unit_of_coprime x.1.val x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (cast_val _), right_inv := λ ⟨_, _⟩, by simp } section totient open_locale nat @[simp] lemma card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = φ n := calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} }, { intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_cast_nat, nat.mod_eq_of_lt hb.1], } } end end totient instance subsingleton_units : subsingleton (units (zmod 2)) := ⟨λ x y, begin cases x with x xi, cases y with y yi, revert x y xi yi, exact dec_trivial end⟩ lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val := begin haveI npos : fact (0 < n) := by { apply (nat.eq_zero_or_pos n).resolve_left, unfreezingI { rintro rfl }, simpa [fact] using hn, }, have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, { conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos]}, rw [← nat.two_mul_odd_div_two hn, two_mul, ← nat.succ_add, nat.add_sub_cancel], }, have hxn : (n : ℕ) - x.val < n, { rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self], rw ← zmod.cast_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) }, by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self, ← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.val_lt), zmod.val_cast_nat, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] } end lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha, by rwa [← h, ← not_lt, not_iff_self] at this lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] : (-1 : zmod n) ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := begin cases a, { simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] }, { simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] } end @[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0 | 0 a := int.nat_abs_eq_zero | (n+1) a := by { rw fin.ext_iff, exact iff.rfl } lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_cast_nat, nat.mod_eq_of_lt h] lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n := begin have : ((-a).val + a.val) % n = (n - a.val + a.val) % n, { rw [←val_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], }, calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt) ... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this end lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val := begin rw neg_val', by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] }, rw if_neg h, apply nat.mod_eq_of_lt, apply nat.sub_lt ‹0 < n›, contrapose! h, rwa [nat.le_zero_iff, val_eq_zero] at h, end /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs : Π {n : ℕ}, zmod n → ℤ | 0 x := x | n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n @[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refl } end @[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x | 0 x := int.cast_id x | k@(n+1) x := begin rw val_min_abs_def_pos, split_ifs, { rw [int.cast_coe_nat, cast_val] }, { rw [int.cast_sub, int.cast_coe_nat, cast_val, int.cast_coe_nat, cast_self, sub_zero], } end lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := begin rw zmod.val_min_abs_def_pos, split_ifs with h, { exact h }, have : (x.val - n : ℤ) ≤ 0, { rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, }, rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x), { rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring }, norm_cast, calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _ ... ≤ x.val : by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) } end @[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0 | 0 := by simp only [val_min_abs_def_zero] | (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero] @[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := begin cases n, { simp }, split, { simp only [val_min_abs_def_pos, int.coe_nat_succ], split_ifs with h h; assume h0, { apply val_injective, rwa [int.coe_nat_eq_zero] at h0, }, { apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } }, { rintro rfl, rw val_min_abs_zero } end lemma cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := begin have : (a.val : ℤ) - n ≤ 0, by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, }, rw [zmod.val_min_abs_def_pos], split_ifs, { rw [int.nat_abs_of_nat, cast_val] }, { rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub], rw [int.cast_coe_nat, int.cast_coe_nat, cast_self, sub_zero, cast_val], } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := begin cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], }, by_cases ha0 : a = 0, { rw [ha0, neg_zero] }, by_cases haa : -a = a, { rw [haa] }, suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, { rw [val_min_abs_def_pos, val_min_abs_def_pos], rw ← not_le at hpa, simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)], split_ifs, all_goals { rw [← int.nat_abs_neg], congr' 1, ring } }, suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a, by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this], cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { assume h, apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h), contrapose! haa, rw [← zmod.cast_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add], rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)], rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] } lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) : (q : zmod p) ≠ 0 := by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, nat.coprime_primes hp hq] end zmod namespace zmod variables (p : ℕ) [fact p.prime] private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 := begin obtain ⟨k, rfl⟩ := nat_cast_surjective a, apply coe_mul_inv_eq_one, apply nat.coprime.symm, rwa [nat.prime.coprime_iff_not_dvd ‹p.prime›, ← char_p.cast_eq_zero_iff (zmod p)] end /-- Field structure on `zmod p` if `p` is prime. -/ instance : field (zmod p) := { mul_inv_cancel := mul_inv_cancel_aux p, inv_zero := inv_zero p, .. zmod.comm_ring p, .. zmod.has_inv p, .. zmod.nontrivial p } end zmod lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g := begin ext a, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a, let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)), show φ k = ψ k, rw φ.ext_int ψ, end namespace zmod variables {n : ℕ} {R : Type*} instance subsingleton_ring_hom [semiring R] : subsingleton ((zmod n) →+* R) := ⟨ring_hom.ext_zmod⟩ instance subsingleton_ring_equiv [semiring R] : subsingleton (zmod n ≃+* R) := ⟨λ f g, by { rw ring_equiv.coe_ring_hom_inj_iff, apply ring_hom.ext_zmod _ _ }⟩ lemma ring_hom_surjective [ring R] (f : R →+* (zmod n)) : function.surjective f := begin intros k, rcases zmod.int_cast_surjective k with ⟨n, rfl⟩, refine ⟨n, f.map_int_cast n⟩ end lemma ring_hom_eq_of_ker_eq [comm_ring R] (f g : R →+* (zmod n)) (h : f.ker = g.ker) : f = g := by rw [← f.lift_of_surjective_comp (zmod.ring_hom_surjective f) g (le_of_eq h), ring_hom.ext_zmod (f.lift_of_surjective _ _ _) (ring_hom.id _), ring_hom.id_comp] end zmod
e9091cd752af86de093a36bf0134d904e924289e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/omega_complete_partial_order.lean
785f8bcaf346be61bb2e9bede68a6e3f40e28ee8
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,772
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import topology.basic import order.omega_complete_partial_order /-! # Scott Topological Spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A type of topological spaces whose notion of continuity is equivalent to continuity in ωCPOs. ## Reference * https://ncatlab.org/nlab/show/Scott+topology -/ open set omega_complete_partial_order open_locale classical universes u namespace Scott /-- `x` is an `ω`-Sup of a chain `c` if it is the least upper bound of the range of `c`. -/ def is_ωSup {α : Type u} [preorder α] (c : chain α) (x : α) : Prop := (∀ i, c i ≤ x) ∧ (∀ y, (∀ i, c i ≤ y) → x ≤ y) lemma is_ωSup_iff_is_lub {α : Type u} [preorder α] {c : chain α} {x : α} : is_ωSup c x ↔ is_lub (range c) x := by simp [is_ωSup, is_lub, is_least, upper_bounds, lower_bounds] variables (α : Type u) [omega_complete_partial_order α] /-- The characteristic function of open sets is monotone and preserves the limits of chains. -/ def is_open (s : set α) : Prop := continuous' (λ x, x ∈ s) theorem is_open_univ : is_open α univ := ⟨λ x y h hx, mem_univ _, @complete_lattice.top_continuous α Prop _ _⟩ theorem is_open.inter (s t : set α) : is_open α s → is_open α t → is_open α (s ∩ t) := complete_lattice.inf_continuous' theorem is_open_sUnion (s : set (set α)) (hs : ∀t∈s, is_open α t) : is_open α (⋃₀ s) := begin simp only [is_open] at hs ⊢, convert complete_lattice.Sup_continuous' (set_of ⁻¹' s) _, { ext1 x, simp only [Sup_apply, set_of_bijective.surjective.exists, exists_prop, mem_preimage, set_coe.exists, supr_Prop_eq, mem_set_of_eq, subtype.coe_mk, mem_sUnion] }, { intros p hp, exact hs (set_of p) (mem_preimage.1 hp) }, end end Scott /-- A Scott topological space is defined on preorders such that their open sets, seen as a function `α → Prop`, preserves the joins of ω-chains -/ @[reducible] def Scott (α : Type u) := α instance Scott.topological_space (α : Type u) [omega_complete_partial_order α] : topological_space (Scott α) := { is_open := Scott.is_open α, is_open_univ := Scott.is_open_univ α, is_open_inter := Scott.is_open.inter α, is_open_sUnion := Scott.is_open_sUnion α } section not_below variables {α : Type*} [omega_complete_partial_order α] (y : Scott α) /-- `not_below` is an open set in `Scott α` used to prove the monotonicity of continuous functions -/ def not_below := { x | ¬ x ≤ y } lemma not_below_is_open : is_open (not_below y) := begin have h : monotone (not_below y), { intros x y' h, simp only [not_below, set_of, le_Prop_eq], intros h₀ h₁, apply h₀ (le_trans h h₁) }, existsi h, rintros c, apply eq_of_forall_ge_iff, intro z, rw ωSup_le_iff, simp only [ωSup_le_iff, not_below, mem_set_of_eq, le_Prop_eq, order_hom.coe_fun_mk, chain.map_coe, function.comp_app, exists_imp_distrib, not_forall], end end not_below open Scott (hiding is_open) open omega_complete_partial_order lemma is_ωSup_ωSup {α} [omega_complete_partial_order α] (c : chain α) : is_ωSup c (ωSup c) := begin split, { apply le_ωSup, }, { apply ωSup_le, }, end lemma Scott_continuous_of_continuous {α β} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : Scott α → Scott β) (hf : continuous f) : omega_complete_partial_order.continuous' f := begin simp only [continuous_def, (⁻¹')] at hf, have h : monotone f, { intros x y h, cases (hf {x | ¬ x ≤ f y} (not_below_is_open _)) with hf hf', clear hf', specialize hf h, simp only [preimage, mem_set_of_eq, le_Prop_eq] at hf, by_contradiction H, apply hf H le_rfl }, existsi h, intro c, apply eq_of_forall_ge_iff, intro z, specialize (hf _ (not_below_is_open z)), cases hf, specialize hf_h c, simp only [not_below, order_hom.coe_fun_mk, eq_iff_iff, mem_set_of_eq] at hf_h, rw [← not_iff_not], simp only [ωSup_le_iff, hf_h, ωSup, supr, Sup, complete_lattice.Sup, complete_semilattice_Sup.Sup, exists_prop, mem_range, order_hom.coe_fun_mk, chain.map_coe, function.comp_app, eq_iff_iff, not_forall], tauto, end lemma continuous_of_Scott_continuous {α β} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : Scott α → Scott β) (hf : omega_complete_partial_order.continuous' f) : continuous f := begin rw continuous_def, intros s hs, change continuous' (s ∘ f), cases hs with hs hs', cases hf with hf hf', apply continuous.of_bundled, apply continuous_comp _ _ hf' hs', end
19d556845f32d2d8b0103238d812b7ab917dbab1
bb31430994044506fa42fd667e2d556327e18dfe
/src/order/category/NonemptyFinLinOrd.lean
95a42944534e99bc5c2b8e1a602dd5c1b6f75041
[ "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
6,564
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 data.fintype.order import data.set.finite import order.category.LinearOrder import category_theory.limits.shapes.images import category_theory.limits.shapes.regular_mono /-! # Nonempty finite linear orders This defines `NonemptyFinLinOrd`, the category of nonempty finite linear orders with monotone maps. This is the index category for simplicial objects. -/ universes u v open category_theory category_theory.limits /-- A typeclass for nonempty finite linear orders. -/ class nonempty_fin_lin_ord (α : Type*) extends fintype α, linear_order α := (nonempty : nonempty α . tactic.apply_instance) attribute [instance] nonempty_fin_lin_ord.nonempty @[priority 100] instance nonempty_fin_lin_ord.to_bounded_order (α : Type*) [nonempty_fin_lin_ord α] : bounded_order α := fintype.to_bounded_order α instance punit.nonempty_fin_lin_ord : nonempty_fin_lin_ord punit := { } instance fin.nonempty_fin_lin_ord (n : ℕ) : nonempty_fin_lin_ord (fin (n+1)) := { } instance ulift.nonempty_fin_lin_ord (α : Type u) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord (ulift.{v} α) := { .. linear_order.lift' equiv.ulift (equiv.injective _) } instance (α : Type*) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord αᵒᵈ := { ..order_dual.fintype α } /-- The category of nonempty finite linear orders. -/ def NonemptyFinLinOrd := bundled nonempty_fin_lin_ord namespace NonemptyFinLinOrd instance : bundled_hom.parent_projection @nonempty_fin_lin_ord.to_linear_order := ⟨⟩ attribute [derive [large_category, concrete_category]] NonemptyFinLinOrd instance : has_coe_to_sort NonemptyFinLinOrd Type* := bundled.has_coe_to_sort /-- Construct a bundled `NonemptyFinLinOrd` from the underlying type and typeclass. -/ def of (α : Type*) [nonempty_fin_lin_ord α] : NonemptyFinLinOrd := bundled.of α @[simp] lemma coe_of (α : Type*) [nonempty_fin_lin_ord α] : ↥(of α) = α := rfl instance : inhabited NonemptyFinLinOrd := ⟨of punit⟩ instance (α : NonemptyFinLinOrd) : nonempty_fin_lin_ord α := α.str instance has_forget_to_LinearOrder : has_forget₂ NonemptyFinLinOrd LinearOrder := bundled_hom.forget₂ _ _ /-- Constructs an equivalence between nonempty finite linear orders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : NonemptyFinLinOrd.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply x }, inv_hom_id' := by { ext, exact e.apply_symm_apply x } } /-- `order_dual` as a functor. -/ @[simps] def dual : NonemptyFinLinOrd ⥤ NonemptyFinLinOrd := { obj := λ X, of Xᵒᵈ, map := λ X Y, order_hom.dual } /-- The equivalence between `FinPartialOrder` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : NonemptyFinLinOrd ≌ NonemptyFinLinOrd := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) lemma mono_iff_injective {A B : NonemptyFinLinOrd.{u}} (f : A ⟶ B) : mono f ↔ function.injective f := begin refine ⟨_, concrete_category.mono_of_injective f⟩, introI, intros a₁ a₂ h, let X : NonemptyFinLinOrd.{u} := ⟨ulift (fin 1)⟩, let g₁ : X ⟶ A := ⟨λ x, a₁, λ x₁ x₂ h, by refl⟩, let g₂ : X ⟶ A := ⟨λ x, a₂, λ x₁ x₂ h, by refl⟩, change g₁ (ulift.up (0 : fin 1)) = g₂ (ulift.up (0 : fin 1)), have eq : g₁ ≫ f = g₂ ≫ f := by { ext x, exact h, }, rw cancel_mono at eq, rw eq, end lemma epi_iff_surjective {A B : NonemptyFinLinOrd.{u}} (f : A ⟶ B) : epi f ↔ function.surjective f := begin split, { introI, by_contra' hf', rcases hf' with ⟨m, hm⟩, let Y : NonemptyFinLinOrd.{u} := ⟨ulift (fin 2)⟩, let p₁ : B ⟶ Y := ⟨λ b, if b < m then ulift.up 0 else ulift.up 1, λ x₁ x₂ h, begin simp only, split_ifs with h₁ h₂ h₂, any_goals { apply fin.zero_le, }, { exfalso, exact h₁ (lt_of_le_of_lt h h₂), }, { refl, }, end⟩, let p₂ : B ⟶ Y := ⟨λ b, if b ≤ m then ulift.up 0 else ulift.up 1, λ x₁ x₂ h, begin simp only, split_ifs with h₁ h₂ h₂, any_goals { apply fin.zero_le, }, { exfalso, exact h₁ (h.trans h₂), }, { refl, }, end⟩, have h : p₁ m = p₂ m, { congr, rw ← cancel_epi f, ext a : 2, simp only [comp_apply, order_hom.coe_fun_mk], split_ifs with h₁ h₂ h₂, any_goals { refl, }, { exfalso, exact h₂ (le_of_lt h₁), }, { exfalso, exact hm a (eq_of_le_of_not_lt h₂ h₁), }, }, simpa only [order_hom.coe_fun_mk, lt_self_iff_false, if_false, le_refl, if_true, ulift.up_inj, fin.one_eq_zero_iff, nat.succ_succ_ne_one] using h, }, { intro h, exact concrete_category.epi_of_surjective f h, }, end instance : split_epi_category NonemptyFinLinOrd.{u} := ⟨λ X Y f hf, begin have H : ∀ (y : Y), nonempty (f⁻¹' { y }), { rw epi_iff_surjective at hf, intro y, exact nonempty.intro ⟨(hf y).some, (hf y).some_spec⟩, }, let φ : Y → X := λ y, (H y).some.1, have hφ : ∀ (y : Y), f (φ y) = y := λ y, (H y).some.2, refine is_split_epi.mk' ⟨⟨φ, _⟩, _⟩, swap, { ext b, apply hφ, }, { intros a b, contrapose, intro h, simp only [not_le] at h ⊢, suffices : b ≤ a, { apply lt_of_le_of_ne this, intro h', exfalso, simpa only [h', lt_self_iff_false] using h, }, simpa only [hφ] using f.monotone (le_of_lt h), }, end⟩ instance : has_strong_epi_mono_factorisations NonemptyFinLinOrd.{u} := ⟨λ X Y f, begin let I : NonemptyFinLinOrd.{u} := ⟨set.image (coe_fn f) ⊤, ⟨⟩⟩, let e : X ⟶ I := ⟨λ x, ⟨f x, ⟨x, by tidy⟩⟩, λ x₁ x₂ h, f.monotone h⟩, let m : I ⟶ Y := ⟨λ y, y, by tidy⟩, haveI : epi e := by { rw epi_iff_surjective, tidy, }, haveI : strong_epi e := strong_epi_of_epi e, haveI : mono m := concrete_category.mono_of_injective _ (by tidy), exact nonempty.intro { I := I, m := m, e := e, }, end⟩ end NonemptyFinLinOrd lemma NonemptyFinLinOrd_dual_comp_forget_to_LinearOrder : NonemptyFinLinOrd.dual ⋙ forget₂ NonemptyFinLinOrd LinearOrder = forget₂ NonemptyFinLinOrd LinearOrder ⋙ LinearOrder.dual := rfl
46055766f7205de3c9fa5b20176fb60614822314
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/constFun.lean
18acca1dcf6762c60c10f44a0f8319f99bdc4426
[ "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
358
lean
structure ConstantFunction where domain : Type range : Type f : domain → range h : ∀ a b, f a = f b instance : CoeFun ConstantFunction (fun s => s.domain → s.range) where coe s := s.f def zeroNatNat : ConstantFunction where domain := Nat range := Nat f x := 0 h a b := rfl def tst (x : Nat) : Nat := zeroNatNat x
2baf0c315a5d9bc2fdaf427cdc5a617d11c78b08
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/field_simp_auto.lean
22f72e601e1e4e25f2841bceefa6f9b7353b6cbe
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,411
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.interactive import Mathlib.tactic.norm_num import Mathlib.PostPort namespace Mathlib /-! # `field_simp` tactic Tactic to clear denominators in algebraic expressions, based on `simp` with a specific simpset. -/ namespace tactic /-- Try to prove a goal of the form `x ≠ 0` by calling `assumption`, or `norm_num1` if `x` is a numeral. -/ namespace interactive /-- The goal of `field_simp` is to reduce an expression in a field to an expression of the form `n / d` where neither `n` nor `d` contains any division symbol, just using the simplifier (with a carefully crafted simpset named `field_simps`) to reduce the number of division symbols whenever possible by iterating the following steps: - write an inverse as a division - in any product, move the division to the right - if there are several divisions in a product, group them together at the end and write them as a single division - reduce a sum to a common denominator If the goal is an equality, this simpset will also clear the denominators, so that the proof can normally be concluded by an application of `ring` or `ring_exp`. `field_simp [hx, hy]` is a short form for `simp [-one_div, -mul_eq_zero, hx, hy] with field_simps {discharger := [field_simp.ne_zero]}` Note that this naive algorithm will not try to detect common factors in denominators to reduce the complexity of the resulting expression. Instead, it relies on the ability of `ring` to handle complicated expressions in the next step. As always with the simplifier, reduction steps will only be applied if the preconditions of the lemmas can be checked. This means that proofs that denominators are nonzero should be included. The fact that a product is nonzero when all factors are, and that a power of a nonzero number is nonzero, are included in the simpset, but more complicated assertions (especially dealing with sums) should be given explicitly. If your expression is not completely reduced by the simplifier invocation, check the denominators of the resulting expression and provide proofs that they are nonzero to enable further progress. To check that denominators are nonzero, `field_simp` will look for facts in the context, and will try to apply `norm_num` to close numerical goals. The invocation of `field_simp` removes the lemma `one_div` from the simpset, as this lemma works against the algorithm explained above. It also removes `mul_eq_zero : x * y = 0 ↔ x = 0 ∨ y = 0`, as `norm_num` can not work on disjunctions to close goals of the form `24 ≠ 0`, and replaces it with `mul_ne_zero : x ≠ 0 → y ≠ 0 → x * y ≠ 0` creating two goals instead of a disjunction. For example, ```lean example (a b c d x y : ℂ) (hx : x ≠ 0) (hy : y ≠ 0) : a + b / x + c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x + c) / x) := begin field_simp, ring end ``` See also the `cancel_denoms` tactic, which tries to do a similar simplification for expressions that have numerals in denominators. The tactics are not related: `cancel_denoms` will only handle numeric denominators, and will try to entirely remove (numeric) division from the expression by multiplying by a factor. -/ end Mathlib
efec164a29f227a32ae86e8738b9d686df64c31c
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/nat/interval.lean
1f779981de02ed118e3c39fe78ba9f1fcca27768
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,628
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite /-! # Finite intervals of naturals This file proves that `ℕ` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. ## TODO Some lemmas can be generalized using `ordered_group`, `canonically_ordered_monoid` or `succ_order` and subsequently be moved upstream to `data.finset.locally_finite`. -/ open finset nat instance : locally_finite_order ℕ := { finset_Icc := λ a b, (list.range' a (b + 1 - a)).to_finset, finset_Ico := λ a b, (list.range' a (b - a)).to_finset, finset_Ioc := λ a b, (list.range' (a + 1) (b - a)).to_finset, finset_Ioo := λ a b, (list.range' (a + 1) (b - a - 1)).to_finset, finset_mem_Icc := λ a b x, begin rw [list.mem_to_finset, list.mem_range'], cases le_or_lt a b, { rw [add_tsub_cancel_of_le (nat.lt_succ_of_le h).le, nat.lt_succ_iff] }, { rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) } end, finset_mem_Ico := λ a b x, begin rw [list.mem_to_finset, list.mem_range'], cases le_or_lt a b, { rw [add_tsub_cancel_of_le h] }, { rw [tsub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2.le)) } end, finset_mem_Ioc := λ a b x, begin rw [list.mem_to_finset, list.mem_range'], cases le_or_lt a b, { rw [←succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), nat.lt_succ_iff, nat.succ_le_iff] }, { rw [tsub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.le.trans hx.2)) } end, finset_mem_Ioo := λ a b x, begin rw [list.mem_to_finset, list.mem_range', ← tsub_add_eq_tsub_tsub], cases le_or_lt (a + 1) b, { rw [add_tsub_cancel_of_le h, nat.succ_le_iff] }, { rw [tsub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) } end } namespace nat variables (a b c : ℕ) lemma Icc_eq_range' : Icc a b = (list.range' a (b + 1 - a)).to_finset := rfl lemma Ico_eq_range' : Ico a b = (list.range' a (b - a)).to_finset := rfl lemma Ioc_eq_range' : Ioc a b = (list.range' (a + 1) (b - a)).to_finset := rfl lemma Ioo_eq_range' : Ioo a b = (list.range' (a + 1) (b - a - 1)).to_finset := rfl lemma Iio_eq_range : Iio = range := by { ext b x, rw [mem_Iio, mem_range] } lemma Ico_zero_eq_range : Ico 0 a = range a := by rw [←bot_eq_zero, ←Iio_eq_Ico, Iio_eq_range] lemma _root_.finset.range_eq_Ico : range = Ico 0 := by { funext, exact (Ico_zero_eq_range n).symm } @[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := by rw [Icc_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range'] @[simp] lemma card_Ico : (Ico a b).card = b - a := by rw [Ico_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range'] @[simp] lemma card_Ioc : (Ioc a b).card = b - a := by rw [Ioc_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range'] @[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := by rw [Ioo_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range'] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a := by rw [←card_Ico, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 := by rw [←card_Ioo, fintype.card_of_finset] -- TODO@Yaël: Generalize all the following lemmas to `succ_order` lemma Icc_succ_left : Icc a.succ b = Ioc a b := by { ext x, rw [mem_Icc, mem_Ioc, succ_le_iff] } lemma Ico_succ_right : Ico a b.succ = Icc a b := by { ext x, rw [mem_Ico, mem_Icc, lt_succ_iff] } lemma Ico_succ_left : Ico a.succ b = Ioo a b := by { ext x, rw [mem_Ico, mem_Ioo, succ_le_iff] } lemma Icc_pred_right {b : ℕ} (h : 0 < b) : Icc a (b - 1) = Ico a b := by { ext x, rw [mem_Icc, mem_Ico, lt_iff_le_pred h] } lemma Ico_succ_succ : Ico a.succ b.succ = Ioc a b := by { ext x, rw [mem_Ico, mem_Ioc, succ_le_iff, lt_succ_iff] } @[simp] lemma Ico_succ_singleton : Ico a (a + 1) = {a} := by rw [Ico_succ_right, Icc_self] @[simp] lemma Ico_pred_singleton {a : ℕ} (h : 0 < a) : Ico (a - 1) a = {a - 1} := by rw [←Icc_pred_right _ h, Icc_self] variables {a b c} lemma Ico_succ_right_eq_insert_Ico (h : a ≤ b) : Ico a (b + 1) = insert b (Ico a b) := by rw [Ico_succ_right, ←Ico_insert_right h] lemma Ico_insert_succ_left (h : a < b) : insert a (Ico a.succ b) = Ico a b := by rw [Ico_succ_left, ←Ioo_insert_left h] lemma image_sub_const_Ico (h : c ≤ a) : (Ico a b).image (λ x, x - c) = Ico (a - c) (b - c) := begin ext x, rw mem_image, split, { rintro ⟨x, hx, rfl⟩, rw [mem_Ico] at ⊢ hx, exact ⟨tsub_le_tsub_right hx.1 _, tsub_lt_tsub_right_of_le (h.trans hx.1) hx.2⟩ }, { rintro h, refine ⟨x + c, _, add_tsub_cancel_right _ _⟩, rw mem_Ico at ⊢ h, exact ⟨tsub_le_iff_right.1 h.1, lt_tsub_iff_right.1 h.2⟩ } end lemma Ico_image_const_sub_eq_Ico (hac : a ≤ c) : (Ico a b).image (λ x, c - x) = Ico (c + 1 - b) (c + 1 - a) := begin ext x, rw [mem_image, mem_Ico], split, { rintro ⟨x, hx, rfl⟩, rw mem_Ico at hx, refine ⟨_, ((tsub_le_tsub_iff_left hac).2 hx.1).trans_lt ((tsub_lt_tsub_iff_right hac).2 (nat.lt_succ_self _))⟩, cases lt_or_le c b, { rw tsub_eq_zero_iff_le.mpr (succ_le_of_lt h), exact zero_le _ }, { rw ←succ_sub_succ c, exact (tsub_le_tsub_iff_left (succ_le_succ $ hx.2.le.trans h)).2 hx.2 } }, { rintro ⟨hb, ha⟩, rw [lt_tsub_iff_left, lt_succ_iff] at ha, have hx : x ≤ c := (nat.le_add_left _ _).trans ha, refine ⟨c - x, _, tsub_tsub_cancel_of_le hx⟩, { rw mem_Ico, exact ⟨le_tsub_of_add_le_right ha, (tsub_lt_iff_left hx).2 $ succ_le_iff.1 $ tsub_le_iff_right.1 hb⟩ } } end lemma range_image_pred_top_sub (n : ℕ) : (finset.range n).image (λ j, n - 1 - j) = finset.range n := begin cases n, { rw [range_zero, image_empty] }, { rw [finset.range_eq_Ico, Ico_image_const_sub_eq_Ico (zero_le _)], simp_rw [succ_sub_succ, tsub_zero, tsub_self] } end end nat
64b799bc655d05acf2977a6309a476636a977903
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/task_test2.lean
77576d8c5f6f4fd020f1648095d9f57b1434ce09
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
446
lean
new_frontend def run1 (i : Nat) (n : Nat) (xs : List Nat) : Nat := n.repeat (fun r => dbgTrace (">> [" ++ toString i ++ "] " ++ toString r) $ fun _ => xs.foldl (fun a b => a + b) r) 0 def tst (n : Nat) : IO UInt32 := let ys := (List.replicate n 1); let ts : List (Task Nat) := (List.iota 10).map (fun i => Task.spawn fun _ => run1 (i+1) n ys); let ns : List Nat := ts.map Task.get; IO.println (">> " ++ toString ns) *> pure 0 #eval tst 10
9f4435933b01812c46b1404e44fd9c2428b8cd29
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/option.lean
bd3f0ee8d22827d993658a9c77da55f24e0f5e23
[ "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,745
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.fintype.card import data.finset.option /-! # fintype instances for option -/ open function open_locale nat universes u v variables {α β γ : Type*} open finset function instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ lemma univ_option (α : Type*) [fintype α] : (univ : finset (option α)) = insert_none univ := rfl @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (finset.card_cons _).trans $ congr_arg2 _ (card_map _) rfl /-- If `option α` is a `fintype` then so is `α` -/ def fintype_of_option {α : Type*} [fintype (option α)] : fintype α := ⟨finset.erase_none (fintype.elems (option α)), λ x, mem_erase_none.mpr (fintype.complete (some x))⟩ /-- A type is a `fintype` if its successor (using `option`) is a `fintype`. -/ def fintype_of_option_equiv [fintype α] (f : α ≃ option β) : fintype β := by { haveI := fintype.of_equiv _ f, exact fintype_of_option } namespace fintype /-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ def trunc_rec_empty_option {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α)) (α : Type u) [fintype α] [decidable_eq α] : trunc (P α) := begin suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)), { apply trunc.bind (this (fintype.card α)), intro h, apply trunc.map _ (fintype.trunc_equiv_fin α), intro e, exact of_equiv (equiv.ulift.trans e.symm) h }, intro n, induction n with n ih, { have : card pempty = card (ulift (fin 0)), { simp only [card_fin, card_pempty, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.mk, refine of_equiv e h_empty, }, { have : card (option (ulift (fin n))) = card (ulift (fin n.succ)), { simp only [card_fin, card_option, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.map _ ih, intro ih, refine of_equiv e (h_option ih), }, end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ @[elab_as_eliminator] lemma induction_empty_option {P : Π (α : Type u) [fintype α], Prop} (of_equiv : ∀ α β [fintype β] (e : α ≃ β), @P α (@fintype.of_equiv α β ‹_› e.symm) → @P β ‹_›) (h_empty : P pempty) (h_option : ∀ α [fintype α], by exactI P α → P (option α)) (α : Type u) [fintype α] : P α := begin obtain ⟨p⟩ := @trunc_rec_empty_option (λ α, ∀ h, @P α h) (λ α β e hα hβ, @of_equiv α β hβ e (hα _)) (λ _i, by convert h_empty) _ α _ (classical.dec_eq α), { exact p _ }, { rintro α hα - Pα hα', resetI, convert h_option α (Pα _) } end end fintype /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ lemma finite.induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α], P α → P (option α)) (α : Type u) [finite α] : P α := begin casesI nonempty_fintype α, refine fintype.induction_empty_option _ _ _ α, exacts [λ α β _, of_equiv, h_empty, @h_option] end
b8b9fd0caa56a5975514d7128744f05323f87559
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/by_contradiction.lean
e0e5c309655bff28b5d2d6cd6d771d836928bfbc
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
899
lean
open tactic nat example (a b : nat) : a ≠ b → ¬ a = b := by do intros, by_contradiction `H, trace_state, contradiction #print "-------" example (a b : nat) : ¬¬ a = b → a = b := by do intros, by_contradiction `H, trace_state, contradiction #print "-------" example (p q : Prop) : ¬¬ p → p := by do intros, by_contradiction `H, trace_state, contradiction -- following tests use interactive mode so that we can use `guard_hyp` /-- `by_contradiction` should unfold reducible defs like `ne` to find a leading `not`. --/ example (a b : nat) : a ≠ b → a ≠ b := begin intros, by_contradiction H, guard_hyp H : a = b, contradiction end def my_ne (a b : nat) := a ≠ b /-- Semireducible defs are not unfolded -/ example (a b : nat) : a ≠ b → my_ne a b := begin intros, by_contradiction H, guard_hyp H : ¬my_ne a b, contradiction end
8946bc6854d7fa8d5ca75812e0e6a444e47ecc65
a726f88081e44db9edfd14d32cfe9c4393ee56a4
/world_experiments/world9/level_advanced1.lean
3abff0d858847d5db4c309d960f1d2f2b46ca081
[]
no_license
b-mehta/natural_number_game
80451bf10277adc89a55dbe8581692c36d822462
9faf799d0ab48ecbc89b3d70babb65ba64beee3b
refs/heads/master
1,598,525,389,186
1,573,516,674,000
1,573,516,674,000
217,339,684
0
0
null
1,571,933,100,000
1,571,933,099,000
null
UTF-8
Lean
false
false
1,080
lean
import game.world5.level3 -- hide import game.world2.level14 -- add_right_eq_zero namespace mynat -- hide /- # World 5 : Inequality world ## Level used-to-be-4 : `le_zero` -- THIS NEEDS LE_SUCC SOMEWHERE To do a level like this, you'll need to know that if `a + c = 0` then `a = 0`. You could launch into a proof of this e.g. via a case split on `a` (`cases a` will split into the cases `a = 0` and `a = succ(b)`) but actually we already proved this lemma -- it's `add_right_eq_zero` from the extra levels in world 2 (it's level 14). If you're planning on working through world 5, you should probably check that you can do the extra levels in world 2 first. oh -- start with `intro h`. You should have picked up stuff about the `intro` tactic in the world 2 extra levels. -/ /- Pro tip: if `h` is a proof of `A = B`, then `h.symm` is a proof of `B = A`. -/ /- Lemma For all naturals `a`, if `a ≤ 0` then `a = 0`. -/ lemma le_zero {a : mynat} (h : a ≤ 0) : a = 0 := begin [less_leaky] cases h with c hc, apply add_right_eq_zero hc.symm, end end mynat -- hide
1f1b85dc8be153376ca5ebfba4446bcd8b8201de
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/extract.lean
3cf07ab7ddf11452fbdfffed624a4f88450fca44
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,545
lean
#eval "abc" /- some "a" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next; it₁.extract it₂ /- some "" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; it₁.extract it₁ /- none -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next; it₂.extract it₁ /- some "abc" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.next.next.prev.next; it₁.extract it₂ /- some "bcde" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator.next; let it₂ := it₁.next.next.next.next; it₁.extract it₂ /- some "abcde" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.next.next.next.next; it₁.extract it₂ /- some "ab" -/ #eval let s₁ := "abcde"; let s₂ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := s₂.mkIterator.next.next; it₁.extract it₂ /- none -/ #eval let s₁ := "abcde"; let s₂ := "abhde"; let it₁ := s₁.mkIterator; let it₂ := s₂.mkIterator.next.next; it₁.extract it₂ /- none -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.setCurr 'a'; it₁.extract it₂ /- some "a" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.setCurr 'b'; it₁.extract it₂ /- some "a" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := (it₁.next.setCurr 'a').setCurr 'b'; it₁.extract it₂
25c806a311857f578f5b71351c444876ad7f13c4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/typeMismatch.lean
0f34c2031586036d0deeab4e994bfd1a29fea077
[ "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
186
lean
import Lean -- Test type mismatch error messages for "liftable" methods def test (x : Nat) : IO Nat := IO.println "" open Lean def test2 (x : Expr) : MetaM Unit := Meta.isDefEq x x
e9d18ee4d2f3d7bee7a62a6440b1b09120d72138
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Init/Tactics.lean
ac8e1d4c9c006432884e594fcfb54274d0f0be58
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
35,809
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ prelude import Init.Notation set_option linter.missingDocs true -- keep it documented namespace Lean.Parser.Tactic /-- `with_annotate_state stx t` annotates the lexical range of `stx : Syntax` with the initial and final state of running tactic `t`. -/ scoped syntax (name := withAnnotateState) "with_annotate_state " rawStx ppSpace tactic : tactic /-- Introduces one or more hypotheses, optionally naming and/or pattern-matching them. For each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type. * `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`. * `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`, or matched against a pattern: ```lean -- ... ⊢ α × β → ... intro (a, b) -- ..., a : α, b : β ⊢ ... ``` * Alternatively, `intro` can be combined with pattern matching much like `fun`: ```lean intro | n + 1, 0 => tac | ... ``` -/ syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic /-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/ syntax (name := intros) "intros " (colGt (ident <|> hole))* : tactic /-- `rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`, or fails if no such hypothesis could be found. -/ syntax (name := rename) "rename " term " => " ident : tactic /-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/ syntax (name := revert) "revert " (colGt term:max)+ : tactic /-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/ syntax (name := clear) "clear " (colGt term:max)+ : tactic /-- `subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`. If `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/ syntax (name := subst) "subst " (colGt term:max)+ : tactic /-- Applies `subst` to all hypotheses of the form `h : x = t` or `h : t = x`. -/ syntax (name := substVars) "subst_vars" : tactic /-- `assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails. Note also the `‹t›` term notation, which is a shorthand for `show t by assumption`. -/ syntax (name := assumption) "assumption" : tactic /-- `contradiction` closes the main goal if its hypotheses are "trivially contradictory". - Inductive type/family with no applicable constructors ```lean example (h : False) : p := by contradiction ``` - Injectivity of constructors ```lean example (h : none = some true) : p := by contradiction -- ``` - Decidable false proposition ```lean example (h : 2 + 2 = 3) : p := by contradiction ``` - Contradictory hypotheses ```lean example (h : p) (h' : ¬ p) : q := by contradiction ``` - Other simple contradictions such as ```lean example (x : Nat) (h : x ≠ x) : p := by contradiction ``` -/ syntax (name := contradiction) "contradiction" : tactic /-- `apply e` tries to match the current goal against the conclusion of `e`'s type. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ syntax (name := apply) "apply " term : tactic /-- `exact e` closes the main goal if its target type matches that of `e`. -/ syntax (name := exact) "exact " term : tactic /-- `refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved by unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name. -/ syntax (name := refine) "refine " term : tactic /-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/ syntax (name := refine') "refine' " term : tactic /-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/ syntax (name := constructor) "constructor" : tactic /-- * `case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails. * `case tag x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. * `case tag₁ | tag₂ => tac` is equivalent to `(case tag₁ => tac); (case tag₂ => tac)`. -/ syntax (name := case) "case " sepBy1(caseArg, " | ") " => " tacticSeq : tactic /-- `case'` is similar to the `case tag => tac` tactic, but does not ensure the goal has been solved after applying `tac`, nor admits the goal if `tac` failed. Recall that `case` closes the goal using `sorry` when `tac` fails, and the tactic execution is not interrupted. -/ syntax (name := case') "case' " sepBy1(caseArg, " | ") " => " tacticSeq : tactic /-- `next => tac` focuses on the next goal and solves it using `tac`, or else fails. `next x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/ macro "next " args:binderIdent* " => " tac:tacticSeq : tactic => `(tactic| case _ $args* => $tac) /-- `all_goals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/ syntax (name := allGoals) "all_goals " tacticSeq : tactic /-- `any_goals tac` applies the tactic `tac` to every goal, and succeeds if at least one application succeeds. -/ syntax (name := anyGoals) "any_goals " tacticSeq : tactic /-- `focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it. Usually `· tac`, which enforces that the goal is closed by `tac`, should be preferred. -/ syntax (name := focus) "focus " tacticSeq : tactic /-- `skip` does nothing. -/ syntax (name := skip) "skip" : tactic /-- `done` succeeds iff there are no remaining goals. -/ syntax (name := done) "done" : tactic /-- `trace_state` displays the current state in the info view. -/ syntax (name := traceState) "trace_state" : tactic /-- `trace msg` displays `msg` in the info view. -/ syntax (name := traceMessage) "trace " str : tactic /-- `fail_if_success t` fails if the tactic `t` succeeds. -/ syntax (name := failIfSuccess) "fail_if_success " tacticSeq : tactic /-- `(tacs)` executes a list of tactics in sequence, without requiring that the goal be closed at the end like `· tacs`. Like `by` itself, the tactics can be either separated by newlines or `;`. -/ syntax (name := paren) "(" withoutPosition(tacticSeq) ")" : tactic /-- `with_reducible tacs` excutes `tacs` using the reducible transparency setting. In this setting only definitions tagged as `[reducible]` are unfolded. -/ syntax (name := withReducible) "with_reducible " tacticSeq : tactic /-- `with_reducible_and_instances tacs` excutes `tacs` using the `.instances` transparency setting. In this setting only definitions tagged as `[reducible]` or type class instances are unfolded. -/ syntax (name := withReducibleAndInstances) "with_reducible_and_instances " tacticSeq : tactic /-- `with_unfolding_all tacs` excutes `tacs` using the `.all` transparency setting. In this setting all definitions that are not opaque are unfolded. -/ syntax (name := withUnfoldingAll) "with_unfolding_all " tacticSeq : tactic /-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/ syntax (name := first) "first " withPosition((colGe "|" tacticSeq)+) : tactic /-- `rotate_left n` rotates goals to the left by `n`. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. If `n` is omitted, it defaults to `1`. -/ syntax (name := rotateLeft) "rotate_left" (num)? : tactic /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. If `n` is omitted, it defaults to `1`. -/ syntax (name := rotateRight) "rotate_right" (num)? : tactic /-- `try tac` runs `tac` and succeeds even if `tac` failed. -/ macro "try " t:tacticSeq : tactic => `(tactic| first | $t | skip) /-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/ macro:1 x:tactic tk:" <;> " y:tactic:0 : tactic => `(tactic| focus $x:tactic -- annotate token with state after executing `x` with_annotate_state $tk skip all_goals $y:tactic) /-- `eq_refl` is equivalent to `exact rfl`, but has a few optimizations. -/ syntax (name := refl) "eq_refl" : tactic /-- `rfl` tries to close the current goal using reflexivity. This is supposed to be an extensible tactic and users can add their own support for new reflexive relations. -/ macro "rfl" : tactic => `(tactic| eq_refl) /-- `rfl'` is similar to `rfl`, but disables smart unfolding and unfolds all kinds of definitions, theorems included (relevant for declarations defined by well-founded recursion). -/ macro "rfl'" : tactic => `(tactic| set_option smartUnfolding false in with_unfolding_all rfl) /-- `ac_rfl` proves equalities up to application of an associative and commutative operator. ``` instance : IsAssociative (α := Nat) (.+.) := ⟨Nat.add_assoc⟩ instance : IsCommutative (α := Nat) (.+.) := ⟨Nat.add_comm⟩ example (a b c d : Nat) : a + b + c + d = d + (b + c) + a := by ac_rfl ``` -/ syntax (name := acRfl) "ac_rfl" : tactic /-- The `sorry` tactic closes the goal using `sorryAx`. This is intended for stubbing out incomplete parts of a proof while still having a syntactically correct proof skeleton. Lean will give a warning whenever a proof uses `sorry`, so you aren't likely to miss it, but you can double check if a theorem depends on `sorry` by using `#print axioms my_thm` and looking for `sorryAx` in the axiom list. -/ macro "sorry" : tactic => `(tactic| exact @sorryAx _ false) /-- `admit` is a shorthand for `exact sorry`. -/ macro "admit" : tactic => `(tactic| exact @sorryAx _ false) /-- `infer_instance` is an abbreviation for `exact inferInstance`. It synthesizes a value of any target type by typeclass inference. -/ macro "infer_instance" : tactic => `(tactic| exact inferInstance) /-- Optional configuration option for tactics -/ syntax config := atomic(" (" &"config") " := " withoutPosition(term) ")" /-- The `*` location refers to all hypotheses and the goal. -/ syntax locationWildcard := "*" /-- A hypothesis location specification consists of 1 or more hypothesis references and optionally `⊢` denoting the goal. -/ syntax locationHyp := (colGt term:max)+ patternIgnore("⊢" <|> "|-")? /-- Location specifications are used by many tactics that can operate on either the hypotheses or the goal. It can have one of the forms: * 'empty' is not actually present in this syntax, but most tactics use `(location)?` matchers. It means to target the goal only. * `at h₁ ... hₙ`: target the hypotheses `h₁`, ..., `hₙ` * `at h₁ h₂ ⊢`: target the hypotheses `h₁` and `h₂`, and the goal * `at *`: target all hypotheses and the goal -/ syntax location := withPosition(" at " (locationWildcard <|> locationHyp)) /-- * `change tgt'` will change the goal from `tgt` to `tgt'`, assuming these are definitionally equal. * `change t' at h` will change hypothesis `h : t` to have type `t'`, assuming assuming `t` and `t'` are definitionally equal. -/ syntax (name := change) "change " term (location)? : tactic /-- * `change a with b` will change occurrences of `a` to `b` in the goal, assuming `a` and `b` are are definitionally equal. * `change a with b at h` similarly changes `a` to `b` in the type of hypothesis `h`. -/ syntax (name := changeWith) "change " term " with " term (location)? : tactic /-- If `thm` is a theorem `a = b`, then as a rewrite rule, * `thm` means to replace `a` with `b`, and * `← thm` means to replace `b` with `a`. -/ syntax rwRule := patternIgnore("← " <|> "<- ")? term /-- A `rwRuleSeq` is a list of `rwRule` in brackets. -/ syntax rwRuleSeq := " [" withoutPosition(rwRule,*,?) "]" /-- `rewrite [e]` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational theorems associated with `e` are used. This provides a convenient way to unfold `e`. - `rewrite [e₁, ..., eₙ]` applies the given rules sequentially. - `rewrite [e] at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. -/ syntax (name := rewriteSeq) "rewrite" (config)? rwRuleSeq (location)? : tactic /-- `rw` is like `rewrite`, but also tries to close the goal by "cheap" (reducible) `rfl` afterwards. -/ macro (name := rwSeq) "rw" c:(config)? s:rwRuleSeq l:(location)? : tactic => match s with | `(rwRuleSeq| [$rs,*]%$rbrak) => -- We show the `rfl` state on `]` `(tactic| (rewrite $(c)? [$rs,*] $(l)?; with_annotate_state $rbrak (try (with_reducible rfl)))) | _ => Macro.throwUnsupported /-- The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses. -/ syntax (name := injection) "injection " term (" with " (colGt (ident <|> hole))+)? : tactic /-- `injections` applies `injection` to all hypotheses recursively (since `injection` can produce new hypotheses). Useful for destructing nested constructor equalities like `(a::b::c) = (d::e::f)`. -/ -- TODO: add with syntax (name := injections) "injections" (colGt (ident <|> hole))* : tactic /-- The discharger clause of `simp` and related tactics. This is a tactic used to discharge the side conditions on conditional rewrite rules. -/ syntax discharger := atomic(" (" patternIgnore(&"discharger" <|> &"disch")) " := " withoutPosition(tacticSeq) ")" /-- Use this rewrite rule before entering the subterms -/ syntax simpPre := "↓" /-- Use this rewrite rule after entering the subterms -/ syntax simpPost := "↑" /-- A simp lemma specification is: * optional `↑` or `↓` to specify use before or after entering the subterm * optional `←` to use the lemma backward * `thm` for the theorem to rewrite with -/ syntax simpLemma := (simpPre <|> simpPost)? patternIgnore("← " <|> "<- ")? term /-- An erasure specification `-thm` says to remove `thm` from the simp set -/ syntax simpErase := "-" term:max /-- The simp lemma specification `*` means to rewrite with all hypotheses -/ syntax simpStar := "*" /-- The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants: - `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. - `simp [h₁, h₂, ..., hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`. - `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. - `simp only [h₁, h₂, ..., hₙ]` is like `simp [h₁, h₂, ..., hₙ]` but does not use `[simp]` lemmas. - `simp [-id₁, ..., -idₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`. - `simp at h₁ h₂ ... hₙ` simplifies the hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. If the target or another hypothesis depends on `hᵢ`, a new simplified hypothesis `hᵢ` is introduced, but the old one remains in the local context. - `simp at *` simplifies all the hypotheses and the target. - `simp [*] at *` simplifies target and all (propositional) hypotheses using the other hypotheses. -/ syntax (name := simp) "simp" (config)? (discharger)? (&" only")? (" [" withoutPosition((simpStar <|> simpErase <|> simpLemma),*) "]")? (location)? : tactic /-- `simp_all` is a stronger version of `simp [*] at *` where the hypotheses and target are simplified multiple times until no simplication is applicable. Only non-dependent propositional hypotheses are considered. -/ syntax (name := simpAll) "simp_all" (config)? (discharger)? (&" only")? (" [" withoutPosition((simpErase <|> simpLemma),*) "]")? : tactic /-- The `dsimp` tactic is the definitional simplifier. It is similar to `simp` but only applies theorems that hold by reflexivity. Thus, the result is guaranteed to be definitionally equal to the input. -/ syntax (name := dsimp) "dsimp" (config)? (discharger)? (&" only")? (" [" withoutPosition((simpErase <|> simpLemma),*) "]")? (location)? : tactic /-- `delta id1 id2 ...` delta-expands the definitions `id1`, `id2`, .... This is a low-level tactic, it will expose how recursive definitions have been compiled by Lean. -/ syntax (name := delta) "delta " (colGt ident)+ (location)? : tactic /-- * `unfold id` unfolds definition `id`. * `unfold id1 id2 ...` is equivalent to `unfold id1; unfold id2; ...`. For non-recursive definitions, this tactic is identical to `delta`. For definitions by pattern matching, it uses "equation lemmas" which are autogenerated for each match arm. -/ syntax (name := unfold) "unfold " (colGt ident)+ (location)? : tactic /-- Auxiliary macro for lifting have/suffices/let/... It makes sure the "continuation" `?_` is the main goal after refining. -/ macro "refine_lift " e:term : tactic => `(tactic| focus (refine no_implicit_lambda% $e; rotate_right)) /-- `have h : t := e` adds the hypothesis `h : t` to the current goal if `e` a term of type `t`. * If `t` is omitted, it will be inferred. * If `h` is omitted, the name `this` is used. * The variant `have pattern := e` is equivalent to `match e with | pattern => _`, and it is convenient for types that have only one applicable constructor. For example, given `h : p ∧ q ∧ r`, `have ⟨h₁, h₂, h₃⟩ := h` produces the hypotheses `h₁ : p`, `h₂ : q`, and `h₃ : r`. -/ macro "have " d:haveDecl : tactic => `(tactic| refine_lift have $d:haveDecl; ?_) /-- Given a main goal `ctx ⊢ t`, `suffices h : t' from e` replaces the main goal with `ctx ⊢ t'`, `e` must have type `t` in the context `ctx, h : t'`. The variant `suffices h : t' by tac` is a shorthand for `suffices h : t' from by tac`. If `h :` is omitted, the name `this` is used. -/ macro "suffices " d:sufficesDecl : tactic => `(tactic| refine_lift suffices $d; ?_) /-- `let h : t := e` adds the hypothesis `h : t := e` to the current goal if `e` a term of type `t`. If `t` is omitted, it will be inferred. The variant `let pattern := e` is equivalent to `match e with | pattern => _`, and it is convenient for types that have only applicable constructor. Example: given `h : p ∧ q ∧ r`, `let ⟨h₁, h₂, h₃⟩ := h` produces the hypotheses `h₁ : p`, `h₂ : q`, and `h₃ : r`. -/ macro "let " d:letDecl : tactic => `(tactic| refine_lift let $d:letDecl; ?_) /-- `show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`. -/ macro "show " e:term : tactic => `(tactic| refine_lift show $e from ?_) -- TODO: fix, see comment /-- `let rec f : t := e` adds a recursive definition `f` to the current goal. The syntax is the same as term-mode `let rec`. -/ syntax (name := letrec) withPosition(atomic("let " &"rec ") letRecDecls) : tactic macro_rules | `(tactic| let rec $d) => `(tactic| refine_lift let rec $d; ?_) /-- Similar to `refine_lift`, but using `refine'` -/ macro "refine_lift' " e:term : tactic => `(tactic| focus (refine' no_implicit_lambda% $e; rotate_right)) /-- Similar to `have`, but using `refine'` -/ macro "have' " d:haveDecl : tactic => `(tactic| refine_lift' have $d:haveDecl; ?_) /-- Similar to `have`, but using `refine'` -/ macro (priority := high) "have'" x:ident " := " p:term : tactic => `(tactic| have' $x : _ := $p) /-- Similar to `let`, but using `refine'` -/ macro "let' " d:letDecl : tactic => `(tactic| refine_lift' let $d:letDecl; ?_) /-- The left hand side of an induction arm, `| foo a b c` or `| @foo a b c` where `foo` is a constructor of the inductive type and `a b c` are the arguments to the contstructor. -/ syntax inductionAltLHS := "| " (("@"? ident) <|> hole) (ident <|> hole)* /-- In induction alternative, which can have 1 or more cases on the left and `_`, `?_`, or a tactic sequence after the `=>`. -/ syntax inductionAlt := ppDedent(ppLine) inductionAltLHS+ " => " (hole <|> syntheticHole <|> tacticSeq) /-- After `with`, there is an optional tactic that runs on all branches, and then a list of alternatives. -/ syntax inductionAlts := "with " (tactic)? withPosition((colGe inductionAlt)+) /-- Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well. For example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (Nat.succ a)` and `ih₁ : P a → Q a` and target `Q (Nat.succ a)`. Here the names `a` and `ih₁` are chosen automatically and are not accessible. You can use `with` to provide the variables names for each constructor. - `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable. - `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables - `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized. - Given `x : Nat`, `induction x with | zero => tac₁ | succ x' ih => tac₂` uses tactic `tac₁` for the `zero` case, and `tac₂` for the `succ` case. -/ syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " (colGt term:max)+)? (inductionAlts)? : tactic /-- A `generalize` argument, of the form `term = x` or `h : term = x`. -/ syntax generalizeArg := atomic(ident " : ")? term:51 " = " ident /-- * `generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal with a fresh hypothesis `x`s. If `h` is given, `h : e = x` is introduced as well. * `generalize e = x at h₁ ... hₙ` also generalizes occurrences of `e` inside `h₁`, ..., `hₙ`. * `generalize e = x at *` will generalize occurrences of `e` everywhere. -/ syntax (name := generalize) "generalize " generalizeArg,+ (location)? : tactic /-- A `cases` argument, of the form `e` or `h : e` (where `h` asserts that `e = cᵢ a b` for each constructor `cᵢ` of the inductive). -/ syntax casesTarget := atomic(ident " : ")? term /-- Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well. `cases` detects unreachable cases and closes them automatically. For example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (Nat.succ a)` and target `Q (Nat.succ a)`. Here the name `a` is chosen automatically and is not accessible. You can use `with` to provide the variables names for each constructor. - `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. - Given `as : List α`, `cases as with | nil => tac₁ | cons a as' => tac₂`, uses tactic `tac₁` for the `nil` case, and `tac₂` for the `cons` case, and `a` and `as'` are used as names for the new variables introduced. - `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case. -/ syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic /-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/ syntax (name := renameI) "rename_i " (colGt binderIdent)+ : tactic /-- `repeat tac` applies `tac` to main goal. If the application succeeds, the tactic is applied recursively to the generated subgoals until it eventually fails. -/ syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip) /-- `trivial` tries different simple tactics (e.g., `rfl`, `contradiction`, ...) to close the current goal. You can use the command `macro_rules` to extend the set of tactics used. Example: ``` macro_rules | `(tactic| trivial) => `(tactic| simp) ``` -/ syntax "trivial" : tactic /-- The `split` tactic is useful for breaking nested if-then-else and match expressions in cases. For a `match` expression with `n` cases, the `split` tactic generates at most `n` subgoals -/ syntax (name := split) "split " (colGt term)? (location)? : tactic /-- `dbg_trace "foo"` prints `foo` when elaborated. Useful for debugging tactic control flow: ``` example : False ∨ True := by first | apply Or.inl; trivial; dbg_trace "left" | apply Or.inr; trivial; dbg_trace "right" ``` -/ syntax (name := dbgTrace) "dbg_trace " str : tactic /-- `stop` is a helper tactic for "discarding" the rest of a proof: it is defined as `repeat sorry`. It is useful when working on the middle of a complex proofs, and less messy than commenting the remainder of the proof. -/ macro "stop" tacticSeq : tactic => `(tactic| repeat sorry) /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ syntax (name := specialize) "specialize " term : tactic macro_rules | `(tactic| trivial) => `(tactic| assumption) macro_rules | `(tactic| trivial) => `(tactic| rfl) macro_rules | `(tactic| trivial) => `(tactic| contradiction) macro_rules | `(tactic| trivial) => `(tactic| decide) macro_rules | `(tactic| trivial) => `(tactic| apply True.intro) macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial) /-- `unhygienic tacs` runs `tacs` with name hygiene disabled. This means that tactics that would normally create inaccessible names will instead make regular variables. **Warning**: Tactics may change their variable naming strategies at any time, so code that depends on autogenerated names is brittle. Users should try not to use `unhygienic` if possible. ``` example : ∀ x : Nat, x = x := by unhygienic intro -- x would normally be intro'd as inaccessible exact Eq.refl x -- refer to x ``` -/ macro "unhygienic " t:tacticSeq : tactic => `(tactic| set_option tactic.hygienic false in $t) /-- `fail msg` is a tactic that always fails, and produces an error using the given message. -/ syntax (name := fail) "fail " (str)? : tactic /-- `checkpoint tac` acts the same as `tac`, but it caches the input and output of `tac`, and if the file is re-elaborated and the input matches, the tactic is not re-run and its effects are reapplied to the state. This is useful for improving responsiveness when working on a long tactic proof, by wrapping expensive tactics with `checkpoint`. See the `save` tactic, which may be more convenient to use. (TODO: do this automatically and transparently so that users don't have to use this combinator explicitly.) -/ syntax (name := checkpoint) "checkpoint " tacticSeq : tactic /-- `save` is defined to be the same as `skip`, but the elaborator has special handling for occurrences of `save` in tactic scripts and will transform `by tac1; save; tac2` to `by (checkpoint tac1); tac2`, meaning that the effect of `tac1` will be cached and replayed. This is useful for improving responsiveness when working on a long tactic proof, by using `save` after expensive tactics. (TODO: do this automatically and transparently so that users don't have to use this combinator explicitly.) -/ macro (name := save) "save" : tactic => `(tactic| skip) /-- The tactic `sleep ms` sleeps for `ms` milliseconds and does nothing. It is used for debugging purposes only. -/ syntax (name := sleep) "sleep" num : tactic /-- `exists e₁, e₂, ...` is shorthand for `refine ⟨e₁, e₂, ...⟩; try trivial`. It is useful for existential goals. -/ macro "exists " es:term,+ : tactic => `(tactic| (refine ⟨$es,*, ?_⟩; try trivial)) /-- Apply congruence (recursively) to goals of the form `⊢ f as = f bs` and `⊢ HEq (f as) (f bs)`. The optional parameter is the depth of the recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr 2` produces the intended `⊢ x + y = y + x`. -/ syntax (name := congr) "congr " (num)? : tactic end Tactic namespace Attr /-- Theorems tagged with the `simp` attribute are by the simplifier (i.e., the `simp` tactic, and its variants) to simplify expressions occurring in your goals. We call theorems tagged with the `simp` attribute "simp theorems" or "simp lemmas". Lean maintains a database/index containing all active simp theorems. Here is an example of a simp theorem. ```lean @[simp] theorem ne_eq (a b : α) : (a ≠ b) = Not (a = b) := rfl ``` This simp theorem instructs the simplifier to replace instances of the term `a ≠ b` (e.g. `x + 0 ≠ y`) with `Not (a = b)` (e.g., `Not (x + 0 = y)`). The simplifier applies simp theorems in one direction only: if `A = B` is a simp theorem, then `simp` replaces `A`s with `B`s, but it doesn't replace `B`s with `A`s. Hence a simp theorem should have the property that its right-hand side is "simpler" than its left-hand side. In particular, `=` and `↔` should not be viewed as symmetric operators in this situation. The following would be a terrible simp theorem (if it were even allowed): ```lean @[simp] lemma mul_right_inv_bad (a : G) : 1 = a * a⁻¹ := ... ``` Replacing 1 with a * a⁻¹ is not a sensible default direction to travel. Even worse would be a theorem that causes expressions to grow without bound, causing simp to loop forever. By default the simplifier applies `simp` theorems to an expression `e` after its sub-expressions have been simplified. We say it performs a bottom-up simplification. You can instruct the simplifier to apply a theorem before its sub-expressions have been simplified by using the modifier `↓`. Here is an example ```lean @[simp↓] theorem not_and_eq (p q : Prop) : (¬ (p ∧ q)) = (¬p ∨ ¬q) := ``` When multiple simp theorems are applicable, the simplifier uses the one with highest priority. If there are several with the same priority, it is uses the "most recent one". Example: ```lean @[simp high] theorem cond_true (a b : α) : cond true a b = a := rfl @[simp low+1] theorem or_true (p : Prop) : (p ∨ True) = True := propext <| Iff.intro (fun _ => trivial) (fun _ => Or.inr trivial) @[simp 100] theorem ite_self {d : Decidable c} (a : α) : ite c a a = a := by cases d <;> rfl ``` -/ syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr end Attr end Parser end Lean /-- `‹t›` resolves to an (arbitrary) hypothesis of type `t`. It is useful for referring to hypotheses without accessible names. `t` may contain holes that are solved by unification with the expected type; in particular, `‹_›` is a shortcut for `by assumption`. -/ syntax "‹" withoutPosition(term) "›" : term macro_rules | `(‹$type›) => `((by assumption : $type)) /-- `get_elem_tactic_trivial` is an extensible tactic automatically called by the notation `arr[i]` to prove any side conditions that arise when constructing the term (e.g. the index is in bounds of the array). The default behavior is to just try `trivial` (which handles the case where `i < arr.size` is in the context) and `simp_arith` (for doing linear arithmetic in the index). -/ syntax "get_elem_tactic_trivial" : tactic macro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| trivial) macro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| simp (config := { arith := true }); done) /-- `get_elem_tactic` is the tactic automatically called by the notation `arr[i]` to prove any side conditions that arise when constructing the term (e.g. the index is in bounds of the array). It just delegates to `get_elem_tactic_trivial` and gives a diagnostic error message otherwise; users are encouraged to extend `get_elem_tactic_trivial` instead of this tactic. -/ macro "get_elem_tactic" : tactic => `(tactic| first | get_elem_tactic_trivial | fail "failed to prove index is valid, possible solutions: - Use `have`-expressions to prove the index is valid - Use `a[i]!` notation instead, runtime check is perfomed, and 'Panic' error message is produced if index is not valid - Use `a[i]?` notation instead, result is an `Option` type - Use `a[i]'h` notation instead, where `h` is a proof that index is valid" ) @[inherit_doc getElem] syntax:max term noWs "[" withoutPosition(term) "]" : term macro_rules | `($x[$i]) => `(getElem $x $i (by get_elem_tactic)) @[inherit_doc getElem] syntax term noWs "[" withoutPosition(term) "]'" term:max : term macro_rules | `($x[$i]'$h) => `(getElem $x $i $h)
16907be2c554383a5bdfcfd7054d6442e0358329
3f48345ac9bbaa421714efc9872a0409379bb4ae
/src/examples/automata/Automaton.lean
5d86ccbaf7ac62f95ee8acb81953c5c037852589
[]
no_license
QaisHamarneh/Coalgebra-in-Lean
b4318ee6d83780e5c734eb78fed98b1fe8016f7e
bd0452df98bc64b608e5dfd7babc42c301bb6a46
refs/heads/master
1,663,371,200,241
1,661,004,695,000
1,661,004,695,000
209,798,828
0
0
null
null
null
null
UTF-8
Lean
false
false
1,542
lean
import data.set open set namespace Automaton universes u₃ u₂ u₁ inductive word (Sigma : Type u₂) | ε {} : word | nonempty : Sigma → word → word notation e ` • ` v := word.nonempty e v variables {Sigma : Type u₂} {Γ : Type u₃} open word structure Automaton (Sigma : Type u₂) (Γ : Type u₃): Type (max (u₁+1) u₂ u₃) := (State : Type u₁) -- Set of States (δ : State → Sigma → State) -- δ: S × Σ → S (s₀ : State) -- S₀ the starting state (γ : State → Γ) -- T ⊆ S instance Automaton_to_Type : has_coe_to_sort (Automaton Sigma Γ) := ⟨ Type u₁ , λ A , A.State⟩ /-- Given a morphism τ between two Automates A and B determines if τ is a homomorphism -/ def is_homomorphism {A B : Automaton Sigma Γ} (τ : A → B) : Prop := ∀ a : A.State , -- ∀ states (a) in A A.γ a = B.γ (τ a) ∧ -- a ∈ T_A iff τ(a) ∈ T_B ∀ e : Sigma , -- and ∀ e ∈ Σ τ (A.δ a e) = B.δ (τ a) e -- τ(δ_A(a , e)) = δ_B(τ(a) , e) def δ_Star {A : Automaton Sigma Γ} (s : A): word Sigma → A | ε := s | (e•v) := A.δ (δ_Star v) e def accepted (A : Automaton Sigma Prop) (w : word Sigma) : Prop := A.γ (δ_Star A.s₀ w) end Automaton
0ac6ecb1679aa61d9aabde94444f4cc1429ed65c
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world04/level05.lean
e17c85803f78601b3c0dcd836309fb30a4a66a98
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
197
lean
lemma pow_add (a m n : mynat) : a ^ (m + n) = a ^ m * a ^ n := begin induction n with h hd, rwa [add_zero, pow_zero, mul_one], rw pow_succ, rw add_succ, rw pow_succ, rw hd, rw mul_assoc, refl, end
e215708ce4afd2e4c2df94a1f6529dfde25f5fbd
f02b05b665ad2d2cd970e93758a98d57f310a822
/src/tactic/tcache/tactic.lean
fe75fca6ad968a415d0fc3c9910056c527a4c3b3
[]
no_license
khoek/leancache
b0ed5d2a9a2e87f58d4ad27343d957a9cd49ce5f
5c8329f7b647b8d82966ab180c4473b20d1f249c
refs/heads/master
1,585,344,140,717
1,549,094,327,000
1,549,094,327,000
147,138,187
0
0
null
null
null
null
UTF-8
Lean
false
false
1,221
lean
import tactic.basic import .store open tactic tcache namespace tactic @[inline] meta def are_goals_present : tactic bool := lock_tactic_state $ do /- In a `run_cmd` or similar, there is a single goal with type `true`. If we can clear it using triv, disable caching. -/ try triv, gs ← get_goals, return $ gs.length ≠ 0 @[inline] meta def if_goals_present {α : Type} (alt : tactic α) (t : tactic α) : tactic α := do r ← are_goals_present, if r then t else do hash ← decl_name >>= hash_goals, tcache.trace hash "skipping, no goals", alt meta def tcache_core (t : tactic unit) : tactic unit := discharge_goals t meta def tcache (t : tactic unit) : tactic unit := if_goals_present t (discharge_goals t) meta def tc : tactic unit → tactic unit := tactic.tcache meta def tcache_force {α : Type} (t : tactic α) : tactic α := if_goals_present t $ do init_tcache, tcache_core $ @unchecked_cast (tactic α) (tactic unit) t, return $ @unchecked_cast unit α () namespace interactive meta def tcache (t : interactive.itactic) : tactic unit := tactic.tcache t meta def tc (t : interactive.itactic) : tactic unit := tactic.tcache t end interactive end tactic
fc36b2b8861be4f87fa95668704585c830f4b2b3
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Meta/Tactic/Util.lean
c778c06ac7567fa82fd0026c649375db7ae00605
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
3,381
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.Util.ForEachExpr import Lean.Meta.Basic import Lean.Meta.AppBuilder import Lean.Meta.LevelDefEq import Lean.Meta.PPGoal namespace Lean.Meta /-- Aka user name -/ def getMVarTag (mvarId : MVarId) : MetaM Name := do let mvarDecl ← getMVarDecl mvarId pure mvarDecl.userName def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do modify fun s => { s with mctx := s.mctx.setMVarUserName mvarId tag } def appendTag (tag : Name) (suffix : Name) : Name := let view := extractMacroScopes tag let view := { view with name := view.name ++ suffix.eraseMacroScopes } view.review def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do let tag ← getMVarTag mvarId setMVarTag mvarId (appendTag tag suffix) def mkFreshExprSyntheticOpaqueMVar (type : Expr) (tag : Name := Name.anonymous) : MetaM Expr := mkFreshExprMVar type MetavarKind.syntheticOpaque tag def throwTacticEx {α} (tacticName : Name) (mvarId : MVarId) (msg : MessageData) (ref := Syntax.missing) : MetaM α := throwError "tactic '{tacticName}' failed, {msg}\n{MessageData.ofGoal mvarId}" def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do if (← isExprMVarAssigned mvarId) then throwTacticEx tacticName mvarId "metavariable has already been assigned" def getMVarType (mvarId : MVarId) : MetaM Expr := do pure (← getMVarDecl mvarId).type def getMVarType' (mvarId : MVarId) : MetaM Expr := do whnf (← instantiateMVars (← getMVarDecl mvarId).type) builtin_initialize registerTraceClass `Meta.Tactic /-- Assign `mvarId` to `sorryAx` -/ def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := withMVarContext mvarId do checkNotAssigned mvarId `admit let mvarType ← getMVarType mvarId let val ← mkSorry mvarType synthetic assignExprMVar mvarId val /-- Beta reduce the metavariable type head -/ def headBetaMVarType (mvarId : MVarId) : MetaM Unit := do setMVarType mvarId (← getMVarType mvarId).headBeta /-- Collect nondependent hypotheses. -/ def getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) := withMVarContext mvarId do let mut candidates : NameHashSet := {} for localDecl in (← getLCtx) do unless localDecl.isAuxDecl do candidates ← removeDeps localDecl.type candidates match localDecl.value? with | none => pure () | some value => candidates ← removeDeps value candidates if (← isProp localDecl.type) && !localDecl.hasValue then candidates := candidates.insert localDecl.fvarId candidates ← removeDeps (← getMVarType mvarId) candidates if candidates.isEmpty then return #[] else let mut result := #[] for localDecl in (← getLCtx) do if candidates.contains localDecl.fvarId then result := result.push localDecl.fvarId return result where removeDeps (e : Expr) (candidates : NameHashSet) : MetaM NameHashSet := do let e ← instantiateMVars e let visit : StateRefT NameHashSet MetaM NameHashSet := do e.forEach fun | Expr.fvar fvarId _ => modify fun s => s.erase fvarId | _ => pure () get visit |>.run' candidates end Lean.Meta
c6745eb62c54e9459af4985e4eb29fd161beb78c
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/notes/2019.10.14.prop_logic/semantic_validity.lean
bbce546e44667860c9ada5c8fe4671bc4ccd27f3
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
662
lean
import .prop_logic open prop_logic open prop_logic.var open prop_logic.unOp open prop_logic.binOp open prop_logic.pExp def isModel (i: var → bool) (e : pExp) := pEval e i = tt def valid (e : pExp) := ∀ (i : var → bool), isModel i e def unsatisfiable (e : pExp) := ∀ (i : var → bool), ¬ isModel i e def satisfiable (e : pExp) := ∃ (i : var → bool), isModel i e /- satisfiable if there exists a pExp e that satisfies the condition i e -> tt -/ def satisfiable' (e : pExp) := ∃ (i : var → bool), isModel i e def sat_but_not_valid (e : pExp) := (satisfiable e) ∧ ¬ (valid e)
485955bdd1c183d0912d7503e771a2d516c4bf8d
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.13.lean
652d3ac57778301e958e31ad9c393a2994e3d29a
[]
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
144
lean
import standard example : ∀ a b c : nat, a = b → a = c → c = b := begin intros, apply eq.trans, apply eq.symm, assumption, assumption end
f30890bcf10e6e00f605665b54a091db9695892c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/concatElim.lean
b04e39d0ee6fd6c35f22ae2e033960d331ad9e1f
[ "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
2,471
lean
universe u def concat {α} : List α → α → List α | [], a => [a] | x::xs, a => x :: concat xs a def last {α} : (xs : List α) → xs ≠ [] → α | [], h => by contradiction | [a], h => a | _::a::as, h => last (a::as) (fun h => by injection h) def dropLast {α} : List α → List α | [] => [] | [a] => [] | a::as => a :: dropLast as variable {α} theorem concatEq (xs : List α) (h : xs ≠ []) : concat (dropLast xs) (last xs h) = xs := by match xs, h with | [], h => contradiction | [x], h => rfl | x₁::x₂::xs, h => simp [concat, last, concatEq (x₂::xs) List.noConfusion] theorem lengthCons {α} (x : α) (xs : List α) : (x::xs).length = xs.length + 1 := rfl theorem eqNilOfLengthZero {α} : (xs : List α) → xs.length = 0 → xs = [] | [], h => rfl | x::xs, h => by rw [lengthCons] at h; contradiction theorem dropLastLen {α} (xs : List α) : (n : Nat) → xs.length = n+1 → (dropLast xs).length = n := by match xs with | [] => intros; contradiction | [a] => intro n h have : 1 = n + 1 := h have : 0 = n := by injection this subst this rfl | x₁::x₂::xs => intro n h cases n with | zero => simp [lengthCons] at h injection h | succ n => have : (x₁ :: x₂ :: xs).length = xs.length + 2 := by simp [lengthCons] have : xs.length = n := by rw [this] at h; injection h with h; injection h simp [dropLast, lengthCons, dropLastLen (x₂::xs) xs.length (lengthCons ..), this] @[inline] def concatElim {α} (motive : List α → Sort u) (base : Unit → motive []) (ind : (xs : List α) → (a : α) → motive xs → motive (concat xs a)) (xs : List α) : motive xs := let rec @[specialize] aux : (n : Nat) → (xs : List α) → xs.length = n → motive xs | 0, xs, h => by have aux := eqNilOfLengthZero _ h subst aux apply base () | n+1, xs, h => by have notNil : xs ≠ [] := by intro h1; subst h1; injection h let ih := aux n (dropLast xs) (dropLastLen _ _ h) let aux := ind (dropLast xs) (last xs notNil) ih rw [concatEq] at aux exact aux aux xs.length xs rfl -- The generated code is tail recursive def test (xs : List Nat) : IO Unit := concatElim (motive := fun _ => IO Unit) (fun _ => pure ()) (fun xs x r => do IO.println s!"step xs: {xs} x: {x}"; r) xs #eval test [1, 2, 3, 4]
9e971c620a8ce5509b8111a17d207557d942f7cd
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/arrow.lean
8c9803c5c781823296915765990a5e3a212f4863
[ "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
4,464
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.comma /-! # The category of arrows The category of arrows, with morphisms commutative squares. We set this up as a specialization of the comma category `comma L R`, where `L` and `R` are both the identity functor. We also define the typeclass `has_lift`, representing a choice of a lift of a commutative square (that is, a diagonal morphism making the two triangles commute). ## Tags comma, arrow -/ namespace category_theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation variables {T : Type u} [category.{v} T] section variables (T) /-- The arrow category of `T` has as objects all morphisms in `T` and as morphisms commutative squares in `T`. -/ @[derive category] def arrow := comma.{v v v} (𝟭 T) (𝟭 T) -- Satisfying the inhabited linter instance arrow.inhabited [inhabited T] : inhabited (arrow T) := { default := show comma (𝟭 T) (𝟭 T), from default (comma (𝟭 T) (𝟭 T)) } end namespace arrow @[simp] lemma id_left (f : arrow T) : comma_morphism.left (𝟙 f) = 𝟙 (f.left) := rfl @[simp] lemma id_right (f : arrow T) : comma_morphism.right (𝟙 f) = 𝟙 (f.right) := rfl /-- An object in the arrow category is simply a morphism in `T`. -/ @[simps] def mk {X Y : T} (f : X ⟶ Y) : arrow T := { left := X, right := Y, hom := f } /-- A morphism in the arrow category is a commutative square connecting two objects of the arrow category. -/ @[simps] def hom_mk {f g : arrow T} {u : f.left ⟶ g.left} {v : f.right ⟶ g.right} (w : u ≫ g.hom = f.hom ≫ v) : f ⟶ g := { left := u, right := v, w' := w } /-- We can also build a morphism in the arrow category out of any commutative square in `T`. -/ @[simps] def hom_mk' {X Y : T} {f : X ⟶ Y} {P Q : T} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (w : u ≫ g = f ≫ v) : arrow.mk f ⟶ arrow.mk g := { left := u, right := v, w' := w } @[reassoc] lemma w {f g : arrow T} (sq : f ⟶ g) : sq.left ≫ g.hom = f.hom ≫ sq.right := sq.w /-- A lift of a commutative square is a diagonal morphism making the two triangles commute. -/ @[ext] class has_lift {f g : arrow T} (sq : f ⟶ g) := (lift : f.right ⟶ g.left) (fac_left : f.hom ≫ lift = sq.left) (fac_right : lift ≫ g.hom = sq.right) attribute [simp, reassoc] has_lift.fac_left has_lift.fac_right /-- If we have chosen a lift of a commutative square `sq`, we can access it by saying `lift sq`. -/ abbreviation lift {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.right ⟶ g.left := has_lift.lift sq lemma lift.fac_left {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.hom ≫ lift sq = sq.left := by simp lemma lift.fac_right {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : lift sq ≫ g.hom = sq.right := by simp @[simp, reassoc] lemma lift_mk'_left {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : f ≫ lift (arrow.hom_mk' h) = u := by simp only [←arrow.mk_hom f, lift.fac_left, arrow.hom_mk'_left] @[simp, reassoc] lemma lift_mk'_right {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : lift (arrow.hom_mk' h) ≫ g = v := by simp only [←arrow.mk_hom g, lift.fac_right, arrow.hom_mk'_right] section instance subsingleton_has_lift_of_epi {f g : arrow T} (sq : f ⟶ g) [epi f.hom] : subsingleton (has_lift sq) := subsingleton.intro $ λ a b, has_lift.ext a b $ (cancel_epi f.hom).1 $ by simp instance subsingleton_has_lift_of_mono {f g : arrow T} (sq : f ⟶ g) [mono g.hom] : subsingleton (has_lift sq) := subsingleton.intro $ λ a b, has_lift.ext a b $ (cancel_mono g.hom).1 $ by simp end end arrow namespace functor universes v₁ v₂ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- A functor `C ⥤ D` induces a functor between the corresponding arrow categories. -/ @[simps] def map_arrow (F : C ⥤ D) : arrow C ⥤ arrow D := { obj := λ a, { left := F.obj a.left, right := F.obj a.right, hom := F.map a.hom, }, map := λ a b f, { left := F.map f.left, right := F.map f.right, w' := by { have w := f.w, simp only [id_map] at w, dsimp, simp only [←F.map_comp, w], } } } end functor end category_theory
973088bc8eeb525c9e470edf07d5047778863620
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/measure_theory/probability_mass_function.lean
aa1873f8f82f240a969a644ec2562eb5bddab339
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
4,823
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Probability mass function -- discrete probability measures -/ import topology.instances.nnreal topology.instances.ennreal topology.algebra.infinite_sum noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} open_locale classical /-- Probability mass functions, i.e. discrete probability measures -/ def {u} pmf (α : Type u) : Type u := { f : α → nnreal // has_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) := ⟨λp, α → nnreal, λp a, p.1 a⟩ @[ext] protected lemma ext : ∀{p q : pmf α}, (∀a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2 lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable @[simp] lemma tsum_coe (p : pmf α) : (∑a, p a) = 1 := tsum_eq_has_sum p.has_sum_coe_one def support (p : pmf α) : set α := {a | p.1 a ≠ 0} def pure (a : α) : pmf α := ⟨λa', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := has_sum_le (by intro b; split_ifs; simp [h]; exact le_refl _) (has_sum_ite_eq a (p a)) p.2 protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λa:α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λb, (∑a, p a * f a b), begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = (∑a, p a * f a b) := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ennreal) = (∑a, p a * f a b) := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λa, (f a).bind g) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λa, q.bind (f a)) = q.bind (λb, p.bind (λa, f a b)) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λm, p.bind $ λa, pure (m a)) def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λa, s.count a / s.card, have s.to_finset.sum (λa, (s.count a : ℝ) / s.card) = 1, by simp [div_eq_inv_mul, finset.mul_sum.symm, (finset.sum_nat_cast _ _).symm, hs], have s.to_finset.sum (λa, (s.count a : nnreal) / s.card) = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp, begin rw ← this, apply has_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ def of_fintype [fintype α] (f : α → nnreal) (h : finset.univ.sum f = 1) : pmf α := ⟨f, h ▸ has_sum_sum_of_ne_finset_zero (by simp)⟩ def bernoulli (p : nnreal) (h : p ≤ 1) : pmf bool := of_fintype (λb, cond b p (1 - p)) (nnreal.eq $ by simp [h]) end pmf
c5bac2080ba5a9332876bcf7f93cb8345c6bfdfc
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/Server/Watchdog.lean
48ee87e0773356099c717b312a149fdfbf8f0503
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,321
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 Init.Data.ByteArray import Std.Data.RBMap import Lean.Elab.Import import Lean.Data.Lsp import Lean.Server.Utils import Lean.Server.Requests /-! For general server architecture, see `README.md`. This module implements the watchdog process. ## Watchdog state Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes to the header and thus restart the corresponding worker, freeing its imports. TODO(WN): We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed (continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic, users may be confused about why the server seemingly stopped working for a single file. ## Watchdog <-> worker communication The watchdog process and its file worker processes communicate via LSP. If the necessity arises, we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications are forwarded to the corresponding file worker process, with the exception of these notifications: - textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to asynchronously receive LSP packets from the worker (e.g. request responses). - textDocument/didChange: Update the local file state. If the header was mutated, signal a shutdown to the file worker by closing the I/O channels. Then restart the file worker. Otherwise, forward the `didChange` notification. - textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state. Moreover, we don't implement the full protocol at this level: - Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker. - After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of the file. No additional `didOpen` notifications will be forwarded to the worker process. - `$/cancelRequest` notifications are forwarded to all file workers. - File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request. Similarly, they never receive a `didClose` notification. ## Watchdog <-> client communication The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add non-standard extensions in case they're needed, for example to communicate tactic state. -/ namespace Lean.Server.Watchdog open IO open Std (RBMap RBMap.empty) open Lsp open JsonRpc section Utils structure OpenDocument where meta : DocumentMeta headerAst : Syntax def workerCfg : Process.StdioConfig := { stdin := Process.Stdio.piped stdout := Process.Stdio.piped -- We pass workers' stderr through to the editor. stderr := Process.Stdio.inherit } /-- Events that worker-specific tasks signal to the main thread. -/ inductive WorkerEvent where /- A synthetic event signalling that the grouped edits should be processed. -/ | processGroupedEdits | terminated | crashed (e : IO.Error) | ioError (e : IO.Error) inductive WorkerState where /- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker and when reading a request reply. In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task. Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored. Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file worker arrives. -/ | crashed (queuedMsgs : Array JsonRpc.Message) | running abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare private def parseHeaderAst (input : String) : IO Syntax := do let inputCtx := Parser.mkInputContext input "<input>" let (stx, _, _) ← Parser.parseHeader inputCtx return stx end Utils section FileWorker /-- A group of edits which will be processed at a future instant. -/ structure GroupedEdits where /-- When to process the edits. -/ applyTime : Nat params : DidChangeTextDocumentParams /-- Signals when `applyTime` has been reached. -/ signalTask : Task WorkerEvent /-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/ queuedMsgs : Array JsonRpc.Message structure FileWorker where doc : OpenDocument proc : Process.Child workerCfg commTask : Task WorkerEvent state : WorkerState -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state /-- The pending requests map contains all requests that have been received from the LSP client, but were not answered yet. This includes the queued messages in the grouped edits. -/ pendingRequestsRef : IO.Ref PendingRequestMap groupedEditsRef : IO.Ref (Option GroupedEdits) namespace FileWorker def stdin (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdin def stdout (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdout def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit := fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty)) for ⟨id, _⟩ in pendingRequests do hError.writeLspResponseError { id := id, code := code, message := msg } partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do -- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification let rec loopAction : IO WorkerEvent := do let now ← monoMsNow let some ge ← fw.groupedEditsRef.get | throwServerError "Internal error: empty grouped edits reference in signal task" if ge.applyTime ≤ now then return WorkerEvent.processGroupedEdits else IO.sleep <| UInt32.ofNat <| ge.applyTime - now loopAction let t ← IO.asTask loopAction return t.map fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e end FileWorker end FileWorker section ServerM abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare structure ServerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream /-- Command line arguments. -/ args : List String fileWorkersRef : IO.Ref FileWorkerMap /-- We store these to pass them to workers. -/ initParams : InitializeParams editDelay : Nat workerPath : System.FilePath abbrev ServerM := ReaderT ServerContext IO def updateFileWorkers (val : FileWorker) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val) def findFileWorker? (uri : DocumentUri) : ServerM (Option FileWorker) := do (←(←read).fileWorkersRef.get).find? uri def findFileWorker! (uri : DocumentUri) : ServerM FileWorker := do let some fw ← findFileWorker? uri | throwServerError s!"cannot find open document '{uri}'" return fw def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri) def log (msg : String) : ServerM Unit := do let st ← read st.hLog.putStrLn msg st.hLog.flush /-- Creates a Task which forwards a worker's messages into the output stream until an event which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/ private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do let o := (←read).hOut let rec loop : ServerM WorkerEvent := do try let msg ← fw.stdout.readLspMessage if let Message.response id _ := msg then fw.erasePendingRequest id if let Message.responseError id _ _ _ := msg then fw.erasePendingRequest id -- Writes to Lean I/O channels are atomic, so these won't trample on each other. o.writeLspMessage msg catch err => -- If writeLspMessage from above errors we will block here, but the main task will -- quit eventually anyways if that happens let exitCode ← fw.proc.wait if exitCode = 0 then -- Worker was terminated fw.errorPendingRequests o ErrorCode.contentModified ("The file worker has been terminated. Either the header has changed," ++ " or the file was closed, or the server is shutting down.") return WorkerEvent.terminated else -- Worker crashed fw.errorPendingRequests o ErrorCode.internalError s!"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow in user code"}." return WorkerEvent.crashed err loop let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated task.map $ fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e def startFileWorker (m : DocumentMeta) : ServerM Unit := do publishProgressAtPos m 0 (← read).hOut let st ← read let headerAst ← parseHeaderAst m.text.source let workerProc ← Process.spawn { toStdioConfig := workerCfg cmd := st.workerPath.toString args := #["--worker"] ++ st.args.toArray } let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap) -- The task will never access itself, so this is fine let fw : FileWorker := { doc := ⟨m, headerAst⟩ proc := workerProc commTask := Task.pure WorkerEvent.terminated state := WorkerState.running pendingRequestsRef := pendingRequestsRef groupedEditsRef := ← IO.mkRef none } let commTask ← forwardMessages fw let fw : FileWorker := { fw with commTask := commTask } fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩ fw.stdin.writeLspNotification { method := "textDocument/didOpen" param := { textDocument := { uri := m.uri languageId := "lean" version := m.version text := m.text.source } : DidOpenTextDocumentParams } } updateFileWorkers fw def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do let fw ← findFileWorker! uri try fw.stdin.writeLspMessage (Message.notification "exit" none) catch _ => /- The file worker must have crashed just when we were about to terminate it! That's fine - just forget about it then. (on didClose we won't need the crashed file worker anymore, when the header changed we'll start a new one right after anyways and when we're shutting down the server it's over either way.) -/ return eraseFileWorker uri def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do updateFileWorkers { ←findFileWorker! uri with state := WorkerState.crashed queuedMsgs } /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed and restarts the file worker if the `crashed` flag was already set. Just logs an error if there is no FileWorker at this `uri`. Messages that couldn't be sent can be queued up via the queueFailedMessage flag and will be discharged after the FileWorker is restarted. -/ def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) : ServerM Unit := do let some fw ← findFileWorker? uri | do (←read).hLog.putStrLn s!"Cannot send message to unknown document '{uri}':\n{(toJson msg).compress}" return let pendingEdit ← fw.groupedEditsRef.modifyGet fun | some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg }) | none => (false, none) if pendingEdit then return match fw.state with | WorkerState.crashed queuedMsgs => let mut queuedMsgs := queuedMsgs if queueFailedMessage then queuedMsgs := queuedMsgs.push msg if !restartCrashedWorker then return -- restart the crashed FileWorker eraseFileWorker uri startFileWorker fw.doc.meta let newFw ← findFileWorker! uri let mut crashedMsgs := #[] -- try to discharge all queued msgs, tracking the ones that we can't discharge for msg in queuedMsgs do try newFw.stdin.writeLspMessage msg catch _ => crashedMsgs := crashedMsgs.push msg if ¬ crashedMsgs.isEmpty then handleCrash uri crashedMsgs | WorkerState.running => let initialQueuedMsgs := if queueFailedMessage then #[msg] else #[] try fw.stdin.writeLspMessage msg catch _ => handleCrash uri initialQueuedMsgs end ServerM section NotificationHandling def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit := let doc := p.textDocument /- 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. -/ startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleEdits (fw : FileWorker) : ServerM Unit := do let some ge ← fw.groupedEditsRef.modifyGet (·, none) | throwServerError "Internal error: empty grouped edits reference" let doc := ge.params.textDocument let changes := ge.params.contentChanges let oldDoc := fw.doc let some newVersion ← pure doc.version? | throwServerError "Expected version number" if newVersion <= oldDoc.meta.version then throwServerError "Got outdated version number" if changes.isEmpty then return let (newDocText, _) := foldDocumentChanges changes oldDoc.meta.text let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩ let newHeaderAst ← parseHeaderAst newDocText.source if newHeaderAst != oldDoc.headerAst then terminateFileWorker doc.uri startFileWorker newMeta else let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩ updateFileWorkers { fw with doc := newDoc } tryWriteMessage doc.uri (Notification.mk "textDocument/didChange" ge.params) (restartCrashedWorker := true) for msg in ge.queuedMsgs do tryWriteMessage doc.uri msg def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit := terminateFileWorker p.textDocument.uri def handleCancelRequest (p : CancelParams) : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, fw⟩ in fileWorkers do -- Cancelled requests still require a response, so they can't be removed -- from the pending requests map. if (← fw.pendingRequestsRef.get).contains p.id then tryWriteMessage uri (Notification.mk "$/cancelRequest" p) (queueFailedMessage := false) def forwardNotification {α : Type} [ToJson α] [FileSource α] (method : String) (params : α) : ServerM Unit := tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true) end NotificationHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM 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 handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let uri: DocumentUri ← -- This request is handled specially. if method == "$/lean/rpc/connect" then let ps ← parseParams Lsp.RpcConnectParams params fileSource ps else match (← routeLspRequest method params) with | Except.error e => (←read).hOut.writeLspResponseError <| e.toLspResponseError id return | Except.ok uri => uri let some fw ← findFileWorker? uri /- Clients may send requests to closed files, which we respond to with an error. For example, VSCode sometimes sends requests just after closing a file, and RPC clients may also do so, e.g. due to remaining timers. -/ | do (←read).hOut.writeLspResponseError { id := id /- Some clients (VSCode) also send requests *before* opening a file. We reply with `contentModified` as that does not display a "request failed" popup. -/ code := ErrorCode.contentModified message := s!"Cannot process request to closed file '{uri}'" } return let r := Request.mk id method params fw.pendingRequestsRef.modify (·.insert id r) tryWriteMessage uri r def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler) match method with | "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen /- NOTE: textDocument/didChange is handled in the main loop. -/ | "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose | "$/cancelRequest" => handle CancelParams handleCancelRequest | "$/lean/rpc/connect" => handle RpcConnectParams (forwardNotification method) | "$/lean/rpc/release" => handle RpcReleaseParams (forwardNotification method) | "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (forwardNotification method) | _ => if !"$/".isPrefixOf method then -- implementation-dependent notifications can be safely ignored (←read).hLog.putStrLn s!"Got unsupported notification: {method}" end MessageHandling section MainLoop def shutdown : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, _⟩ in fileWorkers do terminateFileWorker uri for ⟨_, fw⟩ in fileWorkers do discard <| IO.wait fw.commTask inductive ServerEvent where | workerEvent (fw : FileWorker) (ev : WorkerEvent) | clientMsg (msg : JsonRpc.Message) | clientError (e : IO.Error) def runClientTask : ServerM (Task ServerEvent) := do let st ← read let readMsgAction : IO ServerEvent := do /- Runs asynchronously. -/ let msg ← st.hIn.readLspMessage ServerEvent.clientMsg msg let clientTask := (←IO.asTask readMsgAction).map $ fun | Except.ok ev => ev | Except.error e => ServerEvent.clientError e return clientTask partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do let st ← read let workers ← st.fileWorkersRef.get let mut workerTasks := #[] for (_, fw) in workers do if let WorkerState.running := fw.state then workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw) if let some ge ← fw.groupedEditsRef.get then workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw) let ev ← IO.waitAny (workerTasks.push clientTask |>.toList) match ev with | ServerEvent.clientMsg msg => match msg with | Message.request id "shutdown" _ => shutdown st.hOut.writeLspResponse ⟨id, Json.null⟩ | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop (←runClientTask) | Message.notification "textDocument/didChange" (some params) => let p ← parseParams DidChangeTextDocumentParams (toJson params) let fw ← findFileWorker! p.textDocument.uri let now ← monoMsNow /- We wait `editDelay`ms since last edit before applying the changes. -/ let applyTime := now + st.editDelay let queuedMsgs? ← fw.groupedEditsRef.modifyGet fun | some ge => (some ge.queuedMsgs, some { ge with applyTime := applyTime params.textDocument := p.textDocument params.contentChanges := ge.params.contentChanges ++ p.contentChanges -- drain now-outdated messages and respond with `contentModified` below queuedMsgs := #[] }) | none => (none, some { applyTime := applyTime params := p /- This is overwritten just below. -/ signalTask := Task.pure WorkerEvent.processGroupedEdits queuedMsgs := #[] }) match queuedMsgs? with | some queuedMsgs => for msg in queuedMsgs do match msg with | JsonRpc.Message.request id _ _ => fw.erasePendingRequest id (← read).hOut.writeLspResponseError { id := id code := ErrorCode.contentModified message := "File changed." } | _ => () -- notifications do not need to be cancelled | _ => let t ← fw.runEditsSignalTask fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } ) mainLoop (←runClientTask) | Message.notification method (some params) => handleNotification method (toJson params) mainLoop (←runClientTask) | _ => throwServerError "Got invalid JSON-RPC message" | ServerEvent.clientError e => throw e | ServerEvent.workerEvent fw ev => match ev with | WorkerEvent.processGroupedEdits => handleEdits fw mainLoop clientTask | WorkerEvent.ioError e => throwServerError s!"IO error while processing events for {fw.doc.meta.uri}: {e}" | WorkerEvent.crashed e => handleCrash fw.doc.meta.uri #[] mainLoop clientTask | WorkerEvent.terminated => throwServerError "Internal server error: got termination event for worker that should have been removed" end MainLoop def mkLeanServerCapabilities : ServerCapabilities := { textDocumentSync? := some { openClose := true change := TextDocumentSyncKind.incremental willSave := false willSaveWaitUntil := false save? := none } -- refine completionProvider? := some { triggerCharacters? := some #["."] } hoverProvider := true declarationProvider := true definitionProvider := true typeDefinitionProvider := true documentHighlightProvider := true documentSymbolProvider := true semanticTokensProvider? := some { legend := { tokenTypes := SemanticTokenType.names tokenModifiers := #[] } full := true range := true } } def initAndRunWatchdogAux : ServerM Unit := do let st ← read try discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams let clientTask ← runClientTask mainLoop clientTask catch err => shutdown throw err /- NOTE(WN): It looks like instead of sending the `exit` notification, VSCode just closes the stream. In that case, pretend we got an `exit`. -/ let Message.notification "exit" none ← try st.hIn.readLspMessage catch _ => pure (Message.notification "exit" none) | throwServerError "Got `shutdown` request, expected an `exit` notification" def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do let mut workerPath ← IO.appPath if let some path := (←IO.getEnv "LEAN_SYSROOT") then workerPath := System.FilePath.mk path / "bin" / "lean" |>.withExtension System.FilePath.exeExtension if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then workerPath := System.FilePath.mk path let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap) let i ← maybeTee "wdIn.txt" false i let o ← maybeTee "wdOut.txt" true o let e ← maybeTee "wdErr.txt" true e let initRequest ← i.readLspRequestAs "initialize" InitializeParams o.writeLspResponse { id := initRequest.id result := { capabilities := mkLeanServerCapabilities serverInfo? := some { name := "Lean 4 Server" version? := "0.1" } : InitializeResult } } ReaderT.run initAndRunWatchdogAux { hIn := i hOut := o hLog := e args := args fileWorkersRef := fileWorkersRef initParams := initRequest.param editDelay := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200 workerPath := workerPath : ServerContext } @[export lean_server_watchdog_main] def watchdogMain (args : List String) : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWatchdog args i o e return 0 catch err => e.putStrLn s!"Watchdog error: {err}" return 1 end Lean.Server.Watchdog
ffd0c318cd6fa13686aa5e6a433152a1df53bd9b
f02b05b665ad2d2cd970e93758a98d57f310a822
/src/tactic/tcache/store.lean
ca74e148a5d44c390044b616a006e66a88c6513b
[]
no_license
khoek/leancache
b0ed5d2a9a2e87f58d4ad27343d957a9cd49ce5f
5c8329f7b647b8d82966ab180c4473b20d1f249c
refs/heads/master
1,585,344,140,717
1,549,094,327,000
1,549,094,327,000
147,138,187
0
0
null
null
null
null
UTF-8
Lean
false
false
4,235
lean
import system.io import .io import .serial universe u open tactic namespace tcache section open interaction_monad meta def resolve : option (unit → format) → string | none := "" | (some e) := to_string $ e () meta def interaction_monad_orelse' {α : Type u} (t₁ : tactic α) (t₂ : string → tactic α) : tactic α := λ s, result.cases_on (t₁ s) result.success (λ e ref₁ s', result.cases_on (t₂ (resolve e) s) result.success result.exception ) end meta def trace {α : Type u} [has_to_tactic_format α] (hash : string) (a : thunk α) : tactic unit := do f ← has_to_tactic_format.to_tactic_format $ a (), when_tracing `tcache $ tactic.trace $ format!"tc@{hash} - {f}" meta def timeit {α : Type u} (hash s : string) (f : thunk α) : α := if is_trace_enabled_for `tcache then _root_.timeit sformat!"tc@{hash} - {s}" (f ()) else f () meta def timetac {α : Type u} (hash s : string) (f : thunk (tactic α)) : tactic α := if is_trace_enabled_for `tcache then tactic.timetac sformat!"tc@{hash} - {s}" (f ()) else f () meta def sanitize_expr : expr → expr | (expr.const n l) := expr.const n l | (expr.app f a) := expr.app (sanitize_expr f) (sanitize_expr a) | (expr.sort l) := expr.sort l | (expr.pi n bi t v) := expr.pi n bi (sanitize_expr t) (sanitize_expr v) | (expr.lam n bi t v) := expr.lam n bi (sanitize_expr t) (sanitize_expr v) | (expr.var n) := expr.var n | (expr.local_const n₁ n₂ bi v) := expr.const n₂ [] | (expr.mvar _ _ _) := expr.const name.anonymous [] | (expr.macro m _) := expr.const (expr.macro_def_name m) [] -- Do something with the `expr` list? | (expr.elet _ _ _ _) := error "cannot sanitize elet!" meta def hash_goal (e : expr) : tactic ℕ := do t ← infer_type e, return $ (sanitize_expr t).hash meta def hash_goals (n : name) : tactic string := do -- FIXME this xor is probably really slow v ← get_goals >>= list.mfoldl (λ v d, nat.lxor v <$> hash_goal d) 0, return sformat!"{n}.{v}" meta def cache_file_name (hash : string) : string := CACHE_DIR ++ "/" ++ hash ++ ".leancache" meta def find_local_const (n : name) : list expr → expr | [] := error sformat!"unknown const {n}" | (e :: rest) := if e.local_pp_name = n then e else find_local_const rest meta def fixup_local_consts (lc : list expr) : expr → nat → option expr | (expr.local_const _ n _ _) _ := some $ find_local_const n lc | _ _ := none variables (hash : string) meta def solve_goal (pf : expr) : tactic unit := exact pf >> done meta def deserialise_proof : io expr := do h ← io.mk_file_handle (cache_file_name hash) io.mode.read tt, pf ← io.deserialize h, io.fs.close h, return pf meta def handle_recall_failed (pf : expr) (msg : string) : tactic unit := do s₂ ← infer_type pf, trace hash sformat!"failed to recall proof: {msg}\n\n{pf.to_raw_fmt}\n\n{s₂.to_raw_fmt}" meta def try_cache (n : name) (lc : list expr) : tactic unit := do pf ← timetac hash "deserialising proof" $ unsafe_run_io $ deserialise_proof hash, let pf := timeit hash "loading proof took" (pf.replace $ fixup_local_consts lc), interaction_monad_orelse' (solve_goal pf) (handle_recall_failed hash pf) meta def put_cache (n : name) (lc : list expr) (e : expr) : tactic unit := do interaction_monad_orelse' (do unsafe_run_io $ do { h ← io.mk_file_handle (cache_file_name hash) io.mode.write tt, io.serialize h e, io.fs.close h } ) $ λ msg, trace hash sformat!"proof serialisation failure: {msg}\n\n{e}\n\n{e.to_raw_fmt}" meta def execute_capture (n : name) (t : tactic unit) : tactic expr := do [m] ← get_goals, t >> done, instantiate_mvars m meta def try_recompute (n : name) (lc : list expr) (hash : string) (t : tactic unit) : tactic unit := do trace hash "need to regenerate proof", e ← timetac hash "success, took" $ execute_capture n t, put_cache hash n lc e meta def discharge_goals (t : tactic unit) : tactic unit := do n ← decl_name, hash ← hash_goals n, lc ← local_context, try_cache hash n lc <|> try_recompute n lc hash t meta def init_tcache : tactic unit := tactic.unsafe_run_io mk_cache_dir meta def clear_tcache : tactic unit := tactic.unsafe_run_io rm_cache_dir end tcache
44a6082f0e6a6552e04bb140c20da632bcdf7040
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/homotopy/torus.hlean
61e60749776f3b9acfcf71fdb704b7026d41e55f
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,547
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the torus -/ import hit.two_quotient open two_quotient eq bool unit relation namespace torus definition torus_R (x y : unit) := bool local infix `⬝r`:75 := @e_closure.trans unit torus_R star star star local postfix `⁻¹ʳ`:(max+10) := @e_closure.symm unit torus_R star star local notation `[`:max a `]`:0 := @e_closure.of_rel unit torus_R star star a inductive torus_Q : Π⦃x y : unit⦄, e_closure torus_R x y → e_closure torus_R x y → Type := | Qmk : torus_Q ([ff] ⬝r [tt]) ([tt] ⬝r [ff]) definition torus := two_quotient torus_R torus_Q definition base : torus := incl0 _ _ star definition loop1 : base = base := incl1 _ _ ff definition loop2 : base = base := incl1 _ _ tt definition surf : loop1 ⬝ loop2 = loop2 ⬝ loop1 := incl2 _ _ torus_Q.Qmk -- protected definition rec {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- (x : torus) : P x := -- sorry -- example {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) (Pl2 : Pb =[loop2] Pb) -- (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) : torus.rec Pb Pl1 Pl2 Pf base = Pb := idp -- definition rec_loop1 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop1 = Pl1 := -- sorry -- definition rec_loop2 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop2 = Pl2 := -- sorry -- definition rec_surf {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : cubeover P rfl1 (apds (torus.rec Pb Pl1 Pl2 Pf) fill) Pf -- (vdeg_squareover !rec_loop2) (vdeg_squareover !rec_loop2) -- (vdeg_squareover !rec_loop1) (vdeg_squareover !rec_loop1) := -- sorry protected definition elim {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) (x : torus) : P := begin induction x, { exact Pb}, { induction s, { exact Pl1}, { exact Pl2}}, { induction q, exact Ps}, end protected definition elim_on [reducible] {P : Type} (x : torus) (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : P := torus.elim Pb Pl1 Pl2 Ps x definition elim_loop1 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop1 = Pl1 := !elim_incl1 definition elim_loop2 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop2 = Pl2 := !elim_incl1 theorem elim_surf {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : square (ap02 (torus.elim Pb Pl1 Pl2 Ps) surf) Ps (!ap_con ⬝ (!elim_loop1 ◾ !elim_loop2)) (!ap_con ⬝ (!elim_loop2 ◾ !elim_loop1)) := !elim_incl2 end torus attribute torus.base [constructor] attribute /-torus.rec-/ torus.elim [unfold 6] [recursor 6] --attribute torus.elim_type [unfold 9] attribute /-torus.rec_on-/ torus.elim_on [unfold 2] --attribute torus.elim_type_on [unfold 6]
c93ea6cef4e042c5565d8247aeb86e84fb0a84a8
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/ring_theory/discrete_valuation_ring.lean
07ad6a74f82b3845b66b2ced0adb5afe3ba38486
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,185
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import ring_theory.principal_ideal_domain import order.conditionally_complete_lattice import ring_theory.multiplicity import ring_theory.valuation.basic /-! # Discrete valuation rings This file defines discrete valuation rings (DVRs) and develops a basic interface for them. ## Important definitions There are various definitions of a DVR in the literature; we define a DVR to be a local PID which is not a field (the first definition in Wikipedia) and prove that this is equivalent to being a PID with a unique non-zero prime ideal (the definition in Serre's book "Local Fields"). Let R be an integral domain, assumed to be a principal ideal ring and a local ring. * `discrete_valuation_ring R` : a predicate expressing that R is a DVR ### Definitions * `add_val R : add_valuation R enat` : the additive valuation on a DVR. ## Implementation notes It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible. We do not hence define `uniformizer` at all, because we can use `irreducible` instead. ## Tags discrete valuation ring -/ open_locale classical universe u open ideal local_ring /-- An integral domain is a *discrete valuation ring* (DVR) if it's a local PID which is not a field. -/ class discrete_valuation_ring (R : Type u) [integral_domain R] extends is_principal_ideal_ring R, local_ring R : Prop := (not_a_field' : maximal_ideal R ≠ ⊥) namespace discrete_valuation_ring variables (R : Type u) [integral_domain R] [discrete_valuation_ring R] lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field' variable {R} open principal_ideal_ring /-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the maximal ideal of R -/ theorem irreducible_iff_uniformizer (ϖ : R) : irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} := ⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm, begin intro h, have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R, from h.symm ▸ submodule.mem_span_singleton_self ϖ, refine ⟨h2, _⟩, intros a b hab, by_contra h, push_neg at h, obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h, rw h at ha hb, rw mem_span_singleton' at ha hb, rcases ha with ⟨a, rfl⟩, rcases hb with ⟨b, rfl⟩, rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab, have h3 := eq_zero_of_mul_eq_self_right _ hab.symm, { apply not_a_field R, simp [h, h3] }, { intro hh, apply h2, refine is_unit_of_dvd_one ϖ _, use a * b, exact hh.symm } end⟩ variable (R) /-- Uniformisers exist in a DVR -/ theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ := by {simp_rw [irreducible_iff_uniformizer], exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal} /-- Uniformisers exist in a DVR -/ theorem exists_prime : ∃ ϖ : R, prime ϖ := (exists_irreducible R).imp (λ _, principal_ideal_ring.irreducible_iff_prime.1) /-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/ theorem iff_pid_with_one_nonzero_prime (R : Type u) [integral_domain R] : discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P := begin split, { intro RDVR, rcases id RDVR with ⟨RPID, Rlocal, Rnotafield⟩, split, assumption, resetI, use local_ring.maximal_ideal R, split, split, { assumption }, { apply_instance } , { rintro Q ⟨hQ1, hQ2⟩, obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1, have hq : q ≠ 0, { rintro rfl, apply hQ1, simp }, erw span_singleton_prime hq at hQ2, replace hQ2 := hQ2.irreducible, rw irreducible_iff_uniformizer at hQ2, exact hQ2.symm } }, { rintro ⟨RPID, Punique⟩, haveI : local_ring R := local_of_unique_nonzero_prime R Punique, refine {not_a_field' := _}, rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩, have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1), intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM } end lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) : associated a b := begin rw irreducible_iff_uniformizer at ha hb, rw [←span_singleton_eq_span_singleton, ←ha, hb], end end discrete_valuation_ring namespace discrete_valuation_ring variable (R : Type*) /-- Alternative characterisation of discrete valuation rings. -/ def has_unit_mul_pow_irreducible_factorization [integral_domain R] : Prop := ∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x namespace has_unit_mul_pow_irreducible_factorization variables {R} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) include hR lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin rcases hR with ⟨ϖ, hϖ, hR⟩, suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ, { apply associated.trans (this hp) (this hq).symm, }, clear hp hq p q, intros p hp, obtain ⟨n, hn⟩ := hR hp.ne_zero, have : irreducible (ϖ ^ n) := hn.symm.irreducible hp, rcases lt_trichotomy n 1 with (H|rfl|H), { obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial }, simpa only [not_irreducible_one, pow_zero] using this, }, { simpa only [pow_one] using hn.symm, }, { obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H, rw pow_succ at this, rcases this.is_unit_or_is_unit rfl with H0|H0, { exact (hϖ.not_unit H0).elim, }, { rw [add_comm, pow_succ] at H0, exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } } end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a unique factorization domain. See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/ theorem to_unique_factorization_monoid : unique_factorization_monoid R := let p := classical.some hR in let spec := classical.some_spec hR in unique_factorization_monoid.of_exists_prime_factors $ λ x hx, begin use multiset.repeat p (classical.some (spec.2 hx)), split, { intros q hq, have hpq := multiset.eq_of_mem_repeat hq, rw hpq, refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩, intros a b h, by_cases ha : a = 0, { rw ha, simp only [true_or, dvd_zero], }, by_cases hb : b = 0, { rw hb, simp only [or_true, dvd_zero], }, obtain ⟨m, u, rfl⟩ := spec.2 ha, rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (units.is_unit _)] at h, rw is_unit.dvd_mul_right (units.is_unit _), by_cases hm : m = 0, { simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h }, left, obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm, rw pow_succ, apply dvd_mul_of_dvd_left (dvd_refl _) _ }, { rw [multiset.prod_repeat], exact (classical.some_spec (spec.2 hx)), } end omit hR lemma of_ufd_of_unique_irreducible [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : has_unit_mul_pow_irreducible_factorization R := begin obtain ⟨p, hp⟩ := h₁, refine ⟨p, hp, _⟩, intros x hx, cases wf_dvd_monoid.exists_factors x hx with fx hfx, refine ⟨fx.card, _⟩, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, symmetry, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ q hq rfl, rw associates.mk_eq_mk_iff_associated, apply h₂ (hfx.1 _ hq) hp, end end has_unit_mul_pow_irreducible_factorization lemma aux_pid_of_ufd_of_unique_irreducible (R : Type u) [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : is_principal_ideal_ring R := begin constructor, intro I, by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], }, obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0, obtain ⟨p, hp, H⟩ := has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂, have ex : ∃ n : ℕ, p ^ n ∈ I, { obtain ⟨n, u, rfl⟩ := H hx0, refine ⟨n, _⟩, simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hxI, }, constructor, use p ^ (nat.find ex), show I = ideal.span _, apply le_antisymm, { intros r hr, by_cases hr0 : r = 0, { simp only [hr0, submodule.zero_mem], }, obtain ⟨n, u, rfl⟩ := H hr0, simp only [mem_span_singleton, units.is_unit, is_unit.dvd_mul_right], apply pow_dvd_pow, apply nat.find_min', simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hr, }, { erw submodule.span_singleton_le_iff_mem, exact nat.find_spec ex, }, end /-- A unique factorization domain with at least one irreducible element in which all irreducible elements are associated is a discrete valuation ring. -/ lemma of_ufd_of_unique_irreducible {R : Type u} [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : discrete_valuation_ring R := begin rw iff_pid_with_one_nonzero_prime, haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂, obtain ⟨p, hp⟩ := h₁, refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩, { rw submodule.ne_bot_iff, refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, }, { rwa [ideal.span_singleton_prime hp.ne_zero, ← unique_factorization_monoid.irreducible_iff_prime], }, { intro I, rw ← submodule.is_principal.span_singleton_generator I, rintro ⟨I0, hI⟩, apply span_singleton_eq_span_singleton.mpr, apply h₂ _ hp, erw [ne.def, span_singleton_eq_bot] at I0, rwa [unique_factorization_monoid.irreducible_iff_prime, ← ideal.span_singleton_prime I0], }, end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a discrete valuation ring. -/ lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) : discrete_valuation_ring R := begin letI : unique_factorization_monoid R := hR.to_unique_factorization_monoid, apply of_ufd_of_unique_irreducible _ hR.unique_irreducible, unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, }, end section variables [integral_domain R] [discrete_valuation_ring R] variable {R} lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ), associated x (ϖ ^ n) := begin have : wf_dvd_monoid R := is_noetherian_ring.wf_dvd_monoid, cases wf_dvd_monoid.exists_factors x hx with fx hfx, unfreezingI { use fx.card }, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ _ _ rfl, rw associates.mk_eq_mk_iff_associated, refine associated_of_irreducible _ _ hirr, apply hfx.1, assumption end lemma eq_unit_mul_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ) (u : units R), x = u * ϖ ^ n := begin obtain ⟨n, hn⟩ := associated_pow_irreducible hx hirr, obtain ⟨u, rfl⟩ := hn.symm, use [n, u], apply mul_comm, end open submodule.is_principal lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) : ∃ n : ℕ, s = ideal.span {ϖ ^ n} := begin have gen_ne_zero : generator s ≠ 0, { rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption }, rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩, use n, have : span _ = _ := span_singleton_generator s, rw [← this, ← hnu, span_singleton_eq_span_singleton], use u end lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q) (u v : units R) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) : m = n := begin have key : associated (multiset.repeat p m).prod (multiset.repeat q n).prod, { rw [multiset.prod_repeat, multiset.prod_repeat, associated], refine ⟨u * v⁻¹, _⟩, simp only [units.coe_mul], rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], }, have := multiset.card_eq_card_of_rel (unique_factorization_monoid.factors_unique _ _ key), { simpa only [multiset.card_repeat] }, all_goals { intros x hx, replace hx := multiset.eq_of_mem_repeat hx, unfreezingI { subst hx, assumption } }, end lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : units R) (m n : ℕ) (h : ↑u * ϖ ^ m = v * ϖ ^ n) : u = v := begin obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h, rw ← sub_eq_zero at h, rw [← sub_mul, mul_eq_zero] at h, cases h, { rw sub_eq_zero at h, exact_mod_cast h }, { apply (hirr.ne_zero (pow_eq_zero h)).elim, } end /-! ## The additive valuation on a DVR -/ open multiplicity /-- The `enat`-valued additive valuation on a DVR -/ noncomputable def add_val (R : Type u) [integral_domain R] [discrete_valuation_ring R] : add_valuation R enat := add_valuation (classical.some_spec (exists_prime R)) lemma add_val_def (r : R) (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) (hr : r = u * ϖ ^ n) : add_val R r = n := by rw [add_val, add_valuation_apply, hr, eq_of_associated_left (associated_of_irreducible R hϖ (classical.some_spec (exists_prime R)).irreducible), eq_of_associated_right (associated.symm ⟨u, mul_comm _ _⟩), multiplicity_pow_self_of_prime (principal_ideal_ring.irreducible_iff_prime.1 hϖ)] lemma add_val_def' (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) : add_val R ((u : R) * ϖ ^ n) = n := add_val_def _ u hϖ n rfl @[simp] lemma add_val_zero : add_val R 0 = ⊤ := (add_val R).map_zero @[simp] lemma add_val_one : add_val R 1 = 0 := (add_val R).map_one @[simp] lemma add_val_uniformizer {ϖ : R} (hϖ : irreducible ϖ) : add_val R ϖ = 1 := add_val_def ϖ 1 hϖ 1 (by simp) @[simp] lemma add_val_mul {a b : R} : add_val R (a * b) = add_val R a + add_val R b := (add_val R).map_mul _ _ lemma add_val_pow (a : R) (n : ℕ) : add_val R (a ^ n) = n • add_val R a := (add_val R).map_pow _ _ lemma add_val_eq_top_iff {a : R} : add_val R a = ⊤ ↔ a = 0 := begin have hi := (classical.some_spec (exists_prime R)).irreducible, split, { contrapose, intro h, obtain ⟨n, ha⟩ := associated_pow_irreducible h hi, obtain ⟨u, rfl⟩ := ha.symm, rw [mul_comm, add_val_def' u hi n], exact enat.coe_ne_top _ }, { rintro rfl, exact add_val_zero } end lemma add_val_le_iff_dvd {a b : R} : add_val R a ≤ add_val R b ↔ a ∣ b := begin have hp := classical.some_spec (exists_prime R), split; intro h, { by_cases ha0 : a = 0, { rw [ha0, add_val_zero, top_le_iff, add_val_eq_top_iff] at h, rw h, apply dvd_zero }, obtain ⟨n, ha⟩ := associated_pow_irreducible ha0 hp.irreducible, rw [add_val, add_valuation_apply, add_valuation_apply, multiplicity_le_multiplicity_iff] at h, exact ha.dvd.trans (h n ha.symm.dvd), }, { rw [add_val, add_valuation_apply, add_valuation_apply], exact multiplicity_le_multiplicity_of_dvd_right h } end lemma add_val_add {a b : R} : min (add_val R a) (add_val R b) ≤ add_val R (a + b) := (add_val R).map_add _ _ end end discrete_valuation_ring
f3d69e9b419422483290eb545c4e5caa3d0e7441
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Server/FileSource.lean
19018f5306af3e139ba8f1823f6bbb71b2d6598e
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
2,920
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga -/ import Lean.Data.Lsp namespace Lean namespace Lsp class FileSource (α : Type) where fileSource : α → DocumentUri export FileSource (fileSource) instance Location.hasFileSource : FileSource Location := ⟨fun l => l.uri⟩ instance TextDocumentIdentifier.hasFileSource : FileSource TextDocumentIdentifier := ⟨fun i => i.uri⟩ instance VersionedTextDocumentIdentifier.hasFileSource : FileSource VersionedTextDocumentIdentifier := ⟨fun i => i.uri⟩ instance TextDocumentEdit.hasFileSource : FileSource TextDocumentEdit := ⟨fun e => fileSource e.textDocument⟩ instance TextDocumentItem.hasFileSource : FileSource TextDocumentItem := ⟨fun i => i.uri⟩ instance TextDocumentPositionParams.hasFileSource : FileSource TextDocumentPositionParams := ⟨fun p => fileSource p.textDocument⟩ instance DidOpenTextDocumentParams.hasFileSource : FileSource DidOpenTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance DidChangeTextDocumentParams.hasFileSource : FileSource DidChangeTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance DidCloseTextDocumentParams.hasFileSource : FileSource DidCloseTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance CompletionParams.hasFileSource : FileSource CompletionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance HoverParams.hasFileSource : FileSource HoverParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance DeclarationParams.hasFileSource : FileSource DeclarationParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance DefinitionParams.hasFileSource : FileSource DefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance TypeDefinitionParams.hasFileSource : FileSource TypeDefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance WaitForDiagnosticsParams.hasFileSource : FileSource WaitForDiagnosticsParams := ⟨fun p => p.uri⟩ instance DocumentHighlightParams.hasFileSource : FileSource DocumentHighlightParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance DocumentSymbolParams.hasFileSource : FileSource DocumentSymbolParams := ⟨fun p => fileSource p.textDocument⟩ instance SemanticTokensParams.hasFileSource : FileSource SemanticTokensParams := ⟨fun p => fileSource p.textDocument⟩ instance SemanticTokensRangeParams.hasFileSource : FileSource SemanticTokensRangeParams := ⟨fun p => fileSource p.textDocument⟩ instance PlainGoalParams.hasFileSource : FileSource PlainGoalParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource PlainTermGoalParams where fileSource p := fileSource p.textDocument end Lsp end Lean
e5aa334f3956311af54e65128e9bb7dadb4612a8
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/nat/choose/central.lean
220d0d421fab84ee51602f3ce78f3fd4da4b5436
[ "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
5,191
lean
/- Copyright (c) 2021 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens, Thomas Browning -/ import data.nat.choose.basic import data.nat.choose.sum /-! # Central binomial coefficients This file proves properties of the central binomial coefficients (that is, `nat.choose (2 * n) n`). ## Main definition and results * `nat.central_binom`: the central binomial coefficient, `(2 * n).choose n`. * `nat.succ_mul_central_binom_succ`: the inductive relationship between successive central binomial coefficients. * `nat.four_pow_lt_mul_central_binom`: an exponential lower bound on the central binomial coefficient. * `succ_dvd_central_binom`: The result that `n+1 ∣ n.central_binom`, ensuring that the explicit definition of the Catalan numbers is integer-valued. -/ namespace nat /-- The central binomial coefficient, `nat.choose (2 * n) n`. -/ def central_binom (n : ℕ) := (2 * n).choose n lemma central_binom_eq_two_mul_choose (n : ℕ) : central_binom n = (2 * n).choose n := rfl lemma central_binom_pos (n : ℕ) : 0 < central_binom n := choose_pos (nat.le_mul_of_pos_left zero_lt_two) lemma central_binom_ne_zero (n : ℕ) : central_binom n ≠ 0 := (central_binom_pos n).ne' @[simp] lemma central_binom_zero : central_binom 0 = 1 := choose_zero_right _ /-- The central binomial coefficient is the largest binomial coefficient. -/ lemma choose_le_central_binom (r n : ℕ) : choose (2 * n) r ≤ central_binom n := calc (2 * n).choose r ≤ (2 * n).choose (2 * n / 2) : choose_le_middle r (2 * n) ... = (2 * n).choose n : by rw nat.mul_div_cancel_left n zero_lt_two lemma two_le_central_binom (n : ℕ) (n_pos : 0 < n) : 2 ≤ central_binom n := calc 2 ≤ 2 * n : le_mul_of_pos_right n_pos ... = (2 * n).choose 1 : (choose_one_right (2 * n)).symm ... ≤ central_binom n : choose_le_central_binom 1 n /-- An inductive property of the central binomial coefficient. -/ lemma succ_mul_central_binom_succ (n : ℕ) : (n + 1) * central_binom (n + 1) = 2 * (2 * n + 1) * central_binom n := calc (n + 1) * (2 * (n + 1)).choose (n + 1) = (2 * n + 2).choose (n + 1) * (n + 1) : mul_comm _ _ ... = (2 * n + 1).choose n * (2 * n + 2) : by rw [choose_succ_right_eq, choose_mul_succ_eq] ... = 2 * ((2 * n + 1).choose n * (n + 1)) : by ring ... = 2 * ((2 * n + 1).choose n * ((2 * n + 1) - n)) : by rw [two_mul n, add_assoc, nat.add_sub_cancel_left] ... = 2 * ((2 * n).choose n * (2 * n + 1)) : by rw choose_mul_succ_eq ... = (2 * (2 * n + 1)) * (2 * n).choose n : by rw [mul_assoc, mul_comm (2 * n + 1)] /-- An exponential lower bound on the central binomial coefficient. This bound is of interest because it appears in [Tochiori's refinement of Erdős's proof of Bertrand's postulate](tochiori_bertrand). -/ lemma four_pow_lt_mul_central_binom (n : ℕ) (n_big : 4 ≤ n) : 4 ^ n < n * central_binom n := begin induction n using nat.strong_induction_on with n IH, rcases lt_trichotomy n 4 with (hn|rfl|hn), { clear IH, dec_trivial! }, { norm_num [central_binom, choose] }, obtain ⟨n, rfl⟩ : ∃ m, n = m + 1 := nat.exists_eq_succ_of_ne_zero (zero_lt_four.trans hn).ne', calc 4 ^ (n + 1) < 4 * (n * central_binom n) : (mul_lt_mul_left zero_lt_four).mpr (IH n n.lt_succ_self (nat.le_of_lt_succ hn)) ... ≤ 2 * (2 * n + 1) * central_binom n : by { rw ← mul_assoc, linarith } ... = (n + 1) * central_binom (n + 1) : (succ_mul_central_binom_succ n).symm, end /-- An exponential lower bound on the central binomial coefficient. This bound is weaker than `four_pow_n_lt_n_mul_central_binom`, but it is of historical interest because it appears in Erdős's proof of Bertrand's postulate. -/ lemma four_pow_le_two_mul_self_mul_central_binom : ∀ (n : ℕ) (n_pos : 0 < n), 4 ^ n ≤ (2 * n) * central_binom n | 0 pr := (nat.not_lt_zero _ pr).elim | 1 pr := by norm_num [central_binom, choose] | 2 pr := by norm_num [central_binom, choose] | 3 pr := by norm_num [central_binom, choose] | n@(m + 4) _ := calc 4 ^ n ≤ n * central_binom n : (four_pow_lt_mul_central_binom _ le_add_self).le ... ≤ 2 * n * central_binom n : by { rw [mul_assoc], refine le_mul_of_pos_left zero_lt_two } lemma two_dvd_central_binom_succ (n : ℕ) : 2 ∣ central_binom (n + 1) := begin use (n+1+n).choose n, rw [central_binom_eq_two_mul_choose, two_mul, ← add_assoc, choose_succ_succ, choose_symm_add, ← two_mul], end lemma two_dvd_central_binom_of_one_le {n : ℕ} (h : 0 < n) : 2 ∣ central_binom n := begin rw ← nat.succ_pred_eq_of_pos h, exact two_dvd_central_binom_succ n.pred, end /-- A crucial lemma to ensure that Catalan numbers can be defined via their explicit formula `catalan n = n.central_binom / (n + 1)`. -/ lemma succ_dvd_central_binom (n : ℕ) : (n + 1) ∣ n.central_binom := begin have h_s : (n+1).coprime (2*n+1), { rw [two_mul,add_assoc, coprime_add_self_right, coprime_self_add_left], exact coprime_one_left n }, apply h_s.dvd_of_dvd_mul_left, apply dvd_of_mul_dvd_mul_left zero_lt_two, rw [← mul_assoc, ← succ_mul_central_binom_succ, mul_comm], exact mul_dvd_mul_left _ (two_dvd_central_binom_succ n), end end nat
8a1ccb05a70661fc3b01e91be5014c3b19003b45
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/skeletal.lean
25c170bad667784a6b2508925e8ad993a324abb5
[ "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
10,582
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.isomorphism_classes import category_theory.thin /-! # Skeleton of a category Define skeletal categories as categories in which any two isomorphic objects are equal. Construct the skeleton of an arbitrary category by taking isomorphism classes, and show it is a skeleton of the original category. In addition, construct the skeleton of a thin category as a partial ordering, and (noncomputably) show it is a skeleton of the original category. The advantage of this special case being handled separately is that lemmas and definitions about orderings can be used directly, for example for the subobject lattice. In addition, some of the commutative diagrams about the functors commute definitionally on the nose which is convenient in practice. -/ universes v₁ v₂ v₃ u₁ u₂ u₃ namespace category_theory open category variables (C : Type u₁) [category.{v₁} C] variables (D : Type u₂) [category.{v₂} D] variables {E : Type u₃} [category.{v₃} E] /-- A category is skeletal if isomorphic objects are equal. -/ def skeletal : Prop := ∀ ⦃X Y : C⦄, is_isomorphic X Y → X = Y /-- `is_skeleton_of C D F` says that `F : D ⥤ C` exhibits `D` as a skeletal full subcategory of `C`, in particular `F` is a (strong) equivalence and `D` is skeletal. -/ structure is_skeleton_of (F : D ⥤ C) := (skel : skeletal D) (eqv : is_equivalence F) local attribute [instance] is_isomorphic_setoid variables {C D} /-- If `C` is thin and skeletal, then any naturally isomorphic functors to `C` are equal. -/ lemma functor.eq_of_iso {F₁ F₂ : D ⥤ C} [∀ X Y : C, subsingleton (X ⟶ Y)] (hC : skeletal C) (hF : F₁ ≅ F₂) : F₁ = F₂ := functor.ext (λ X, hC ⟨hF.app X⟩) (λ _ _ _, subsingleton.elim _ _) /-- If `C` is thin and skeletal, `D ⥤ C` is skeletal. `category_theory.functor_thin` shows it is thin also. -/ lemma functor_skeletal [∀ X Y : C, subsingleton (X ⟶ Y)] (hC : skeletal C) : skeletal (D ⥤ C) := λ F₁ F₂ h, h.elim (functor.eq_of_iso hC) variables (C D) /-- Construct the skeleton category as the induced category on the isomorphism classes, and derive its category structure. -/ @[derive category] def skeleton : Type u₁ := induced_category C quotient.out instance [inhabited C] : inhabited (skeleton C) := ⟨⟦default C⟧⟩ /-- The functor from the skeleton of `C` to `C`. -/ @[simps, derive [full, faithful]] noncomputable def from_skeleton : skeleton C ⥤ C := induced_functor _ instance : ess_surj (from_skeleton C) := { mem_ess_image := λ X, ⟨quotient.mk X, quotient.mk_out X⟩ } noncomputable instance : is_equivalence (from_skeleton C) := equivalence.equivalence_of_fully_faithfully_ess_surj (from_skeleton C) lemma skeleton_skeletal : skeletal (skeleton C) := begin rintro X Y ⟨h⟩, have : X.out ≈ Y.out := ⟨(from_skeleton C).map_iso h⟩, simpa using quotient.sound this, end /-- The `skeleton` of `C` given by choice is a skeleton of `C`. -/ noncomputable def skeleton_is_skeleton : is_skeleton_of C (skeleton C) (from_skeleton C) := { skel := skeleton_skeletal C, eqv := from_skeleton.is_equivalence C } section variables {C D} /-- Two categories which are categorically equivalent have skeletons with equivalent objects. -/ noncomputable def equivalence.skeleton_equiv (e : C ≌ D) : skeleton C ≃ skeleton D := let f := ((from_skeleton C).as_equivalence.trans e).trans (from_skeleton D).as_equivalence.symm in { to_fun := f.functor.obj, inv_fun := f.inverse.obj, left_inv := λ X, skeleton_skeletal C ⟨(f.unit_iso.app X).symm⟩, right_inv := λ Y, skeleton_skeletal D ⟨(f.counit_iso.app Y)⟩, } end /-- Construct the skeleton category by taking the quotient of objects. This construction gives a preorder with nice definitional properties, but is only really appropriate for thin categories. If your original category is not thin, you probably want to be using `skeleton` instead of this. -/ def thin_skeleton : Type u₁ := quotient (is_isomorphic_setoid C) instance inhabited_thin_skeleton [inhabited C] : inhabited (thin_skeleton C) := ⟨quotient.mk (default _)⟩ instance thin_skeleton.preorder : preorder (thin_skeleton C) := { le := quotient.lift₂ (λ X Y, nonempty (X ⟶ Y)) begin rintros _ _ _ _ ⟨i₁⟩ ⟨i₂⟩, exact propext ⟨nonempty.map (λ f, i₁.inv ≫ f ≫ i₂.hom), nonempty.map (λ f, i₁.hom ≫ f ≫ i₂.inv)⟩, end, le_refl := begin refine quotient.ind (λ a, _), exact ⟨𝟙 _⟩, end, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ A B C, nonempty.map2 (≫) } /-- The functor from a category to its thin skeleton. -/ @[simps] def to_thin_skeleton : C ⥤ thin_skeleton C := { obj := quotient.mk, map := λ X Y f, hom_of_le (nonempty.intro f) } /-! The constructions here are intended to be used when the category `C` is thin, even though some of the statements can be shown without this assumption. -/ namespace thin_skeleton /-- The thin skeleton is thin. -/ instance thin {X Y : thin_skeleton C} : subsingleton (X ⟶ Y) := ⟨by { rintros ⟨⟨f₁⟩⟩ ⟨⟨f₂⟩⟩, refl }⟩ variables {C} {D} /-- A functor `C ⥤ D` computably lowers to a functor `thin_skeleton C ⥤ thin_skeleton D`. -/ @[simps] def map (F : C ⥤ D) : thin_skeleton C ⥤ thin_skeleton D := { obj := quotient.map F.obj $ λ X₁ X₂ ⟨hX⟩, ⟨F.map_iso hX⟩, map := λ X Y, quotient.rec_on_subsingleton₂ X Y $ λ x y k, hom_of_le (k.le.elim (λ t, ⟨F.map t⟩)) } lemma comp_to_thin_skeleton (F : C ⥤ D) : F ⋙ to_thin_skeleton D = to_thin_skeleton C ⋙ map F := rfl /-- Given a natural transformation `F₁ ⟶ F₂`, induce a natural transformation `map F₁ ⟶ map F₂`.-/ def map_nat_trans {F₁ F₂ : C ⥤ D} (k : F₁ ⟶ F₂) : map F₁ ⟶ map F₂ := { app := λ X, quotient.rec_on_subsingleton X (λ x, ⟨⟨⟨k.app x⟩⟩⟩) } -- TODO: state the lemmas about what happens when you compose with `to_thin_skeleton` /-- A functor `C ⥤ D ⥤ E` computably lowers to a functor `thin_skeleton C ⥤ thin_skeleton D ⥤ thin_skeleton E` -/ @[simps] def map₂ (F : C ⥤ D ⥤ E) : thin_skeleton C ⥤ thin_skeleton D ⥤ thin_skeleton E := { obj := λ x, { obj := λ y, quotient.map₂ (λ X Y, (F.obj X).obj Y) (λ X₁ X₂ ⟨hX⟩ Y₁ Y₂ ⟨hY⟩, ⟨(F.obj X₁).map_iso hY ≪≫ (F.map_iso hX).app Y₂⟩) x y, map := λ y₁ y₂, quotient.rec_on_subsingleton x $ λ X, quotient.rec_on_subsingleton₂ y₁ y₂ $ λ Y₁ Y₂ hY, hom_of_le (hY.le.elim (λ g, ⟨(F.obj X).map g⟩)) }, map := λ x₁ x₂, quotient.rec_on_subsingleton₂ x₁ x₂ $ λ X₁ X₂ f, { app := λ y, quotient.rec_on_subsingleton y (λ Y, hom_of_le (f.le.elim (λ f', ⟨(F.map f').app Y⟩))) } } variables (C) section variables [∀ X Y : C, subsingleton (X ⟶ Y)] instance to_thin_skeleton_faithful : faithful (to_thin_skeleton C) := {} /-- Use `quotient.out` to create a functor out of the thin skeleton. -/ @[simps] noncomputable def from_thin_skeleton : thin_skeleton C ⥤ C := { obj := quotient.out, map := λ x y, quotient.rec_on_subsingleton₂ x y $ λ X Y f, (nonempty.some (quotient.mk_out X)).hom ≫ f.le.some ≫ (nonempty.some (quotient.mk_out Y)).inv } noncomputable instance from_thin_skeleton_equivalence : is_equivalence (from_thin_skeleton C) := { inverse := to_thin_skeleton C, counit_iso := nat_iso.of_components (λ X, (nonempty.some (quotient.mk_out X))) (by tidy), unit_iso := nat_iso.of_components (λ x, quotient.rec_on_subsingleton x (λ X, eq_to_iso (quotient.sound ⟨(nonempty.some (quotient.mk_out X)).symm⟩))) (by tidy) } variables {C} lemma equiv_of_both_ways {X Y : C} (f : X ⟶ Y) (g : Y ⟶ X) : X ≈ Y := ⟨iso_of_both_ways f g⟩ instance thin_skeleton_partial_order : partial_order (thin_skeleton C) := { le_antisymm := quotient.ind₂ begin rintros _ _ ⟨f⟩ ⟨g⟩, apply quotient.sound (equiv_of_both_ways f g), end, ..category_theory.thin_skeleton.preorder C } lemma skeletal : skeletal (thin_skeleton C) := λ X Y, quotient.induction_on₂ X Y $ λ x y h, h.elim $ λ i, i.1.le.antisymm i.2.le lemma map_comp_eq (F : E ⥤ D) (G : D ⥤ C) : map (F ⋙ G) = map F ⋙ map G := functor.eq_of_iso skeletal $ nat_iso.of_components (λ X, quotient.rec_on_subsingleton X (λ x, iso.refl _)) (by tidy) lemma map_id_eq : map (𝟭 C) = 𝟭 (thin_skeleton C) := functor.eq_of_iso skeletal $ nat_iso.of_components (λ X, quotient.rec_on_subsingleton X (λ x, iso.refl _)) (by tidy) lemma map_iso_eq {F₁ F₂ : D ⥤ C} (h : F₁ ≅ F₂) : map F₁ = map F₂ := functor.eq_of_iso skeletal { hom := map_nat_trans h.hom, inv := map_nat_trans h.inv } /-- `from_thin_skeleton C` exhibits the thin skeleton as a skeleton. -/ noncomputable def thin_skeleton_is_skeleton : is_skeleton_of C (thin_skeleton C) (from_thin_skeleton C) := { skel := skeletal, eqv := thin_skeleton.from_thin_skeleton_equivalence C } noncomputable instance is_skeleton_of_inhabited : inhabited (is_skeleton_of C (thin_skeleton C) (from_thin_skeleton C)) := ⟨thin_skeleton_is_skeleton⟩ end variables {C} /-- An adjunction between thin categories gives an adjunction between their thin skeletons. -/ def lower_adjunction (R : D ⥤ C) (L : C ⥤ D) (h : L ⊣ R) : thin_skeleton.map L ⊣ thin_skeleton.map R := adjunction.mk_of_unit_counit { unit := { app := λ X, begin letI := is_isomorphic_setoid C, refine quotient.rec_on_subsingleton X (λ x, hom_of_le ⟨h.unit.app x⟩), -- TODO: make quotient.rec_on_subsingleton' so the letI isn't needed end }, counit := { app := λ X, begin letI := is_isomorphic_setoid D, refine quotient.rec_on_subsingleton X (λ x, hom_of_le ⟨h.counit.app x⟩), end } } end thin_skeleton open thin_skeleton section variables {C} {α : Type*} [partial_order α] /-- When `e : C ≌ α` is a categorical equivalence from a thin category `C` to some partial order `α`, the `thin_skeleton C` is order isomorphic to `α`. -/ noncomputable def equivalence.thin_skeleton_order_iso [∀ X Y : C, subsingleton (X ⟶ Y)] (e : C ≌ α) : thin_skeleton C ≃o α := ((from_thin_skeleton C).as_equivalence.trans e).to_order_iso end end category_theory
b7d9eb5f33b052c05429871ea63e6c852274aaed
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/shapes/terminal.lean
e98b747981d8c1e39de7ac83b5fc7aa5989f9c05
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
23,778
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.pempty import category_theory.limits.has_limits import category_theory.epi_mono import category_theory.category.preorder /-! # Initial and terminal objects in a category. ## References * [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B) -/ noncomputable theory universes w w' v v₁ v₂ u u₁ u₂ open category_theory namespace category_theory.limits variables {C : Type u₁} [category.{v₁} C] /-- Construct a cone for the empty diagram given an object. -/ @[simps] def as_empty_cone (X : C) : cone (functor.empty.{w} C) := { X := X, π := by tidy } /-- Construct a cocone for the empty diagram given an object. -/ @[simps] def as_empty_cocone (X : C) : cocone (functor.empty.{w} C) := { X := X, ι := by tidy } /-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/ abbreviation is_terminal (X : C) := is_limit (as_empty_cone.{v₁} X) /-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/ abbreviation is_initial (X : C) := is_colimit (as_empty_cocone.{v₁} X) /-- An object `Y` is terminal iff for every `X` there is a unique morphism `X ⟶ Y`. -/ def is_terminal_equiv_unique (F : discrete.{v₁} pempty ⥤ C) (Y : C) : is_limit (⟨Y, by tidy⟩ : cone F) ≃ ∀ X : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.lift ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { lift := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `Y` is terminal if for every `X` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_terminal.of_unique (Y : C) [h : Π X : C, unique (X ⟶ Y)] : is_terminal Y := { lift := λ s, (h s.X).default } /-- If `α` is a preorder with top, then `⊤` is a terminal object. -/ def is_terminal_top {α : Type*} [preorder α] [order_top α] : is_terminal (⊤ : α) := is_terminal.of_unique _ /-- Transport a term of type `is_terminal` across an isomorphism. -/ def is_terminal.of_iso {Y Z : C} (hY : is_terminal Y) (i : Y ≅ Z) : is_terminal Z := is_limit.of_iso_limit hY { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- An object `X` is initial iff for every `Y` there is a unique morphism `X ⟶ Y`. -/ def is_initial_equiv_unique (F : discrete.{v₁} pempty ⥤ C) (X : C) : is_colimit (⟨X, by tidy⟩ : cocone F) ≃ ∀ Y : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.desc ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { desc := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `X` is initial if for every `Y` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_initial.of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : is_initial X := { desc := λ s, (h s.X).default } /-- If `α` is a preorder with bot, then `⊥` is an initial object. -/ def is_initial_bot {α : Type*} [preorder α] [order_bot α] : is_initial (⊥ : α) := is_initial.of_unique _ /-- Transport a term of type `is_initial` across an isomorphism. -/ def is_initial.of_iso {X Y : C} (hX : is_initial X) (i : X ≅ Y) : is_initial Y := is_colimit.of_iso_colimit hX { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- Give the morphism to a terminal object from any other. -/ def is_terminal.from {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X := t.lift (as_empty_cone Y) /-- Any two morphisms to a terminal object are equal. -/ lemma is_terminal.hom_ext {X Y : C} (t : is_terminal X) (f g : Y ⟶ X) : f = g := t.hom_ext (by tidy) @[simp] lemma is_terminal.comp_from {Z : C} (t : is_terminal Z) {X Y : C} (f : X ⟶ Y) : f ≫ t.from Y = t.from X := t.hom_ext _ _ @[simp] lemma is_terminal.from_self {X : C} (t : is_terminal X) : t.from X = 𝟙 X := t.hom_ext _ _ /-- Give the morphism from an initial object to any other. -/ def is_initial.to {X : C} (t : is_initial X) (Y : C) : X ⟶ Y := t.desc (as_empty_cocone Y) /-- Any two morphisms from an initial object are equal. -/ lemma is_initial.hom_ext {X Y : C} (t : is_initial X) (f g : X ⟶ Y) : f = g := t.hom_ext (by tidy) @[simp] lemma is_initial.to_comp {X : C} (t : is_initial X) {Y Z : C} (f : Y ⟶ Z) : t.to Y ≫ f = t.to Z := t.hom_ext _ _ @[simp] lemma is_initial.to_self {X : C} (t : is_initial X) : t.to X = 𝟙 X := t.hom_ext _ _ /-- Any morphism from a terminal object is split mono. -/ def is_terminal.split_mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : split_mono f := ⟨t.from _, t.hom_ext _ _⟩ /-- Any morphism to an initial object is split epi. -/ def is_initial.split_epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : split_epi f := ⟨t.to _, t.hom_ext _ _⟩ /-- Any morphism from a terminal object is mono. -/ lemma is_terminal.mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f := by haveI := t.split_mono_from f; apply_instance /-- Any morphism to an initial object is epi. -/ lemma is_initial.epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f := by haveI := t.split_epi_to f; apply_instance /-- If `T` and `T'` are terminal, they are isomorphic. -/ @[simps] def is_terminal.unique_up_to_iso {T T' : C} (hT : is_terminal T) (hT' : is_terminal T') : T ≅ T' := { hom := hT'.from _, inv := hT.from _ } /-- If `I` and `I'` are initial, they are isomorphic. -/ @[simps] def is_initial.unique_up_to_iso {I I' : C} (hI : is_initial I) (hI' : is_initial I') : I ≅ I' := { hom := hI.to _, inv := hI'.to _ } variable (C) /-- A category has a terminal object if it has a limit over the empty diagram. Use `has_terminal_of_unique` to construct instances. -/ abbreviation has_terminal := has_limits_of_shape (discrete.{v₁} pempty) C /-- A category has an initial object if it has a colimit over the empty diagram. Use `has_initial_of_unique` to construct instances. -/ abbreviation has_initial := has_colimits_of_shape (discrete.{v₁} pempty) C section univ variables (X : C) {F₁ : discrete.{w} pempty ⥤ C} {F₂ : discrete.{w'} pempty ⥤ C} /-- Being terminal is independent of the empty diagram, its universe, and the cone over it, as long as the cone points are isomorphic. -/ def is_limit_change_empty_cone {c₁ : cone F₁} (hl : is_limit c₁) (c₂ : cone F₂) (hi : c₁.X ≅ c₂.X) : is_limit c₂ := { lift := λ c, hl.lift ⟨c.X, by tidy⟩ ≫ hi.hom, fac' := λ _ j, j.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (f ≫ hi.inv) (λ j, j.elim), simp } } /-- Replacing an empty cone in `is_limit` by another with the same cone point is an equivalence. -/ def is_limit_empty_cone_equiv (c₁ : cone F₁) (c₂ : cone F₂) (h : c₁.X ≅ c₂.X) : is_limit c₁ ≃ is_limit c₂ := { to_fun := λ hl, is_limit_change_empty_cone C hl c₂ h, inv_fun := λ hl, is_limit_change_empty_cone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_terminal_change_diagram (h : has_limit F₁) : has_limit F₂ := ⟨⟨⟨⟨limit F₁, by tidy⟩, is_limit_change_empty_cone C (limit.is_limit F₁) _ (eq_to_iso rfl)⟩⟩⟩ lemma has_terminal_change_universe [h : has_limits_of_shape (discrete.{w} pempty) C] : has_limits_of_shape (discrete.{w'} pempty) C := { has_limit := λ J, has_terminal_change_diagram C (let f := h.1 in f (functor.empty C)) } /-- Being initial is independent of the empty diagram, its universe, and the cocone over it, as long as the cocone points are isomorphic. -/ def is_colimit_change_empty_cocone {c₁ : cocone F₁} (hl : is_colimit c₁) (c₂ : cocone F₂) (hi : c₁.X ≅ c₂.X) : is_colimit c₂ := { desc := λ c, hi.inv ≫ hl.desc ⟨c.X, by tidy⟩, fac' := λ _ j, j.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (hi.hom ≫ f) (λ j, j.elim), simp } } /-- Replacing an empty cocone in `is_colimit` by another with the same cocone point is an equivalence. -/ def is_colimit_empty_cocone_equiv (c₁ : cocone F₁) (c₂ : cocone F₂) (h : c₁.X ≅ c₂.X) : is_colimit c₁ ≃ is_colimit c₂ := { to_fun := λ hl, is_colimit_change_empty_cocone C hl c₂ h, inv_fun := λ hl, is_colimit_change_empty_cocone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_initial_change_diagram (h : has_colimit F₁) : has_colimit F₂ := ⟨⟨⟨⟨colimit F₁, by tidy⟩, is_colimit_change_empty_cocone C (colimit.is_colimit F₁) _ (eq_to_iso rfl)⟩⟩⟩ lemma has_initial_change_universe [h : has_colimits_of_shape (discrete.{w} pempty) C] : has_colimits_of_shape (discrete.{w'} pempty) C := { has_colimit := λ J, has_initial_change_diagram C (let f := h.1 in f (functor.empty C)) } end univ /-- An arbitrary choice of terminal object, if one exists. You can use the notation `⊤_ C`. This object is characterized by having a unique morphism from any object. -/ abbreviation terminal [has_terminal C] : C := limit (functor.empty.{v₁} C) /-- An arbitrary choice of initial object, if one exists. You can use the notation `⊥_ C`. This object is characterized by having a unique morphism to any object. -/ abbreviation initial [has_initial C] : C := colimit (functor.empty.{v₁} C) notation `⊤_ ` C:20 := terminal C notation `⊥_ ` C:20 := initial C section variables {C} /-- We can more explicitly show that a category has a terminal object by specifying the object, and showing there is a unique morphism to it from any other object. -/ lemma has_terminal_of_unique (X : C) [h : Π Y : C, unique (Y ⟶ X)] : has_terminal C := { has_limit := λ F, has_limit.mk ⟨_, (is_terminal_equiv_unique F X).inv_fun h⟩ } /-- We can more explicitly show that a category has an initial object by specifying the object, and showing there is a unique morphism from it to any other object. -/ lemma has_initial_of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : has_initial C := { has_colimit := λ F, has_colimit.mk ⟨_, (is_initial_equiv_unique F X).inv_fun h⟩ } /-- The map from an object to the terminal object. -/ abbreviation terminal.from [has_terminal C] (P : C) : P ⟶ ⊤_ C := limit.lift (functor.empty C) (as_empty_cone P) /-- The map to an object from the initial object. -/ abbreviation initial.to [has_initial C] (P : C) : ⊥_ C ⟶ P := colimit.desc (functor.empty C) (as_empty_cocone P) /-- A terminal object is terminal. -/ def terminal_is_terminal [has_terminal C] : is_terminal (⊤_ C) := { lift := λ s, terminal.from _ } /-- An initial object is initial. -/ def initial_is_initial [has_initial C] : is_initial (⊥_ C) := { desc := λ s, initial.to _ } instance unique_to_terminal [has_terminal C] (P : C) : unique (P ⟶ ⊤_ C) := is_terminal_equiv_unique _ (⊤_ C) terminal_is_terminal P instance unique_from_initial [has_initial C] (P : C) : unique (⊥_ C ⟶ P) := is_initial_equiv_unique _ (⊥_ C) initial_is_initial P @[simp] lemma terminal.comp_from [has_terminal C] {P Q : C} (f : P ⟶ Q) : f ≫ terminal.from Q = terminal.from P := by tidy @[simp] lemma initial.to_comp [has_initial C] {P Q : C} (f : P ⟶ Q) : initial.to P ≫ f = initial.to Q := by tidy /-- Any morphism from a terminal object is split mono. -/ instance terminal.split_mono_from {Y : C} [has_terminal C] (f : ⊤_ C ⟶ Y) : split_mono f := is_terminal.split_mono_from terminal_is_terminal _ /-- Any morphism to an initial object is split epi. -/ instance initial.split_epi_to {Y : C} [has_initial C] (f : Y ⟶ ⊥_ C) : split_epi f := is_initial.split_epi_to initial_is_initial _ /-- An initial object is terminal in the opposite category. -/ def terminal_op_of_initial {X : C} (t : is_initial X) : is_terminal (opposite.op X) := { lift := λ s, (t.to s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- An initial object in the opposite category is terminal in the original category. -/ def terminal_unop_of_initial {X : Cᵒᵖ} (t : is_initial X) : is_terminal X.unop := { lift := λ s, (t.to (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- A terminal object is initial in the opposite category. -/ def initial_op_of_terminal {X : C} (t : is_terminal X) : is_initial (opposite.op X) := { desc := λ s, (t.from s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- A terminal object in the opposite category is initial in the original category. -/ def initial_unop_of_terminal {X : Cᵒᵖ} (t : is_terminal X) : is_initial X.unop := { desc := λ s, (t.from (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- A category is a `initial_mono_class` if the canonical morphism of an initial object is a monomorphism. In practice, this is most useful when given an arbitrary morphism out of the chosen initial object, see `initial.mono_from`. Given a terminal object, this is equivalent to the assumption that the unique morphism from initial to terminal is a monomorphism, which is the second of Freyd's axioms for an AT category. TODO: This is a condition satisfied by categories with zero objects and morphisms. -/ class initial_mono_class (C : Type u₁) [category.{v₁} C] : Prop := (is_initial_mono_from : ∀ {I} (X : C) (hI : is_initial I), mono (hI.to X)) lemma is_initial.mono_from [initial_mono_class C] {I} {X : C} (hI : is_initial I) (f : I ⟶ X) : mono f := begin rw hI.hom_ext f (hI.to X), apply initial_mono_class.is_initial_mono_from, end @[priority 100] instance initial.mono_from [has_initial C] [initial_mono_class C] (X : C) (f : ⊥_ C ⟶ X) : mono f := initial_is_initial.mono_from f /-- To show a category is a `initial_mono_class` it suffices to give an initial object such that every morphism out of it is a monomorphism. -/ lemma initial_mono_class.of_is_initial {I : C} (hI : is_initial I) (h : ∀ X, mono (hI.to X)) : initial_mono_class C := { is_initial_mono_from := λ I' X hI', begin rw hI'.hom_ext (hI'.to X) ((hI'.unique_up_to_iso hI).hom ≫ hI.to X), apply mono_comp, end } /-- To show a category is a `initial_mono_class` it suffices to show every morphism out of the initial object is a monomorphism. -/ lemma initial_mono_class.of_initial [has_initial C] (h : ∀ X : C, mono (initial.to X)) : initial_mono_class C := initial_mono_class.of_is_initial initial_is_initial h /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from an initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_is_terminal {I T : C} (hI : is_initial I) (hT : is_terminal T) (f : mono (hI.to T)) : initial_mono_class C := initial_mono_class.of_is_initial hI (λ X, mono_of_mono_fac (hI.hom_ext (_ ≫ hT.from X) (hI.to T))) /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from the initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_terminal [has_initial C] [has_terminal C] (h : mono (initial.to (⊤_ C))) : initial_mono_class C := initial_mono_class.of_is_terminal initial_is_initial terminal_is_terminal h section comparison variables {D : Type u₂} [category.{v₂} D] (G : C ⥤ D) /-- The comparison morphism from the image of a terminal object to the terminal object in the target category. This is an isomorphism iff `G` preserves terminal objects, see `category_theory.limits.preserves_terminal.of_iso_comparison`. -/ def terminal_comparison [has_terminal C] [has_terminal D] : G.obj (⊤_ C) ⟶ ⊤_ D := terminal.from _ /-- The comparison morphism from the initial object in the target category to the image of the initial object. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves initial objects. def initial_comparison [has_initial C] [has_initial D] : ⊥_ D ⟶ G.obj (⊥_ C) := initial.to _ end comparison variables {J : Type u} [category.{v} J] /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`. In `limit_of_diagram_initial` we show it is a limit cone. -/ @[simps] def cone_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : cone F := { X := F.obj X, π := { app := λ j, F.map (tX.to j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.id_comp, tX.hom_ext (tX.to j ≫ k) (tX.to j')], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone `cone_of_diagram_initial` is a limit. -/ def limit_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : is_limit (cone_of_diagram_initial tX F) := { lift := λ s, s.π.app X, uniq' := λ s m w, begin rw [← w X, cone_of_diagram_initial_π_app, tX.hom_ext (tX.to X) (𝟙 _)], dsimp, simp -- See note [dsimp, simp] end} -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_initial (F : J ⥤ C) [has_initial J] [has_limit F] : limit F ≅ F.obj (⊥_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_initial initial_is_initial F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cone for `J`, provided that the morphisms in the diagram are isomorphisms. In `limit_of_diagram_terminal` we show it is a limit cone. -/ @[simps] def cone_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cone F := { X := F.obj X, π := { app := λ i, inv (F.map (hX.from _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.id_comp, ← F.map_comp, hX.hom_ext (hX.from i) (f ≫ hX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cone_of_diagram_terminal` is a limit. -/ def limit_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_limit (cone_of_diagram_terminal hX F) := { lift := λ S, S.π.app _ } -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object and all the morphisms in the diagram are isomorphisms, then the image of the terminal object is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_terminal (F : J ⥤ C) [has_terminal J] [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : limit F ≅ F.obj (⊤_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`. In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone F := { X := F.obj X, ι := { app := λ j, F.map (tX.from j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.comp_id, tX.hom_ext (k ≫ tX.from j') (tX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone `cocone_of_diagram_terminal` is a colimit. -/ def colimit_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : is_colimit (cocone_of_diagram_terminal tX F) := { desc := λ s, s.ι.app X, uniq' := λ s m w, by { rw [← w X, cocone_of_diagram_terminal_ι_app, tX.hom_ext (tX.from X) (𝟙 _)], simp } } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_terminal (F : J ⥤ C) [has_terminal J] [has_colimit F] : colimit F ≅ F.obj (⊤_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cocone for `J`, provided that the morphisms in the diagram are isomorphisms. In `colimit_of_diagram_initial` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cocone F := { X := F.obj X, ι := { app := λ i, inv (F.map (hX.to _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.comp_id, ← F.map_comp, hX.hom_ext (hX.to i ≫ f) (hX.to j)], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cocone_of_diagram_initial` is a colimit. -/ def colimit_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_colimit (cocone_of_diagram_initial hX F) := { desc := λ S, S.ι.app _ } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object and all the morphisms in the diagram are isomorphisms, then the image of the initial object is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_initial (F : J ⥤ C) [has_initial J] [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : colimit F ≅ F.obj (⊥_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_initial initial_is_initial _) /-- If `j` is initial in the index category, then the map `limit.π F j` is an isomorphism. -/ lemma is_iso_π_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_limit F] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_initial I F), ⟨by { ext, simp }, by simp⟩⟩⟩ instance is_iso_π_initial [has_initial J] (F : J ⥤ C) [has_limit F] : is_iso (limit.π F (⊥_ J)) := is_iso_π_of_is_initial (initial_is_initial) F lemma is_iso_π_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_terminal I F), by { ext, simp }, by simp ⟩⟩ instance is_iso_π_terminal [has_terminal J] (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F (⊤_ J)) := is_iso_π_of_is_terminal terminal_is_terminal F /-- If `j` is terminal in the index category, then the map `colimit.ι F j` is an isomorphism. -/ lemma is_iso_ι_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_terminal I F), ⟨by simp, by { ext, simp }⟩⟩⟩ instance is_iso_ι_terminal [has_terminal J] (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F (⊤_ J)) := is_iso_ι_of_is_terminal (terminal_is_terminal) F lemma is_iso_ι_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_initial I F), ⟨by tidy, by { ext, simp }⟩⟩⟩ instance is_iso_ι_initial [has_initial J] (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F (⊥_ J)) := is_iso_ι_of_is_initial initial_is_initial F end end category_theory.limits
1e63ab809b74a12beab0f63d07d0f545047cbc16
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/discrete_quotient.lean
bded7b0c1086e848c3663044e14e3a2b67eb09ae
[ "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
14,139
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne, Adam Topaz -/ import topology.separation import topology.subset_properties import topology.locally_constant.basic /-! # Discrete quotients of a topological space. This file defines the type of discrete quotients of a topological space, denoted `discrete_quotient X`. To avoid quantifying over types, we model such quotients as setoids whose equivalence classes are clopen. ## Definitions 1. `discrete_quotient X` is the type of discrete quotients of `X`. It is endowed with a coercion to `Type`, which is defined as the quotient associated to the setoid in question, and each such quotient is endowed with the discrete topology. 2. Given `S : discrete_quotient X`, the projection `X → S` is denoted `S.proj`. 3. When `X` is compact and `S : discrete_quotient X`, the space `S` is endowed with a `fintype` instance. ## Order structure The type `discrete_quotient X` is endowed with an instance of a `semilattice_inf` with `order_top`. The partial ordering `A ≤ B` mathematically means that `B.proj` factors through `A.proj`. The top element `⊤` is the trivial quotient, meaning that every element of `X` is collapsed to a point. Given `h : A ≤ B`, the map `A → B` is `discrete_quotient.of_le h`. Whenever `X` is discrete, the type `discrete_quotient X` is also endowed with an instance of a `semilattice_inf` with `order_bot`, where the bot element `⊥` is `X` itself. Given `f : X → Y` and `h : continuous f`, we define a predicate `le_comap h A B` for `A : discrete_quotient X` and `B : discrete_quotient Y`, asserting that `f` descends to `A → B`. If `cond : le_comap h A B`, the function `A → B` is obtained by `discrete_quotient.map cond`. ## Theorems The two main results proved in this file are: 1. `discrete_quotient.eq_of_proj_eq` which states that when `X` is compact, t2 and totally disconnected, any two elements of `X` agree if their projections in `Q` agree for all `Q : discrete_quotient X`. 2. `discrete_quotient.exists_of_compat` which states that when `X` is compact, then any system of elements of `Q` as `Q : discrete_quotient X` varies, which is compatible with respect to `discrete_quotient.of_le`, must arise from some element of `X`. ## Remarks The constructions in this file will be used to show that any profinite space is a limit of finite discrete spaces. -/ variables (X : Type*) [topological_space X] /-- The type of discrete quotients of a topological space. -/ @[ext] structure discrete_quotient := (rel : X → X → Prop) (equiv : equivalence rel) (clopen : ∀ x, is_clopen (set_of (rel x))) namespace discrete_quotient variables {X} (S : discrete_quotient X) /-- Construct a discrete quotient from a clopen set. -/ def of_clopen {A : set X} (h : is_clopen A) : discrete_quotient X := { rel := λ x y, x ∈ A ∧ y ∈ A ∨ x ∉ A ∧ y ∉ A, equiv := ⟨by tauto!, by tauto!, by tauto!⟩, clopen := begin intros x, by_cases hx : x ∈ A, { apply is_clopen.union, { convert h, ext, exact ⟨λ i, i.2, λ i, ⟨hx,i⟩⟩ }, { convert is_clopen_empty, tidy } }, { apply is_clopen.union, { convert is_clopen_empty, tidy }, { convert is_clopen.compl h, ext, exact ⟨λ i, i.2, λ i, ⟨hx, i⟩⟩ } }, end } lemma refl : ∀ x : X, S.rel x x := S.equiv.1 lemma symm : ∀ x y : X, S.rel x y → S.rel y x := S.equiv.2.1 lemma trans : ∀ x y z : X, S.rel x y → S.rel y z → S.rel x z := S.equiv.2.2 /-- The setoid whose quotient yields the discrete quotient. -/ def setoid : setoid X := ⟨S.rel, S.equiv⟩ instance : has_coe_to_sort (discrete_quotient X) Type* := ⟨λ S, quotient S.setoid⟩ instance : topological_space S := ⊥ /-- The projection from `X` to the given discrete quotient. -/ def proj : X → S := quotient.mk' lemma proj_surjective : function.surjective S.proj := quotient.surjective_quotient_mk' lemma fiber_eq (x : X) : S.proj ⁻¹' {S.proj x} = set_of (S.rel x) := begin ext1 y, simp only [set.mem_preimage, set.mem_singleton_iff, quotient.eq', discrete_quotient.proj.equations._eqn_1, set.mem_set_of_eq], exact ⟨λ h, S.symm _ _ h, λ h, S.symm _ _ h⟩, end lemma proj_is_locally_constant : is_locally_constant S.proj := begin rw (is_locally_constant.tfae S.proj).out 0 3, intros x, rcases S.proj_surjective x with ⟨x,rfl⟩, simp [fiber_eq, (S.clopen x).1], end lemma proj_continuous : continuous S.proj := is_locally_constant.continuous $ proj_is_locally_constant _ lemma fiber_closed (A : set S) : is_closed (S.proj ⁻¹' A) := is_closed.preimage S.proj_continuous ⟨trivial⟩ lemma fiber_open (A : set S) : is_open (S.proj ⁻¹' A) := is_open.preimage S.proj_continuous trivial lemma fiber_clopen (A : set S) : is_clopen (S.proj ⁻¹' A) := ⟨fiber_open _ _, fiber_closed _ _⟩ instance : partial_order (discrete_quotient X) := { le := λ A B, ∀ x y : X, A.rel x y → B.rel x y, le_refl := λ a, by tauto, le_trans := λ a b c h1 h2, by tauto, le_antisymm := λ a b h1 h2, by { ext, tauto } } instance : order_top (discrete_quotient X) := { top := ⟨λ a b, true, ⟨by tauto, by tauto, by tauto⟩, λ _, is_clopen_univ⟩, le_top := λ a, by tauto } instance : semilattice_inf (discrete_quotient X) := { inf := λ A B, { rel := λ x y, A.rel x y ∧ B.rel x y, equiv := ⟨λ a, ⟨A.refl _,B.refl _⟩, λ a b h, ⟨A.symm _ _ h.1, B.symm _ _ h.2⟩, λ a b c h1 h2, ⟨A.trans _ _ _ h1.1 h2.1, B.trans _ _ _ h1.2 h2.2⟩⟩, clopen := λ x, is_clopen.inter (A.clopen _) (B.clopen _) }, inf_le_left := λ a b, by tauto, inf_le_right := λ a b, by tauto, le_inf := λ a b c h1 h2, by tauto, ..discrete_quotient.partial_order } instance : inhabited (discrete_quotient X) := ⟨⊤⟩ section comap variables {Y : Type*} [topological_space Y] {f : Y → X} (cont : continuous f) /-- Comap a discrete quotient along a continuous map. -/ def comap : discrete_quotient Y := { rel := λ a b, S.rel (f a) (f b), equiv := ⟨λ a, S.refl _, λ a b h, S.symm _ _ h, λ a b c h1 h2, S.trans _ _ _ h1 h2⟩, clopen := λ y, ⟨is_open.preimage cont (S.clopen _).1, is_closed.preimage cont (S.clopen _).2⟩ } @[simp] lemma comap_id : S.comap (continuous_id : continuous (id : X → X)) = S := by { ext, refl } @[simp] lemma comap_comp {Z : Type*} [topological_space Z] {g : Z → Y} (cont' : continuous g) : S.comap (continuous.comp cont cont') = (S.comap cont).comap cont' := by { ext, refl } lemma comap_mono {A B : discrete_quotient X} (h : A ≤ B) : A.comap cont ≤ B.comap cont := by tauto end comap section of_le /-- The map induced by a refinement of a discrete quotient. -/ def of_le {A B : discrete_quotient X} (h : A ≤ B) : A → B := λ a, quotient.lift_on' a (λ x, B.proj x) (λ a b i, quotient.sound' (h _ _ i)) @[simp] lemma of_le_refl {A : discrete_quotient X} : of_le (le_refl A) = id := by { ext ⟨⟩, refl } lemma of_le_refl_apply {A : discrete_quotient X} (a : A) : of_le (le_refl A) a = a := by simp @[simp] lemma of_le_comp {A B C : discrete_quotient X} (h1 : A ≤ B) (h2 : B ≤ C) : of_le (le_trans h1 h2) = of_le h2 ∘ of_le h1 := by { ext ⟨⟩, refl } lemma of_le_comp_apply {A B C : discrete_quotient X} (h1 : A ≤ B) (h2 : B ≤ C) (a : A) : of_le (le_trans h1 h2) a = of_le h2 (of_le h1 a) := by simp lemma of_le_continuous {A B : discrete_quotient X} (h : A ≤ B) : continuous (of_le h) := continuous_of_discrete_topology @[simp] lemma of_le_proj {A B : discrete_quotient X} (h : A ≤ B) : of_le h ∘ A.proj = B.proj := by { ext, exact quotient.sound' (B.refl _) } @[simp] lemma of_le_proj_apply {A B : discrete_quotient X} (h : A ≤ B) (x : X) : of_le h (A.proj x) = B.proj x := by { change (of_le h ∘ A.proj) x = _, simp } end of_le /-- When X is discrete, there is a `order_bot` instance on `discrete_quotient X` -/ instance [discrete_topology X] : order_bot (discrete_quotient X) := { bot := { rel := (=), equiv := eq_equivalence, clopen := λ x, is_clopen_discrete _ }, bot_le := by { rintro S a b (h : a = b), rw h, exact S.refl _ } } lemma proj_bot_injective [discrete_topology X] : function.injective (⊥ : discrete_quotient X).proj := λ a b h, quotient.exact' h lemma proj_bot_bijective [discrete_topology X] : function.bijective (⊥ : discrete_quotient X).proj := ⟨proj_bot_injective, proj_surjective _⟩ section map variables {Y : Type*} [topological_space Y] {f : Y → X} (cont : continuous f) (A : discrete_quotient Y) (B : discrete_quotient X) /-- Given `cont : continuous f`, `le_comap cont A B` is defined as `A ≤ B.comap f`. Mathematically this means that `f` descends to a morphism `A → B`. -/ def le_comap : Prop := A ≤ B.comap cont variables {cont A B} lemma le_comap_id (A : discrete_quotient X) : le_comap continuous_id A A := by tauto lemma le_comap_comp {Z : Type*} [topological_space Z] {g : Z → Y} {cont' : continuous g} {C : discrete_quotient Z} : le_comap cont' C A → le_comap cont A B → le_comap (continuous.comp cont cont') C B := by tauto lemma le_comap_trans {C : discrete_quotient X} : le_comap cont A B → B ≤ C → le_comap cont A C := λ h1 h2, le_trans h1 $ comap_mono _ h2 /-- Map a discrete quotient along a continuous map. -/ def map (cond : le_comap cont A B) : A → B := quotient.map' f cond lemma map_continuous (cond : le_comap cont A B) : continuous (map cond) := continuous_of_discrete_topology @[simp] lemma map_proj (cond : le_comap cont A B) : map cond ∘ A.proj = B.proj ∘ f := rfl @[simp] lemma map_proj_apply (cond : le_comap cont A B) (y : Y) : map cond (A.proj y) = B.proj (f y) := rfl @[simp] lemma map_id : map (le_comap_id A) = id := by { ext ⟨⟩, refl } @[simp] lemma map_comp {Z : Type*} [topological_space Z] {g : Z → Y} {cont' : continuous g} {C : discrete_quotient Z} (h1 : le_comap cont' C A) (h2 : le_comap cont A B) : map (le_comap_comp h1 h2) = map h2 ∘ map h1 := by { ext ⟨⟩, refl } @[simp] lemma of_le_map {C : discrete_quotient X} (cond : le_comap cont A B) (h : B ≤ C) : map (le_comap_trans cond h) = of_le h ∘ map cond := by { ext ⟨⟩, refl } @[simp] lemma of_le_map_apply {C : discrete_quotient X} (cond : le_comap cont A B) (h : B ≤ C) (a : A) : map (le_comap_trans cond h) a = of_le h (map cond a) := by { rcases a, refl } @[simp] lemma map_of_le {C : discrete_quotient Y} (cond : le_comap cont A B) (h : C ≤ A) : map (le_trans h cond) = map cond ∘ of_le h := by { ext ⟨⟩, refl } @[simp] lemma map_of_le_apply {C : discrete_quotient Y} (cond : le_comap cont A B) (h : C ≤ A) (c : C) : map (le_trans h cond) c = map cond (of_le h c) := by { rcases c, refl } end map lemma eq_of_proj_eq [t2_space X] [compact_space X] [disc : totally_disconnected_space X] {x y : X} : (∀ Q : discrete_quotient X, Q.proj x = Q.proj y) → x = y := begin intro h, change x ∈ ({y} : set X), rw totally_disconnected_space_iff_connected_component_singleton at disc, rw [← disc y, connected_component_eq_Inter_clopen], rintros U ⟨⟨U, hU1, hU2⟩, rfl⟩, replace h : _ ∨ _ := quotient.exact' (h (of_clopen hU1)), tauto, end lemma fiber_le_of_le {A B : discrete_quotient X} (h : A ≤ B) (a : A) : A.proj ⁻¹' {a} ≤ B.proj ⁻¹' {of_le h a} := begin induction a, erw [fiber_eq, fiber_eq], tidy, end lemma exists_of_compat [compact_space X] (Qs : Π (Q : discrete_quotient X), Q) (compat : ∀ (A B : discrete_quotient X) (h : A ≤ B), of_le h (Qs _) = Qs _) : ∃ x : X, ∀ Q : discrete_quotient X, Q.proj x = Qs _ := begin obtain ⟨x,hx⟩ := is_compact.nonempty_Inter_of_directed_nonempty_compact_closed (λ (Q : discrete_quotient X), Q.proj ⁻¹' {Qs _}) (λ A B, _) (λ i, _) (λ i, (fiber_closed _ _).is_compact) (λ i, fiber_closed _ _), { refine ⟨x, λ Q, _⟩, exact hx _ ⟨Q,rfl⟩ }, { refine ⟨A ⊓ B, λ a ha, _, λ a ha, _⟩, { dsimp only, erw ← compat (A ⊓ B) A inf_le_left, exact fiber_le_of_le _ _ ha }, { dsimp only, erw ← compat (A ⊓ B) B inf_le_right, exact fiber_le_of_le _ _ ha } }, { obtain ⟨x,hx⟩ := i.proj_surjective (Qs i), refine ⟨x,_⟩, dsimp only, rw [← hx, fiber_eq], apply i.refl }, end noncomputable instance [compact_space X] : fintype S := begin have cond : is_compact (⊤ : set X) := compact_univ, rw is_compact_iff_finite_subcover at cond, have h := @cond S (λ s, S.proj ⁻¹' {s}) (λ s, fiber_open _ _) (λ x hx, ⟨S.proj ⁻¹' {S.proj x}, ⟨S.proj x, rfl⟩, rfl⟩), let T := classical.some h, have hT := classical.some_spec h, refine ⟨T,λ s, _⟩, rcases S.proj_surjective s with ⟨x,rfl⟩, rcases hT (by tauto : x ∈ ⊤) with ⟨j, ⟨j,rfl⟩, h1, ⟨hj, rfl⟩, h2⟩, dsimp only at h2, suffices : S.proj x = j, by rwa this, rcases j with ⟨j⟩, apply quotient.sound', erw fiber_eq at h2, exact S.symm _ _ h2 end end discrete_quotient namespace locally_constant variables {X} {α : Type*} (f : locally_constant X α) /-- Any locally constant function induces a discrete quotient. -/ def discrete_quotient : discrete_quotient X := { rel := λ a b, f b = f a, equiv := ⟨by tauto, by tauto, λ a b c h1 h2, by rw [h2, h1]⟩, clopen := λ x, f.is_locally_constant.is_clopen_fiber _ } /-- The function from the discrete quotient associated to a locally constant function. -/ def lift : f.discrete_quotient → α := λ a, quotient.lift_on' a f (λ a b h, h.symm) lemma lift_is_locally_constant : _root_.is_locally_constant f.lift := λ A, trivial /-- A locally constant version of `locally_constant.lift`. -/ def locally_constant_lift : locally_constant f.discrete_quotient α := ⟨f.lift, f.lift_is_locally_constant⟩ @[simp] lemma lift_eq_coe : f.lift = f.locally_constant_lift := rfl @[simp] lemma factors : f.locally_constant_lift ∘ f.discrete_quotient.proj = f := by { ext, refl } end locally_constant
d72715b8206822b6d4062d1ce903f6c6ef796600
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/matrix/charpoly/finite_field.lean
e701a3d07ed0d0128fc3a14f5f397acbbfff97f1
[ "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
2,406
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import linear_algebra.matrix.charpoly.coeff import field_theory.finite.basic import data.matrix.char_p /-! # Results on characteristic polynomials and traces over finite fields. -/ noncomputable theory open polynomial matrix open_locale polynomial variables {n : Type*} [decidable_eq n] [fintype n] @[simp] lemma finite_field.matrix.charpoly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : (M ^ (fintype.card K)).charpoly = M.charpoly := begin casesI (is_empty_or_nonempty n).symm, { cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨k, kpos⟩, ⟨hp, hk⟩⟩, haveI : fact p.prime := ⟨hp⟩, dsimp at hk, rw hk at *, apply (frobenius_inj K[X] p).iterate k, repeat { rw iterate_frobenius, rw ← hk }, rw ← finite_field.expand_card, unfold charpoly, rw [alg_hom.map_det, ← coe_det_monoid_hom, ← (det_monoid_hom : matrix n n K[X] →* K[X]).map_pow], apply congr_arg det, refine mat_poly_equiv.injective _, rw [alg_equiv.map_pow, mat_poly_equiv_charmatrix, hk, sub_pow_char_pow_of_commute, ← C_pow], { exact (id (mat_poly_equiv_eq_X_pow_sub_C (p ^ k) M) : _) }, { exact (C M).commute_X } }, { -- TODO[gh-6025]: remove this `haveI` once `subsingleton_of_empty_right` is a global instance haveI : subsingleton (matrix n n K) := subsingleton_of_empty_right, exact congr_arg _ (subsingleton.elim _ _), }, end @[simp] lemma zmod.charpoly_pow_card {p : ℕ} [fact p.prime] (M : matrix n n (zmod p)) : (M ^ p).charpoly = M.charpoly := by { have h := finite_field.matrix.charpoly_pow_card M, rwa zmod.card at h, } lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : trace (M ^ (fintype.card K)) = trace M ^ (fintype.card K) := begin casesI is_empty_or_nonempty n, { simp [zero_pow fintype.card_pos, matrix.trace], }, rw [matrix.trace_eq_neg_charpoly_coeff, matrix.trace_eq_neg_charpoly_coeff, finite_field.matrix.charpoly_pow_card, finite_field.pow_card] end lemma zmod.trace_pow_card {p : ℕ} [fact p.prime] (M : matrix n n (zmod p)) : trace (M ^ p) = (trace M)^p := by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, }
7991b1ab52199ceb6df231004806e35d070f4f61
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/full_subcategory.lean
52397e39da4f60797ba01ea321a743397504e2b5
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,650
lean
/- Copyright (c) 2017 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.functor.fully_faithful /-! # Induced categories and full subcategories Given a category `D` and a function `F : C → D `from a type `C` to the objects of `D`, there is an essentially unique way to give `C` a category structure such that `F` becomes a fully faithful functor, namely by taking $$ Hom_C(X, Y) = Hom_D(FX, FY) $$. We call this the category induced from `D` along `F`. As a special case, if `C` is a subtype of `D`, this produces the full subcategory of `D` on the objects belonging to `C`. In general the induced category is equivalent to the full subcategory of `D` on the image of `F`. ## Implementation notes It looks odd to make `D` an explicit argument of `induced_category`, when it is determined by the argument `F` anyways. The reason to make `D` explicit is in order to control its syntactic form, so that instances like `induced_category.has_forget₂` (elsewhere) refer to the correct form of D. This is used to set up several algebraic categories like def CommMon : Type (u+1) := induced_category Mon (bundled.map @comm_monoid.to_monoid) -- not `induced_category (bundled monoid) (bundled.map @comm_monoid.to_monoid)`, -- even though `Mon = bundled monoid`! -/ namespace category_theory universes v v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. section induced variables {C : Type u₁} (D : Type u₂) [category.{v} D] variables (F : C → D) include F /-- `induced_category D F`, where `F : C → D`, is a typeclass synonym for `C`, which provides a category structure so that the morphisms `X ⟶ Y` are the morphisms in `D` from `F X` to `F Y`. -/ @[nolint has_nonempty_instance unused_arguments] def induced_category : Type u₁ := C variables {D} instance induced_category.has_coe_to_sort {α : Sort*} [has_coe_to_sort D α] : has_coe_to_sort (induced_category D F) α := ⟨λ c, ↥(F c)⟩ instance induced_category.category : category.{v} (induced_category D F) := { hom := λ X Y, F X ⟶ F Y, id := λ X, 𝟙 (F X), comp := λ _ _ _ f g, f ≫ g } /-- The forgetful functor from an induced category to the original category, forgetting the extra data. -/ @[simps] def induced_functor : induced_category D F ⥤ D := { obj := F, map := λ x y f, f } instance induced_category.full : full (induced_functor F) := { preimage := λ x y f, f } instance induced_category.faithful : faithful (induced_functor F) := {} end induced section full_subcategory /- A full subcategory is the special case of an induced category with F = subtype.val. -/ variables {C : Type u₁} [category.{v} C] variables (Z : C → Prop) /-- A subtype-like structure for full subcategories. Morphisms just ignore the property. We don't use actual subtypes since the simp-normal form `↑X` of `X.val` does not work well for full subcategories. See <https://stacks.math.columbia.edu/tag/001D>. We do not define 'strictly full' subcategories. -/ @[ext, nolint has_nonempty_instance] structure full_subcategory := (obj : C) (property : Z obj) instance full_subcategory.category : category.{v} (full_subcategory Z) := induced_category.category full_subcategory.obj /-- The forgetful functor from a full subcategory into the original category ("forgetting" the condition). -/ def full_subcategory_inclusion : full_subcategory Z ⥤ C := induced_functor full_subcategory.obj @[simp] lemma full_subcategory_inclusion.obj {X} : (full_subcategory_inclusion Z).obj X = X.obj := rfl @[simp] lemma full_subcategory_inclusion.map {X Y} {f : X ⟶ Y} : (full_subcategory_inclusion Z).map f = f := rfl instance full_subcategory.full : full (full_subcategory_inclusion Z) := induced_category.full _ instance full_subcategory.faithful : faithful (full_subcategory_inclusion Z) := induced_category.faithful _ variables {Z} {Z' : C → Prop} /-- An implication of predicates `Z → Z'` induces a functor between full subcategories. -/ @[simps] def full_subcategory.map (h : ∀ ⦃X⦄, Z X → Z' X) : full_subcategory Z ⥤ full_subcategory Z' := { obj := λ X, ⟨X.1, h X.2⟩, map := λ X Y f, f } instance (h : ∀ ⦃X⦄, Z X → Z' X) : full (full_subcategory.map h) := { preimage := λ X Y f, f } instance (h : ∀ ⦃X⦄, Z X → Z' X) : faithful (full_subcategory.map h) := {} @[simp] lemma full_subcategory.map_inclusion (h : ∀ ⦃X⦄, Z X → Z' X) : full_subcategory.map h ⋙ full_subcategory_inclusion Z' = full_subcategory_inclusion Z := rfl section lift variables {D : Type u₂} [category.{v₂} D] (P Q : D → Prop) /-- A functor which maps objects to objects satisfying a certain property induces a lift through the full subcategory of objects satisfying that property. -/ @[simps] def full_subcategory.lift (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) : C ⥤ full_subcategory P := { obj := λ X, ⟨F.obj X, hF X⟩, map := λ X Y f, F.map f } /-- Composing the lift of a functor through a full subcategory with the inclusion yields the original functor. Unfortunately, this is not true by definition, so we only get a natural isomorphism, but it is pointwise definitionally true, see `full_subcategory.inclusion_obj_lift_obj` and `full_subcategory.inclusion_map_lift_map`. -/ def full_subcategory.lift_comp_inclusion (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) : full_subcategory.lift P F hF ⋙ full_subcategory_inclusion P ≅ F := nat_iso.of_components (λ X, iso.refl _) (by simp) @[simp] lemma full_subcategory.inclusion_obj_lift_obj (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) {X : C} : (full_subcategory_inclusion P).obj ((full_subcategory.lift P F hF).obj X) = F.obj X := rfl lemma full_subcategory.inclusion_map_lift_map (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) {X Y : C} (f : X ⟶ Y) : (full_subcategory_inclusion P).map ((full_subcategory.lift P F hF).map f) = F.map f := rfl instance (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) [faithful F] : faithful (full_subcategory.lift P F hF) := faithful.of_comp_iso (full_subcategory.lift_comp_inclusion P F hF) instance (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) [full F] : full (full_subcategory.lift P F hF) := full.of_comp_faithful_iso (full_subcategory.lift_comp_inclusion P F hF) @[simp] lemma full_subcategory.lift_comp_map (F : C ⥤ D) (hF : ∀ X, P (F.obj X)) (h : ∀ ⦃X⦄, P X → Q X) : full_subcategory.lift P F hF ⋙ full_subcategory.map h = full_subcategory.lift Q F (λ X, h (hF X)) := rfl end lift end full_subcategory end category_theory
62cfb8ba3a56b75ed946069e51b8f1364f7dfa6f
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Data/Json/Basic.lean
612399b748e36ced5849f231597fd13471c6b657
[ "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
7,100
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Std.Data.RBTree namespace Lean -- mantissa * 10^-exponent structure JsonNumber where mantissa : Int exponent : Nat deriving DecidableEq namespace JsonNumber protected def fromNat (n : Nat) : JsonNumber := ⟨n, 0⟩ protected def fromInt (n : Int) : JsonNumber := ⟨n, 0⟩ instance : Coe Nat JsonNumber := ⟨JsonNumber.fromNat⟩ instance : Coe Int JsonNumber := ⟨JsonNumber.fromInt⟩ private partial def countDigits (n : Nat) : Nat := let rec loop (n digits : Nat) : Nat := if n ≤ 9 then digits else loop (n/10) (digits+1) loop n 1 -- convert mantissa * 10^-exponent to 0.mantissa * 10^exponent protected def normalize : JsonNumber → Int × Nat × Int | ⟨m, e⟩ => Id.run <| do if m = 0 then (0, 0, 0) else let sign : Int := if m > 0 then 1 else -1 let mut mAbs := m.natAbs let nDigits := countDigits mAbs -- eliminate trailing zeros for _ in [0:nDigits] do if mAbs % 10 = 0 then mAbs := mAbs / 10 else break (sign, mAbs, -(e : Int) + nDigits) -- todo (Dany): We should have an Ordering version of this. def lt (a b : JsonNumber) : Bool := let (as, am, ae) := a.normalize let (bs, bm, be) := b.normalize match (as, bs) with | (-1, 1) => true | (1, -1) => false | _ => let ((am, ae), (bm, be)) := if as = -1 && bs = -1 then ((bm, be), (am, ae)) else ((am, ae), (bm, be)) let amDigits := countDigits am let bmDigits := countDigits bm -- align the mantissas let (am, bm) := if amDigits < bmDigits then (am * 10^(bmDigits - amDigits), bm) else (am, bm * 10^(amDigits - bmDigits)) if ae < be then true else if ae > be then false else am < bm def ltProp : LT JsonNumber := ⟨fun a b => lt a b = true⟩ instance : LT JsonNumber := ltProp instance (a b : JsonNumber) : Decidable (a < b) := inferInstanceAs (Decidable (lt a b = true)) instance : Ord JsonNumber where compare x y := if x < y then Ordering.lt else if x > y then Ordering.gt else Ordering.eq protected def toString : JsonNumber → String | ⟨m, 0⟩ => m.repr | ⟨m, e⟩ => let sign := if m ≥ 0 then "" else "-" let m := m.natAbs -- if there are too many zeroes after the decimal, we -- use exponents to compress the representation. -- this is mostly done for memory usage reasons: -- the size of the representation would otherwise -- grow exponentially in the value of exponent. let exp : Int := 9 + countDigits m - (e : Int) let exp := if exp < 0 then exp else 0 let e' := (10 : Int) ^ (e - exp.natAbs) let left := (m / e').repr let right := e' + coe m % e' |>.repr.toSubstring.drop 1 |>.dropRightWhile (fun c => c = '0') |>.toString let exp := if exp = 0 then "" else "e" ++ exp.repr s!"{sign}{left}.{right}{exp}" -- shift a JsonNumber by a specified amount of places to the left protected def shiftl : JsonNumber → Nat → JsonNumber -- if s ≤ e, then 10 ^ (s - e) = 1, and hence the mantissa remains unchanged. -- otherwise, the expression pads the mantissa with zeroes -- to accomodate for the remaining places to shift. | ⟨m, e⟩, s => ⟨m * (10 ^ (s - e) : Nat), e - s⟩ -- shift a JsonNumber by a specified amount of places to the right protected def shiftr : JsonNumber → Nat → JsonNumber | ⟨m, e⟩, s => ⟨m, e + s⟩ instance : ToString JsonNumber := ⟨JsonNumber.toString⟩ instance : Repr JsonNumber where reprPrec | ⟨m, e⟩, _ => Std.Format.bracket "⟨" (repr m ++ "," ++ repr e) "⟩" end JsonNumber def strLt (a b : String) := Decidable.decide (a < b) open Std (RBNode RBNode.leaf) inductive Json where | null | bool (b : Bool) | num (n : JsonNumber) | str (s : String) | arr (elems : Array Json) -- uses RBNode instead of RBMap because RBMap is a def -- and thus currently cannot be used to define a type that -- is recursive in one of its parameters | obj (kvPairs : RBNode String (fun _ => Json)) deriving Inhabited namespace Json private partial def beq' : Json → Json → Bool | null, null => true | bool a, bool b => a == b | num a, num b => a == b | str a, str b => a == b | arr a, arr b => let _ : BEq Json := ⟨beq'⟩ a == b | obj a, obj b => let _ : BEq Json := ⟨beq'⟩ let szA := a.fold (init := 0) (fun a _ _ => a + 1) let szB := b.fold (init := 0) (fun a _ _ => a + 1) szA == szB && a.all fun field fa => match b.find compare field with | none => false | some fb => fa == fb | _, _ => false instance : BEq Json where beq := beq' -- HACK(Marc): temporary ugliness until we can use RBMap for JSON objects def mkObj (o : List (String × Json)) : Json := obj <| Id.run <| do let mut kvPairs := RBNode.leaf for ⟨k, v⟩ in o do kvPairs := kvPairs.insert compare k v kvPairs instance : Coe Nat Json := ⟨fun n => Json.num n⟩ instance : Coe Int Json := ⟨fun n => Json.num n⟩ instance : Coe String Json := ⟨Json.str⟩ instance : Coe Bool Json := ⟨Json.bool⟩ def isNull : Json -> Bool | null => true | _ => false def getObj? : Json → Except String (RBNode String (fun _ => Json)) | obj kvs => kvs | _ => throw "object expected" def getArr? : Json → Except String (Array Json) | arr a => a | _ => throw "array expected" def getStr? : Json → Except String String | str s => s | _ => throw "String expected" def getNat? : Json → Except String Nat | (n : Nat) => n | _ => throw "Natural number expected" def getInt? : Json → Except String Int | (i : Int) => i | _ => throw "Integer expected" def getBool? : Json → Except String Bool | (b : Bool) => b | _ => throw "Bool expected" def getNum? : Json → Except String JsonNumber | num n => n | _ => throw "number expected" def getObjVal? : Json → String → Except String Json | obj kvs, k => match kvs.find compare k with | some v => v | none => throw s!"property not found: {k}" | _ , _ => throw "object expected" def getArrVal? : Json → Nat → Except String Json | arr a, i => match a.get? i with | some v => v | none => throw s!"index out of bounds: {i}" | _ , _ => throw "array expected" def getObjValD (j : Json) (k : String) : Json := (j.getObjVal? k).toOption.getD null def setObjVal! : Json → String → Json → Json | obj kvs, k, v => obj <| kvs.insert compare k v | j , _, _ => panic! "Json.setObjVal!: not an object: {j}" inductive Structured where | arr (elems : Array Json) | obj (kvPairs : RBNode String (fun _ => Json)) instance : Coe (Array Json) Structured := ⟨Structured.arr⟩ instance : Coe (RBNode String (fun _ => Json)) Structured := ⟨Structured.obj⟩ end Json end Lean
b4e30e3a0c58a47e05bb5870670059fc1e2918be
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/comp_val2.lean
273d119a79633fe913e1abe376dad64be1980842
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
597
lean
open tactic example : 'a' ≠ 'b' := by comp_val example : '0' ≠ 'a' := by comp_val example : "hello worlg" ≠ "hhello world" := by comp_val example : "hello world" ≠ "hhello world" := by comp_val example : "abc" ≠ "cde" := by comp_val example : "abc" ≠ "" := by comp_val example : "" ≠ "cde" := by comp_val example : (⟨3, dec_trivial⟩ : fin 5) ≠ ⟨4, dec_trivial⟩ := by comp_val example : (⟨4, dec_trivial⟩ : fin 5) ≠ ⟨1, dec_trivial⟩ := by comp_val example {P : ℕ → Prop} {h1 : P 1} {h5 : P 5} : (⟨1, h1⟩ : {n // P n}) ≠ ⟨5, h5⟩ := by comp_val
2208eb52c944ed84c7cd9c20065295b0253d7776
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Parser/Syntax.lean
a3c000027df13de5d7babf976a7a6e14d5e6b77b
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,756
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.Command import Lean.Parser.Tactic namespace Lean namespace Parser builtin_initialize registerBuiltinParserAttribute `builtinSyntaxParser `stx LeadingIdentBehavior.both registerBuiltinDynamicParserAttribute `stxParser `stx builtin_initialize registerBuiltinParserAttribute `builtinPrecParser `prec LeadingIdentBehavior.both registerBuiltinDynamicParserAttribute `precParser `prec @[inline] def precedenceParser (rbp : Nat := 0) : Parser := categoryParser `prec rbp @[inline] def syntaxParser (rbp : Nat := 0) : Parser := categoryParser `stx rbp def «precedence» := leading_parser ":" >> precedenceParser maxPrec def optPrecedence := optional (atomic «precedence») namespace Syntax @[builtinPrecParser] def numPrec := checkPrec maxPrec >> numLit @[builtinSyntaxParser] def paren := leading_parser "(" >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def cat := leading_parser ident >> optPrecedence @[builtinSyntaxParser] def unary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def binary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ", " >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def sepBy := leading_parser "sepBy(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")" @[builtinSyntaxParser] def sepBy1 := leading_parser "sepBy1(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")" @[builtinSyntaxParser] def atom := leading_parser strLit @[builtinSyntaxParser] def nonReserved := leading_parser "&" >> strLit end Syntax namespace Term @[builtinTermParser] def stx.quot : Parser := leading_parser "`(stx|" >> incQuotDepth syntaxParser >> ")" @[builtinTermParser] def prec.quot : Parser := leading_parser "`(prec|" >> incQuotDepth precedenceParser >> ")" @[builtinTermParser] def prio.quot : Parser := leading_parser "`(prio|" >> incQuotDepth priorityParser >> ")" end Term namespace Command def namedName := leading_parser (atomic ("(" >> nonReservedSymbol "name") >> " := " >> ident >> ")") def optNamedName := optional namedName def «prefix» := leading_parser "prefix" def «infix» := leading_parser "infix" def «infixl» := leading_parser "infixl" def «infixr» := leading_parser "infixr" def «postfix» := leading_parser "postfix" def mixfixKind := «prefix» <|> «infix» <|> «infixl» <|> «infixr» <|> «postfix» @[builtinCommandParser] def «mixfix» := leading_parser Term.attrKind >> mixfixKind >> precedence >> optNamedName >> optNamedPrio >> ppSpace >> strLit >> darrow >> termParser -- NOTE: We use `suppressInsideQuot` in the following parsers because quotations inside them are evaluated in the same stage and -- thus should be ignored when we use `checkInsideQuot` to prepare the next stage for a builtin syntax change def identPrec := leading_parser ident >> optPrecedence def optKind : Parser := optional ("(" >> nonReservedSymbol "kind" >> ":=" >> ident >> ")") def notationItem := ppSpace >> withAntiquot (mkAntiquot "notationItem" `Lean.Parser.Command.notationItem) (strLit <|> identPrec) @[builtinCommandParser] def «notation» := leading_parser Term.attrKind >> "notation" >> optPrecedence >> optNamedName >> optNamedPrio >> many notationItem >> darrow >> termParser @[builtinCommandParser] def «macro_rules» := suppressInsideQuot (leading_parser optional docComment >> Term.attrKind >> "macro_rules" >> optKind >> Term.matchAlts) @[builtinCommandParser] def «syntax» := leading_parser optional docComment >> Term.attrKind >> "syntax " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 syntaxParser >> " : " >> ident @[builtinCommandParser] def syntaxAbbrev := leading_parser "syntax " >> ident >> " := " >> many1 syntaxParser @[builtinCommandParser] def syntaxCat := leading_parser "declare_syntax_cat " >> ident def macroArg := leading_parser optional (atomic (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> syntaxParser argPrec def macroRhs (quotP : Parser) : Parser := leading_parser "`(" >> incQuotDepth quotP >> ")" <|> termParser def macroTailTactic : Parser := atomic (" : " >> identEq "tactic") >> darrow >> macroRhs Tactic.seq1 def macroTailCommand : Parser := atomic (" : " >> identEq "command") >> darrow >> macroRhs (many1Unbox commandParser) def macroTailDefault : Parser := atomic (" : " >> ident) >> darrow >> macroRhs (categoryParserOfStack 2) def macroTail := leading_parser macroTailTactic <|> macroTailCommand <|> macroTailDefault @[builtinCommandParser] def «macro» := leading_parser suppressInsideQuot (optional docComment >> Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 macroArg >> macroTail) @[builtinCommandParser] def «elab_rules» := leading_parser suppressInsideQuot (optional docComment >> Term.attrKind >> "elab_rules" >> optKind >> optional (" : " >> ident) >> optional (" <= " >> ident) >> Term.matchAlts) def elabArg := macroArg def elabTail := leading_parser atomic (" : " >> ident >> optional (" <= " >> ident)) >> darrow >> termParser @[builtinCommandParser] def «elab» := leading_parser suppressInsideQuot (optional docComment >> Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 elabArg >> elabTail) end Command end Parser end Lean
69002787e092b70359e65965809f9d2a8540d2dc
859855170b866e395d328ebb28c4e060aa5559e8
/src/solutions/09_limits_final.lean
3db41918883fdc7b7a1a5380b5b67d56cd6e9a28
[ "Apache-2.0" ]
permissive
bradheintz/tutorials
1be40c9e97a484441f268ea8504c3d74534162cf
02f15b400478de7278f4baa08935befd0f3986ef
refs/heads/master
1,688,028,802,367
1,627,863,284,000
1,627,863,284,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,756
lean
import tuto_lib set_option pp.beta true set_option pp.coercions false /- This is the final file in the series. Here we use everything covered in previous files to prove a couple of famous theorems from elementary real analysis. Of course they all have more general versions in mathlib. As usual, keep in mind the following: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q as well as a lemma from the previous file: le_of_le_add_all : (∀ ε > 0, y ≤ x + ε) → y ≤ x Let's start with a variation on a known exercise. -/ -- 0071 lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x) (ineg : ∃ N, ∀ n ≥ N, y ≤ u n) : y ≤ x := begin -- sorry apply le_of_le_add_all, intros ε ε_pos, cases hu ε ε_pos with N hN, cases ineg with N' hN', let N₀ := max N N', specialize hN N₀ (le_max_left N N'), specialize hN' N₀ (le_max_right N N'), rw abs_le at hN, linarith, -- sorry end /- Let's now return to the result proved in the `00_` file of this series, and prove again the sequential characterization of upper bounds (with a slighly different proof). For this, and other exercises below, we'll need many things that we proved in previous files, and a couple of extras. From the 5th file: limit_const (x : ℝ) : seq_limit (λ n, x) x squeeze (lim_u : seq_limit u l) (lim_w : seq_limit w l) (hu : ∀ n, u n ≤ v n) (hw : ∀ n, v n ≤ w n) : seq_limit v l From the 8th: def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y lt_sup (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a := You can also use: nat.one_div_pos_of_nat {n : ℕ} : 0 < 1 / (n + 1 : ℝ) inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε and their easy consequences: limit_of_sub_le_inv_succ (h : ∀ n, |u n - x| ≤ 1/(n+1)) : seq_limit u x limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x The structure of the proof is offered. It features a new tactic: `choose` which invokes the axiom of choice (observing the tactic state before and after using it should be enough to understand everything). -/ -- 0072 lemma is_sup_iff (A : set ℝ) (x : ℝ) : (is_sup A x) ↔ (upper_bound A x ∧ ∃ u : ℕ → ℝ, seq_limit u x ∧ ∀ n, u n ∈ A ) := begin split, { intro h, split, { -- sorry exact h.left, -- sorry }, { have : ∀ n : ℕ, ∃ a ∈ A, x - 1/(n+1) < a, { intros n, have : 1/(n+1 : ℝ) > 0, exact nat.one_div_pos_of_nat, -- sorry exact lt_sup h _ (by linarith), -- sorry }, choose u hu using this, -- sorry use u, split, { apply squeeze (limit_const_sub_inv_succ x) (limit_const x), { intros n, exact le_of_lt (hu n).2, }, { intro n, exact h.1 _ (hu n).left, } }, { intro n, exact (hu n).left }, -- sorry } }, { rintro ⟨maj, u, limu, u_in⟩, -- sorry split, { exact maj }, { intros y ymaj, apply lim_le limu, intro n, apply ymaj, apply u_in }, -- sorry }, end /-- Continuity of a function at a point -/ def continuous_at_pt (f : ℝ → ℝ) (x₀ : ℝ) : Prop := ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - f x₀| ≤ ε variables {f : ℝ → ℝ} {x₀ : ℝ} {u : ℕ → ℝ} -- 0073 lemma seq_continuous_of_continuous (hf : continuous_at_pt f x₀) (hu : seq_limit u x₀) : seq_limit (f ∘ u) (f x₀) := begin -- sorry intros ε ε_pos, rcases hf ε ε_pos with ⟨δ, δ_pos, hδ⟩, cases hu δ δ_pos with N hN, use N, intros n hn, apply hδ, exact hN n hn, -- sorry end -- 0074 example : (∀ u : ℕ → ℝ, seq_limit u x₀ → seq_limit (f ∘ u) (f x₀)) → continuous_at_pt f x₀ := begin -- sorry contrapose!, intro hf, unfold continuous_at_pt at hf, push_neg at hf, cases hf with ε h, cases h with ε_pos hf, have H : ∀ n : ℕ, ∃ x, |x - x₀| ≤ 1/(n+1) ∧ ε < |f x - f x₀|, intro n, apply hf, exact nat.one_div_pos_of_nat, clear hf, choose u hu using H, use u, split, intros η η_pos, have fait : ∃ (N : ℕ), ∀ (n : ℕ), n ≥ N → 1 / (↑n + 1) ≤ η, exact inv_succ_le_all η η_pos, cases fait with N hN, use N, intros n hn, calc |u n - x₀| ≤ 1/(n+1) : (hu n).left ... ≤ η : hN n hn, unfold seq_limit, push_neg, use [ε, ε_pos], intro N, use N, split, linarith, exact (hu N).right, -- sorry end /- Recall from the 6th file: def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a id_le_extraction : extraction φ → ∀ n, n ≤ φ n and from the 8th file: def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A not_seq_limit_of_tendstoinfinity : tendsto_infinity u → ∀ l, ¬ seq_limit u l -/ variables {φ : ℕ → ℕ} -- 0075 lemma subseq_tendstoinfinity (h : tendsto_infinity u) (hφ : extraction φ) : tendsto_infinity (u ∘ φ) := begin -- sorry intros A, cases h A with N hN, use N, intros n hn, apply hN, calc N ≤ n : hn ... ≤ φ n : id_le_extraction hφ n, -- sorry end -- 0076 lemma squeeze_infinity {u v : ℕ → ℝ} (hu : tendsto_infinity u) (huv : ∀ n, u n ≤ v n) : tendsto_infinity v := begin -- sorry intros A, cases hu A with N hN, use N, intros n hn, specialize hN n hn, specialize huv n, linarith, -- sorry end /- We will use segments: Icc a b := { x | a ≤ x ∧ x ≤ b } The notation stands for Interval-closed-closed. Variations exist with o or i instead of c, where o stands for open and i for infinity. We will use the following version of Bolzano-Weierstrass bolzano_weierstrass (h : ∀ n, u n ∈ [a, b]) : ∃ c ∈ [a, b], cluster_point u c as well as the obvious seq_limit_id : tendsto_infinity (λ n, n) -/ open set -- 0077 lemma bdd_above_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ M, ∀ x ∈ Icc a b, f x ≤ M := begin -- sorry by_contradiction H, push_neg at H, have clef : ∀ n : ℕ, ∃ x, x ∈ Icc a b ∧ f x > n, intro n, apply H, clear H, choose u hu using clef, have lim_infinie : tendsto_infinity (f ∘ u), apply squeeze_infinity (seq_limit_id), intros n, specialize hu n, linarith, have bornes : ∀ n, u n ∈ Icc a b, intro n, exact (hu n).left, rcases bolzano_weierstrass bornes with ⟨c, c_dans, φ, φ_extr, lim⟩, have lim_infinie_extr : tendsto_infinity (f ∘ (u ∘ φ)), exact subseq_tendstoinfinity lim_infinie φ_extr, have lim_extr : seq_limit (f ∘ (u ∘ φ)) (f c), exact seq_continuous_of_continuous (hf c c_dans) lim, exact not_seq_limit_of_tendstoinfinity lim_infinie_extr (f c) lim_extr, -- sorry end /- In the next exercise, we can use: abs_neg x : |-x| = |x| -/ -- 0078 lemma continuous_opposite {f : ℝ → ℝ} {x₀ : ℝ} (h : continuous_at_pt f x₀) : continuous_at_pt (λ x, -f x) x₀ := begin -- sorry intros ε ε_pos, cases h ε ε_pos with δ h, cases h with δ_pos h, use [δ, δ_pos], intros y hy, have : -f y - -f x₀ = -(f y - f x₀), ring, rw [this, abs_neg], exact h y hy, -- sorry end /- Now let's combine the two exercises above -/ -- 0079 lemma bdd_below_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ m, ∀ x ∈ Icc a b, m ≤ f x := begin -- sorry have : ∃ M, ∀ x ∈ Icc a b, -f x ≤ M, { apply bdd_above_segment, intros x x_dans, exact continuous_opposite (hf x x_dans), }, cases this with M hM, use -M, intros x x_dans, specialize hM x x_dans, linarith, -- sorry end /- Remember from the 5th file: unique_limit : seq_limit u l → seq_limit u l' → l = l' and from the 6th one: subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l We now admit the following version of the least upper bound theorem (that cannot be proved without discussing the construction of real numbers or admitting another strong theorem). sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) : ∃ x ∈ Icc a b, is_sup A x In the next exercise, it can be useful to prove inclusions of sets of real number. By definition, A ⊆ B means : ∀ x, x ∈ A → x ∈ B. Hence one can start a proof of A ⊆ B by `intros x x_in`, which brings `x : ℝ` and `x_in : x ∈ A` in the local context, and then prove `x ∈ B`. Note also the use of {x | P x} which denotes the set of x satisfying predicate P. Hence `x' ∈ { x | P x} ↔ P x'`, by definition. -/ -- 0080 example {a b : ℝ} (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ x₀ ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f x₀ := begin -- sorry cases bdd_below_segment hf with m hm, cases bdd_above_segment hf with M hM, let A := {y | ∃ x ∈ Icc a b, y = f x}, obtain ⟨y₀, y_dans, y_sup⟩ : ∃ y₀ ∈ Icc m M, is_sup A y₀, { apply sup_segment, { use [f a, a, by linarith, hab, by ring], }, { rintros y ⟨x, x_in, rfl⟩, exact ⟨hm x x_in, hM x x_in⟩ } }, rw is_sup_iff at y_sup, rcases y_sup with ⟨y_maj, u, lim_u, u_dans⟩, choose v hv using u_dans, cases forall_and_distrib.mp hv with v_dans hufv, replace hufv : u = f ∘ v := funext hufv, rcases bolzano_weierstrass v_dans with ⟨x₀, x₀_in, φ, φ_extr, lim_vφ⟩, use [x₀, x₀_in], intros x x_dans, have lim : seq_limit (f ∘ v ∘ φ) (f x₀), { apply seq_continuous_of_continuous, exact hf x₀ x₀_in, exact lim_vφ }, have unique : f x₀ = y₀, { apply unique_limit lim, rw hufv at lim_u, exact subseq_tendsto_of_tendsto lim_u φ_extr }, rw unique, apply y_maj, use [x, x_dans], -- sorry end lemma stupid {a b x : ℝ} (h : x ∈ Icc a b) (h' : x ≠ b) : x < b := lt_of_le_of_ne h.right h' /- And now the final boss... -/ def I := (Icc 0 1 : set ℝ) -- the type ascription makes sure 0 and 1 are real numbers here -- 0081 example (f : ℝ → ℝ) (hf : ∀ x, continuous_at_pt f x) (h₀ : f 0 < 0) (h₁ : f 1 > 0) : ∃ x₀ ∈ I, f x₀ = 0 := begin let A := { x | x ∈ I ∧ f x < 0}, have ex_x₀ : ∃ x₀ ∈ I, is_sup A x₀, { -- sorry apply sup_segment, use 0, split, split, linarith, linarith, exact h₀, intros x hx, exact hx.left -- sorry }, rcases ex_x₀ with ⟨x₀, x₀_in, x₀_sup⟩, use [x₀, x₀_in], have : f x₀ ≤ 0, { -- sorry rw is_sup_iff at x₀_sup, rcases x₀_sup with ⟨maj_x₀, u, lim_u, u_dans⟩, have : seq_limit (f ∘ u) (f x₀), exact seq_continuous_of_continuous (hf x₀) lim_u, apply lim_le this, intros n, have : f (u n) < 0, exact (u_dans n).right, linarith -- sorry }, have x₀_1: x₀ < 1, { -- sorry apply stupid x₀_in, intro h, rw ← h at h₁, linarith -- sorry }, have : f x₀ ≥ 0, { have in_I : ∃ N : ℕ, ∀ n ≥ N, x₀ + 1/(n+1) ∈ I, { have : ∃ N : ℕ, ∀ n≥ N, 1/(n+1 : ℝ) ≤ 1-x₀, { -- sorry apply inv_succ_le_all, linarith, -- sorry }, -- sorry cases this with N hN, use N, intros n hn, specialize hN n hn, have : 1/(n+1 : ℝ) > 0, exact nat.one_div_pos_of_nat, change 0 ≤ x₀ ∧ x₀ ≤ 1 at x₀_in, split ; linarith, -- sorry }, have not_in : ∀ n : ℕ, x₀ + 1/(n+1) ∉ A, -- By definition, x ∉ A means ¬ (x ∈ A). { -- sorry intros n hn, cases x₀_sup with x₀_maj _, specialize x₀_maj _ hn, have : 1/(n+1 : ℝ) > 0, from nat.one_div_pos_of_nat, linarith, -- sorry }, dsimp [A] at not_in, -- sorry push_neg at not_in, have lim : seq_limit (λ n, f(x₀ + 1/(n+1))) (f x₀), { apply seq_continuous_of_continuous (hf x₀), apply limit_const_add_inv_succ }, apply le_lim lim, cases in_I with N hN, use N, intros n hn, exact not_in n (hN n hn), -- sorry }, linarith, end
17325dbd3d3a783b61093844e89aa3bafa081543
4727251e0cd73359b15b664c3170e5d754078599
/src/probability/conditional.lean
278b0bfdd21bdc6bf3c20154544a14cee63bcf98
[ "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,576
lean
/- Copyright (c) 2022 Rishikesh Vaishnav. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rishikesh Vaishnav -/ import probability.independence /-! # Conditional Probability This file defines conditional probability and includes basic results relating to it. Given some measure `μ` defined on a measure space on some type `α` and some `s : set α`, we define the measure of `μ` conditioned on `s` as the restricted measure scaled by the inverse of the measure of `s`: `cond μ s = (μ s)⁻¹ • μ.restrict s`. The scaling ensures that this is a probability measure (when `μ` is a finite measure). From this definition, we derive the "axiomatic" definition of conditional probability based on application: for any `s t : set α`, we have `μ[t|s] = (μ s)⁻¹ * μ (s ∩ t)`. ## Main Statements * `cond_cond_eq_cond_inter`: conditioning on one set and then another is equivalent to conditioning on their intersection. * `cond_eq_inv_mul_cond_mul`: Bayes' Theorem, `μ[t|s] = (μ s)⁻¹ * μ[s|t] * (μ t)`. ## Notations This file uses the notation `μ[|s]` the measure of `μ` conditioned on `s`, and `μ[t|s]` for the probability of `t` given `s` under `μ` (equivalent to the application `μ[|s] t`). These notations are contained in the locale `probability_theory`. ## Implementation notes Because we have the alternative measure restriction application principles `measure.restrict_apply` and `measure.restrict_apply'`, which require measurability of the restricted and restricting sets, respectively, many of the theorems here will have corresponding alternatives as well. For the sake of brevity, we've chosen to only go with `measure.restrict_apply'` for now, but the alternative theorems can be added if needed. Use of `@[simp]` generally follows the rule of removing conditions on a measure when possible. Hypotheses that are used to "define" a conditional distribution by requiring that the conditioning set has non-zero measure should be named using the abbreviation "c" (which stands for "conditionable") rather than "nz". For example `(hci : μ (s ∩ t) ≠ 0)` (rather than `hnzi`) should be used for a hypothesis ensuring that `μ[|s ∩ t]` is defined. ## Tags conditional, conditioned, bayes -/ noncomputable theory open_locale ennreal open measure_theory measurable_space variables {α : Type*} {m : measurable_space α} (μ : measure α) {s t : set α} namespace probability_theory section definitions /-- The conditional probability measure of measure `μ` on set `s` is `μ` restricted to `s` and scaled by the inverse of `μ s` (to make it a probability measure): `(μ s)⁻¹ • μ.restrict s`. -/ def cond (s : set α) : measure α := (μ s)⁻¹ • μ.restrict s end definitions localized "notation μ `[` s `|` t `]` := probability_theory.cond μ t s" in probability_theory localized "notation μ `[|`:60 t`]` := probability_theory.cond μ t" in probability_theory /-- The conditional probability measure of any finite measure on any set of positive measure is a probability measure. -/ lemma cond_is_probability_measure [is_finite_measure μ] (hcs : μ s ≠ 0) : is_probability_measure $ μ[|s] := ⟨by { rw [cond, measure.smul_apply, measure.restrict_apply measurable_set.univ, set.univ_inter], exact ennreal.inv_mul_cancel hcs (measure_ne_top _ s) }⟩ section bayes @[simp] lemma cond_empty : μ[|∅] = 0 := by simp [cond] @[simp] lemma cond_univ [is_probability_measure μ] : μ[|set.univ] = μ := by simp [cond, measure_univ, measure.restrict_univ] /-- The axiomatic definition of conditional probability derived from a measure-theoretic one. -/ lemma cond_apply (hms : measurable_set s) (t : set α) : μ[t|s] = (μ s)⁻¹ * μ (s ∩ t) := by { rw [cond, measure.smul_apply, measure.restrict_apply' hms, set.inter_comm], refl } lemma cond_inter_self (hms : measurable_set s) (t : set α) : μ[s ∩ t|s] = μ[t|s] := by rw [cond_apply _ hms, ← set.inter_assoc, set.inter_self, ← cond_apply _ hms] lemma inter_pos_of_cond_ne_zero (hms : measurable_set s) (hcst : μ[t|s] ≠ 0) : 0 < μ (s ∩ t) := begin refine pos_iff_ne_zero.mpr (right_ne_zero_of_mul _), { exact (μ s)⁻¹ }, convert hcst, simp [hms, set.inter_comm] end lemma cond_pos_of_inter_ne_zero [is_finite_measure μ] (hms : measurable_set s) (hci : μ (s ∩ t) ≠ 0) : 0 < μ[|s] t := begin rw cond_apply _ hms, refine ennreal.mul_pos _ hci, exact ennreal.inv_ne_zero.mpr (measure_ne_top _ _), end lemma cond_cond_eq_cond_inter' (hms : measurable_set s) (hmt : measurable_set t) (hcs : μ s ≠ ∞) (hci : μ (s ∩ t) ≠ 0) : μ[|s][|t] = μ[|s ∩ t] := begin have hcs : μ s ≠ 0 := (μ.to_outer_measure.pos_of_subset_ne_zero (set.inter_subset_left _ _) hci).ne', ext u, simp [*, hms.inter hmt, cond_apply, ← mul_assoc, ← set.inter_assoc, ennreal.mul_inv, mul_comm, ← mul_assoc, ennreal.inv_mul_cancel], end /-- Conditioning first on `s` and then on `t` results in the same measure as conditioning on `s ∩ t`. -/ lemma cond_cond_eq_cond_inter [is_finite_measure μ] (hms : measurable_set s) (hmt : measurable_set t) (hci : μ (s ∩ t) ≠ 0) : μ[|s][|t] = μ[|s ∩ t] := cond_cond_eq_cond_inter' μ hms hmt (measure_ne_top μ s) hci lemma cond_mul_eq_inter' (hms : measurable_set s) (hcs : μ s ≠ 0) (hcs' : μ s ≠ ∞) (t : set α) : μ[t|s] * μ s = μ (s ∩ t) := by rw [cond_apply μ hms t, mul_comm, ←mul_assoc, ennreal.mul_inv_cancel hcs hcs', one_mul] lemma cond_mul_eq_inter [is_finite_measure μ] (hms : measurable_set s) (hcs : μ s ≠ 0) (t : set α) : μ[t|s] * μ s = μ (s ∩ t) := cond_mul_eq_inter' μ hms hcs (measure_ne_top _ s) t /-- A version of the law of total probability. -/ lemma cond_add_cond_compl_eq [is_finite_measure μ] (hms : measurable_set s) (hcs : μ s ≠ 0) (hcs' : μ sᶜ ≠ 0) : μ[t|s] * μ s + μ[t|sᶜ] * μ sᶜ = μ t := begin rw [cond_mul_eq_inter μ hms hcs, cond_mul_eq_inter μ hms.compl hcs', set.inter_comm _ t, set.inter_comm _ t], exact measure_inter_add_diff t hms, end /-- **Bayes' Theorem** -/ theorem cond_eq_inv_mul_cond_mul [is_finite_measure μ] (hms : measurable_set s) (hmt : measurable_set t) : μ[t|s] = (μ s)⁻¹ * μ[s|t] * (μ t) := begin by_cases ht : μ t = 0, { simp [cond, ht, measure.restrict_apply hmt, or.inr (measure_inter_null_of_null_left s ht)] }, { rw [mul_assoc, cond_mul_eq_inter μ hmt ht s, set.inter_comm, cond_apply _ hms] } end end bayes end probability_theory
a9b267a1412dea9585caa0460b03627ef0b94bb5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/orientation.lean
3a940f78fb7b93d3df34744be6096642c7ac2af0
[ "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
15,368
lean
/- Copyright (c) 2021 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.ray import linear_algebra.determinant /-! # Orientations of modules This file defines orientations of modules. ## Main definitions * `orientation` is a type synonym for `module.ray` for the case where the module is that of alternating maps from a module to its underlying ring. An orientation may be associated with an alternating map or with a basis. * `module.oriented` is a type class for a choice of orientation of a module that is considered the positive orientation. ## Implementation notes `orientation` is defined for an arbitrary index type, but the main intended use case is when that index type is a `fintype` and there exists a basis of the same cardinality. ## References * https://en.wikipedia.org/wiki/Orientation_(vector_space) -/ noncomputable theory open_locale big_operators section ordered_comm_semiring variables (R : Type*) [strict_ordered_comm_semiring R] variables (M : Type*) [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] variables (ι : Type*) [decidable_eq ι] /-- An orientation of a module, intended to be used when `ι` is a `fintype` with the same cardinality as a basis. -/ abbreviation orientation := module.ray R (alternating_map R M R ι) /-- A type class fixing an orientation of a module. -/ class module.oriented := (positive_orientation : orientation R M ι) export module.oriented (positive_orientation) variables {R M} /-- An equivalence between modules implies an equivalence between orientations. -/ def orientation.map (e : M ≃ₗ[R] N) : orientation R M ι ≃ orientation R N ι := module.ray.map $ alternating_map.dom_lcongr R R ι R e @[simp] lemma orientation.map_apply (e : M ≃ₗ[R] N) (v : alternating_map R M R ι) (hv : v ≠ 0) : orientation.map ι e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (v.comp_linear_map e.symm) (mt (v.comp_linear_equiv_eq_zero_iff e.symm).mp hv) := rfl @[simp] lemma orientation.map_refl : (orientation.map ι $ linear_equiv.refl R M) = equiv.refl _ := by rw [orientation.map, alternating_map.dom_lcongr_refl, module.ray.map_refl] @[simp] lemma orientation.map_symm (e : M ≃ₗ[R] N) : (orientation.map ι e).symm = orientation.map ι e.symm := rfl /-- A module is canonically oriented with respect to an empty index type. -/ @[priority 100] instance is_empty.oriented [nontrivial R] [is_empty ι] : module.oriented R M ι := { positive_orientation := ray_of_ne_zero R (alternating_map.const_linear_equiv_of_is_empty 1) $ alternating_map.const_linear_equiv_of_is_empty.injective.ne (by simp) } @[simp] lemma orientation.map_positive_orientation_of_is_empty [nontrivial R] [is_empty ι] (f : M ≃ₗ[R] N) : orientation.map ι f positive_orientation = positive_orientation := rfl @[simp] lemma orientation.map_of_is_empty [is_empty ι] (x : orientation R M ι) (f : M ≃ₗ[R] M) : orientation.map ι f x = x := begin induction x using module.ray.ind with g hg, rw orientation.map_apply, congr, ext i, rw alternating_map.comp_linear_map_apply, congr, end end ordered_comm_semiring section ordered_comm_ring variables {R : Type*} [strict_ordered_comm_ring R] variables {M N : Type*} [add_comm_group M] [add_comm_group N] [module R M] [module R N] @[simp] protected lemma orientation.map_neg {ι : Type*} [decidable_eq ι] (f : M ≃ₗ[R] N) (x : orientation R M ι) : orientation.map ι f (-x) = - orientation.map ι f x := module.ray.map_neg _ x namespace basis variables {ι : Type*} [decidable_eq ι] /-- The value of `orientation.map` when the index type has the cardinality of a basis, in terms of `f.det`. -/ lemma map_orientation_eq_det_inv_smul [finite ι] (e : basis ι R M) (x : orientation R M ι) (f : M ≃ₗ[R] M) : orientation.map ι f x = (f.det)⁻¹ • x := begin casesI nonempty_fintype ι, induction x using module.ray.ind with g hg, rw [orientation.map_apply, smul_ray_of_ne_zero, ray_eq_iff, units.smul_def, (g.comp_linear_map ↑f.symm).eq_smul_basis_det e, g.eq_smul_basis_det e, alternating_map.comp_linear_map_apply, alternating_map.smul_apply, basis.det_comp, basis.det_self, mul_one, smul_eq_mul, mul_comm, mul_smul, linear_equiv.coe_inv_det], end variables [fintype ι] /-- The orientation given by a basis. -/ protected def orientation [nontrivial R] (e : basis ι R M) : orientation R M ι := ray_of_ne_zero R _ e.det_ne_zero lemma orientation_map [nontrivial R] (e : basis ι R M) (f : M ≃ₗ[R] N) : (e.map f).orientation = orientation.map ι f e.orientation := by simp_rw [basis.orientation, orientation.map_apply, basis.det_map'] /-- The orientation given by a basis derived using `units_smul`, in terms of the product of those units. -/ lemma orientation_units_smul [nontrivial R] (e : basis ι R M) (w : ι → units R) : (e.units_smul w).orientation = (∏ i, w i)⁻¹ • e.orientation := begin rw [basis.orientation, basis.orientation, smul_ray_of_ne_zero, ray_eq_iff, e.det.eq_smul_basis_det (e.units_smul w), det_units_smul_self, units.smul_def, smul_smul], norm_cast, simp end @[simp] lemma orientation_is_empty [nontrivial R] [is_empty ι] (b : basis ι R M) : b.orientation = positive_orientation := begin congrm ray_of_ne_zero _ _ _, convert b.det_is_empty, end end basis end ordered_comm_ring section linear_ordered_comm_ring variables {R : Type*} [linear_ordered_comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} [decidable_eq ι] namespace orientation /-- A module `M` over a linearly ordered commutative ring has precisely two "orientations" with respect to an empty index type. (Note that these are only orientations of `M` of in the conventional mathematical sense if `M` is zero-dimensional.) -/ lemma eq_or_eq_neg_of_is_empty [nontrivial R] [is_empty ι] (o : orientation R M ι) : o = positive_orientation ∨ o = - positive_orientation := begin induction o using module.ray.ind with x hx, dsimp [positive_orientation], simp only [ray_eq_iff, same_ray_neg_swap], rw same_ray_or_same_ray_neg_iff_not_linear_independent, intros h, let a : R := alternating_map.const_linear_equiv_of_is_empty.symm x, have H : linear_independent R ![a, 1], { convert h.map' ↑alternating_map.const_linear_equiv_of_is_empty.symm (linear_equiv.ker _), ext i, fin_cases i; simp [a] }, rw linear_independent_iff' at H, simpa using H finset.univ ![1, -a] (by simp [fin.sum_univ_succ]) 0 (by simp), end end orientation namespace basis variables [fintype ι] /-- The orientations given by two bases are equal if and only if the determinant of one basis with respect to the other is positive. -/ lemma orientation_eq_iff_det_pos (e₁ e₂ : basis ι R M) : e₁.orientation = e₂.orientation ↔ 0 < e₁.det e₂ := calc e₁.orientation = e₂.orientation ↔ same_ray R e₁.det e₂.det : ray_eq_iff _ _ ... ↔ same_ray R (e₁.det e₂ • e₂.det) e₂.det : by rw [← e₁.det.eq_smul_basis_det e₂] ... ↔ 0 < e₁.det e₂ : same_ray_smul_left_iff_of_ne e₂.det_ne_zero (e₁.is_unit_det e₂).ne_zero /-- Given a basis, any orientation equals the orientation given by that basis or its negation. -/ lemma orientation_eq_or_eq_neg (e : basis ι R M) (x : orientation R M ι) : x = e.orientation ∨ x = -e.orientation := begin induction x using module.ray.ind with x hx, rw ← x.map_basis_ne_zero_iff e at hx, rwa [basis.orientation, ray_eq_iff, neg_ray_of_ne_zero, ray_eq_iff, x.eq_smul_basis_det e, same_ray_neg_smul_left_iff_of_ne e.det_ne_zero hx, same_ray_smul_left_iff_of_ne e.det_ne_zero hx, lt_or_lt_iff_ne, ne_comm] end /-- Given a basis, an orientation equals the negation of that given by that basis if and only if it does not equal that given by that basis. -/ lemma orientation_ne_iff_eq_neg (e : basis ι R M) (x : orientation R M ι) : x ≠ e.orientation ↔ x = -e.orientation := ⟨λ h, (e.orientation_eq_or_eq_neg x).resolve_left h, λ h, h.symm ▸ (module.ray.ne_neg_self e.orientation).symm⟩ /-- Composing a basis with a linear equiv gives the same orientation if and only if the determinant is positive. -/ lemma orientation_comp_linear_equiv_eq_iff_det_pos (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = e.orientation ↔ 0 < (f : M →ₗ[R] M).det := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] /-- Composing a basis with a linear equiv gives the negation of that orientation if and only if the determinant is negative. -/ lemma orientation_comp_linear_equiv_eq_neg_iff_det_neg (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = -e.orientation ↔ (f : M →ₗ[R] M).det < 0 := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] /-- Negating a single basis vector (represented using `units_smul`) negates the corresponding orientation. -/ @[simp] lemma orientation_neg_single [nontrivial R] (e : basis ι R M) (i : ι) : (e.units_smul (function.update 1 i (-1))).orientation = -e.orientation := begin rw [orientation_units_smul, finset.prod_update_of_mem (finset.mem_univ _)], simp end /-- Given a basis and an orientation, return a basis giving that orientation: either the original basis, or one constructed by negating a single (arbitrary) basis vector. -/ def adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : basis ι R M := by haveI := classical.dec_eq (orientation R M ι); exact if e.orientation = x then e else (e.units_smul (function.update 1 (classical.arbitrary ι) (-1))) /-- `adjust_to_orientation` gives a basis with the required orientation. -/ @[simp] lemma orientation_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : (e.adjust_to_orientation x).orientation = x := begin rw adjust_to_orientation, split_ifs with h, { exact h }, { rw [orientation_neg_single, eq_comm, ←orientation_ne_iff_eq_neg, ne_comm], exact h } end /-- Every basis vector from `adjust_to_orientation` is either that from the original basis or its negation. -/ lemma adjust_to_orientation_apply_eq_or_eq_neg [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) (i : ι) : e.adjust_to_orientation x i = e i ∨ e.adjust_to_orientation x i = -(e i) := begin rw adjust_to_orientation, split_ifs with h, { simp }, { by_cases hi : i = classical.arbitrary ι; simp [units_smul_apply, hi] } end lemma det_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : (e.adjust_to_orientation x).det = e.det ∨ (e.adjust_to_orientation x).det = - e.det := begin dsimp [basis.adjust_to_orientation], split_ifs, { left, refl }, { right, simp [e.det_units_smul, ← units.coe_prod, finset.prod_update_of_mem] } end @[simp] lemma abs_det_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) (v : ι → M) : |(e.adjust_to_orientation x).det v| = |e.det v| := begin cases e.det_adjust_to_orientation x with h h; simp [h] end end basis end linear_ordered_comm_ring section linear_ordered_field variables {R : Type*} [linear_ordered_field R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} [decidable_eq ι] namespace orientation variables [fintype ι] [_i : finite_dimensional R M] open finite_dimensional include _i /-- If the index type has cardinality equal to the finite dimension, any two orientations are equal or negations. -/ lemma eq_or_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ = x₂ ∨ x₁ = -x₂ := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, rcases e.orientation_eq_or_eq_neg x₁ with h₁|h₁; rcases e.orientation_eq_or_eq_neg x₂ with h₂|h₂; simp [h₁, h₂] end /-- If the index type has cardinality equal to the finite dimension, an orientation equals the negation of another orientation if and only if they are not equal. -/ lemma ne_iff_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ ≠ x₂ ↔ x₁ = -x₂ := ⟨λ hn, (eq_or_eq_neg x₁ x₂ h).resolve_left hn, λ he, he.symm ▸ (module.ray.ne_neg_self x₂).symm⟩ /-- The value of `orientation.map` when the index type has cardinality equal to the finite dimension, in terms of `f.det`. -/ lemma map_eq_det_inv_smul (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = (f.det)⁻¹ • x := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, exact e.map_orientation_eq_det_inv_smul x f end omit _i /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the same orientation if and only if the determinant is positive. -/ lemma map_eq_iff_det_pos (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = x ↔ 0 < (f : M →ₗ[R] M).det := begin casesI is_empty_or_nonempty ι, { have H : finrank R M = 0, { refine h.symm.trans _, convert fintype.card_of_is_empty, apply_instance }, simp [linear_map.det_eq_one_of_finrank_eq_zero H] }, have H : 0 < finrank R M, { rw ← h, exact fintype.card_pos }, haveI : finite_dimensional R M := finite_dimensional_of_finrank H, rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] end /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the negation of that orientation if and only if the determinant is negative. -/ lemma map_eq_neg_iff_det_neg (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = -x ↔ (f : M →ₗ[R] M).det < 0 := begin casesI is_empty_or_nonempty ι, { have H : finrank R M = 0, { refine h.symm.trans _, convert fintype.card_of_is_empty, apply_instance }, simp [linear_map.det_eq_one_of_finrank_eq_zero H, module.ray.ne_neg_self x] }, have H : 0 < finrank R M, { rw ← h, exact fintype.card_pos }, haveI : finite_dimensional R M := finite_dimensional_of_finrank H, rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] end include _i /-- If the index type has cardinality equal to the finite dimension, a basis with the given orientation. -/ def some_basis [nonempty ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : basis ι R M := ((fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm).adjust_to_orientation x /-- `some_basis` gives a basis with the required orientation. -/ @[simp] lemma some_basis_orientation [nonempty ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : (x.some_basis h).orientation = x := basis.orientation_adjust_to_orientation _ _ end orientation end linear_ordered_field
3bca4d0253a3db65fcb990a899bee1c3f1cedb31
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/int/basic.lean
916572a3304d4e146d35f01ef424a05af5036820
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
42,210
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic algebra.char_zero algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨0⟩ meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩ attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] @[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_le_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i, p i → p (i + 1)) (hn : ∀i, p i → p (i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { have := hn _ n_ih, simpa } }, exact this (i + 1) } end /- / -/ theorem of_nat_div (m n : nat) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl theorem neg_succ_of_nat_div (m : nat) {b : ℤ} (H : b > 0) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) @[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ @[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ @[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → a % b ≥ 0 | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] @[simp] theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : a ≥ 0) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] /- dvd -/ theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : c > 0) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : c > 0) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : m ≥ n.succ) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have, { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ_inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp [(*), int.mul, nat_abs_neg_of_nat] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq] /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros i m; simp [bodd]; cases i.bodd; cases m.bodd; refl @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd]; cases m.bodd; cases n.bodd; refl @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd]; cases m.bodd; cases n.bodd; refl theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) @[priority 0] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩ @[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl @[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl @[simp] theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n := by simp @[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add]; apply congr_arg (λ x:ℕ, -(x:α)); simp @[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 @[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] theorem eq_cast [add_group α] [has_one α] (f : ℤ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n := begin have H : ∀ (n : ℕ), f n = n := nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y), cases n, {apply H}, apply eq_neg_of_add_eq_zero, rw [← nat.cast_zero, ← H 0, int.coe_nat_zero, ← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1), Hadd, show f (n+1) = n+1, from H (n+1)] end @[simp] theorem cast_id (n : ℤ) : ↑n = n := (eq_cast id rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast end int
bfe3363d254b095beac1224cecb1ae9ad9a98ca2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/iterated_deriv.lean
1c1f1e4c36a40ac081b63214fbd25ba70a2fca10
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,246
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv.comp import analysis.calculus.cont_diff_def /-! # One-dimensional iterated derivatives > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the `n`-th derivative of a function `f : 𝕜 → F` as a function `iterated_deriv n f : 𝕜 → F`, as well as a version on domains `iterated_deriv_within n f s : 𝕜 → F`, and prove their basic properties. ## Main definitions and results Let `𝕜` be a nontrivially normed field, and `F` a normed vector space over `𝕜`. Let `f : 𝕜 → F`. * `iterated_deriv n f` is the `n`-th derivative of `f`, seen as a function from `𝕜` to `F`. It is defined as the `n`-th Fréchet derivative (which is a multilinear map) applied to the vector `(1, ..., 1)`, to take advantage of all the existing framework, but we show that it coincides with the naive iterative definition. * `iterated_deriv_eq_iterate` states that the `n`-th derivative of `f` is obtained by starting from `f` and differentiating it `n` times. * `iterated_deriv_within n f s` is the `n`-th derivative of `f` within the domain `s`. It only behaves well when `s` has the unique derivative property. * `iterated_deriv_within_eq_iterate` states that the `n`-th derivative of `f` in the domain `s` is obtained by starting from `f` and differentiating it `n` times within `s`. This only holds when `s` has the unique derivative property. ## Implementation details The results are deduced from the corresponding results for the more general (multilinear) iterated Fréchet derivative. For this, we write `iterated_deriv n f` as the composition of `iterated_fderiv 𝕜 n f` and a continuous linear equiv. As continuous linear equivs respect differentiability and commute with differentiation, this makes it possible to prove readily that the derivative of the `n`-th derivative is the `n+1`-th derivative in `iterated_deriv_within_succ`, by translating the corresponding result `iterated_fderiv_within_succ_apply_left` for the iterated Fréchet derivative. -/ noncomputable theory open_locale classical topology big_operators open filter asymptotics set variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] /-- The `n`-th iterated derivative of a function from `𝕜` to `F`, as a function from `𝕜` to `F`. -/ def iterated_deriv (n : ℕ) (f : 𝕜 → F) (x : 𝕜) : F := (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) /-- The `n`-th iterated derivative of a function from `𝕜` to `F` within a set `s`, as a function from `𝕜` to `F`. -/ def iterated_deriv_within (n : ℕ) (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) : F := (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) variables {n : ℕ} {f : 𝕜 → F} {s : set 𝕜} {x : 𝕜} lemma iterated_deriv_within_univ : iterated_deriv_within n f univ = iterated_deriv n f := by { ext x, rw [iterated_deriv_within, iterated_deriv, iterated_fderiv_within_univ] } /-! ### Properties of the iterated derivative within a set -/ lemma iterated_deriv_within_eq_iterated_fderiv_within : iterated_deriv_within n f s x = (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_within_eq_equiv_comp : iterated_deriv_within n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv_within 𝕜 n f s) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_within_eq_equiv_comp : iterated_fderiv_within 𝕜 n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv_within n f s) := by rw [iterated_deriv_within_eq_equiv_comp, ← function.comp.assoc, linear_isometry_equiv.self_comp_symm, function.left_id] /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_within_apply_eq_iterated_deriv_within_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv_within n f s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, ← continuous_multilinear_map.map_smul_univ], simp end lemma norm_iterated_fderiv_within_eq_norm_iterated_deriv_within : ‖iterated_fderiv_within 𝕜 n f s x‖ = ‖iterated_deriv_within n f s x‖ := by rw [iterated_deriv_within_eq_equiv_comp, linear_isometry_equiv.norm_map] @[simp] lemma iterated_deriv_within_zero : iterated_deriv_within 0 f s = f := by { ext x, simp [iterated_deriv_within] } @[simp] lemma iterated_deriv_within_one {x : 𝕜} (h : unique_diff_within_at 𝕜 s x): iterated_deriv_within 1 f s x = deriv_within f s x := by { simp only [iterated_deriv_within, iterated_fderiv_within_one_apply h], refl } /-- If the first `n` derivatives within a set of a function are continuous, and its first `n-1` derivatives are differentiable, then the function is `C^n`. This is not an equivalence in general, but this is an equivalence when the set has unique derivatives, see `cont_diff_on_iff_continuous_on_differentiable_on_deriv`. -/ lemma cont_diff_on_of_continuous_on_differentiable_on_deriv {n : ℕ∞} (Hcont : ∀ (m : ℕ), (m : ℕ∞) ≤ n → continuous_on (λ x, iterated_deriv_within m f s x) s) (Hdiff : ∀ (m : ℕ), (m : ℕ∞) < n → differentiable_on 𝕜 (λ x, iterated_deriv_within m f s x) s) : cont_diff_on 𝕜 n f s := begin apply cont_diff_on_of_continuous_on_differentiable_on, { simpa [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff] }, { simpa [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] } end /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma cont_diff_on_of_differentiable_on_deriv {n : ℕ∞} (h : ∀(m : ℕ), (m : ℕ∞) ≤ n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) : cont_diff_on 𝕜 n f s := begin apply cont_diff_on_of_differentiable_on, simpa only [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] end /-- On a set with unique derivatives, a `C^n` function has derivatives up to `n` which are continuous. -/ lemma cont_diff_on.continuous_on_iterated_deriv_within {n : ℕ∞} {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : ℕ∞) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_deriv_within m f s) s := by simpa only [iterated_deriv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff] using h.continuous_on_iterated_fderiv_within hmn hs lemma cont_diff_within_at.differentiable_within_at_iterated_deriv_within {n : ℕ∞} {m : ℕ} (h : cont_diff_within_at 𝕜 n f s x) (hmn : (m : ℕ∞) < n) (hs : unique_diff_on 𝕜 (insert x s)) : differentiable_within_at 𝕜 (iterated_deriv_within m f s) s x := by simpa only [iterated_deriv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_within_at_iff] using h.differentiable_within_at_iterated_fderiv_within hmn hs /-- On a set with unique derivatives, a `C^n` function has derivatives less than `n` which are differentiable. -/ lemma cont_diff_on.differentiable_on_iterated_deriv_within {n : ℕ∞} {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : ℕ∞) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_deriv_within m f s) s := λ x hx, (h x hx).differentiable_within_at_iterated_deriv_within hmn $ by rwa [insert_eq_of_mem hx] /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative on sets with unique derivatives. -/ lemma cont_diff_on_iff_continuous_on_differentiable_on_deriv {n : ℕ∞} (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 n f s ↔ (∀m:ℕ, (m : ℕ∞) ≤ n → continuous_on (iterated_deriv_within m f s) s) ∧ (∀m:ℕ, (m : ℕ∞) < n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) := by simp only [cont_diff_on_iff_continuous_on_differentiable_on hs, iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff, linear_isometry_equiv.comp_differentiable_on_iff] /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_within_succ {x : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : iterated_deriv_within (n + 1) f s x = deriv_within (iterated_deriv_within n f s) s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_fderiv_within _ hxs, deriv_within], change ((continuous_multilinear_map.mk_pi_field 𝕜 (fin n) ((fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1)) : (fin n → 𝕜 ) → F) (λ (i : fin n), 1) = (fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1, simp end /-- The `n`-th iterated derivative within a set with unique derivatives can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_within_eq_iterate {x : 𝕜} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within n f s x = ((λ (g : 𝕜 → F), deriv_within g s)^[n]) f x := begin induction n with n IH generalizing x, { simp }, { rw [iterated_deriv_within_succ (hs x hx), function.iterate_succ'], exact deriv_within_congr (λ y hy, IH hy) (IH hx) } end /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_within_succ' {x : 𝕜} (hxs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within (n + 1) f s x = (iterated_deriv_within n (deriv_within f s) s) x := by { rw [iterated_deriv_within_eq_iterate hxs hx, iterated_deriv_within_eq_iterate hxs hx], refl } /-! ### Properties of the iterated derivative on the whole space -/ lemma iterated_deriv_eq_iterated_fderiv : iterated_deriv n f x = (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_eq_equiv_comp : iterated_deriv n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv 𝕜 n f) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_eq_equiv_comp : iterated_fderiv 𝕜 n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv n f) := by rw [iterated_deriv_eq_equiv_comp, ← function.comp.assoc, linear_isometry_equiv.self_comp_symm, function.left_id] /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_apply_eq_iterated_deriv_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv n f x := by { rw [iterated_deriv_eq_iterated_fderiv, ← continuous_multilinear_map.map_smul_univ], simp } lemma norm_iterated_fderiv_eq_norm_iterated_deriv : ‖iterated_fderiv 𝕜 n f x‖ = ‖iterated_deriv n f x‖ := by rw [iterated_deriv_eq_equiv_comp, linear_isometry_equiv.norm_map] @[simp] lemma iterated_deriv_zero : iterated_deriv 0 f = f := by { ext x, simp [iterated_deriv] } @[simp] lemma iterated_deriv_one : iterated_deriv 1 f = deriv f := by { ext x, simp [iterated_deriv], refl } /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative. -/ lemma cont_diff_iff_iterated_deriv {n : ℕ∞} : cont_diff 𝕜 n f ↔ (∀m:ℕ, (m : ℕ∞) ≤ n → continuous (iterated_deriv m f)) ∧ (∀m:ℕ, (m : ℕ∞) < n → differentiable 𝕜 (iterated_deriv m f)) := by simp only [cont_diff_iff_continuous_differentiable, iterated_fderiv_eq_equiv_comp, linear_isometry_equiv.comp_continuous_iff, linear_isometry_equiv.comp_differentiable_iff] /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma cont_diff_of_differentiable_iterated_deriv {n : ℕ∞} (h : ∀(m : ℕ), (m : ℕ∞) ≤ n → differentiable 𝕜 (iterated_deriv m f)) : cont_diff 𝕜 n f := cont_diff_iff_iterated_deriv.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ lemma cont_diff.continuous_iterated_deriv {n : ℕ∞} (m : ℕ) (h : cont_diff 𝕜 n f) (hmn : (m : ℕ∞) ≤ n) : continuous (iterated_deriv m f) := (cont_diff_iff_iterated_deriv.1 h).1 m hmn lemma cont_diff.differentiable_iterated_deriv {n : ℕ∞} (m : ℕ) (h : cont_diff 𝕜 n f) (hmn : (m : ℕ∞) < n) : differentiable 𝕜 (iterated_deriv m f) := (cont_diff_iff_iterated_deriv.1 h).2 m hmn /-- The `n+1`-th iterated derivative can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_succ : iterated_deriv (n + 1) f = deriv (iterated_deriv n f) := begin ext x, rw [← iterated_deriv_within_univ, ← iterated_deriv_within_univ, ← deriv_within_univ], exact iterated_deriv_within_succ unique_diff_within_at_univ, end /-- The `n`-th iterated derivative can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_eq_iterate : iterated_deriv n f = (deriv^[n]) f := begin ext x, rw [← iterated_deriv_within_univ], convert iterated_deriv_within_eq_iterate unique_diff_on_univ (mem_univ x), simp [deriv_within_univ] end /-- The `n+1`-th iterated derivative can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_succ' : iterated_deriv (n + 1) f = iterated_deriv n (deriv f) := by { rw [iterated_deriv_eq_iterate, iterated_deriv_eq_iterate], refl }
95e6d3c00847ffdb904519648b3775bdfed4a0d2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/representation_theory/fdRep.lean
213f589b738dd0b241f207f221fce845d415f504
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,504
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import representation_theory.Rep import algebra.category.fgModule.limits import category_theory.preadditive.schur import representation_theory.basic /-! # `fdRep k G` is the category of finite dimensional `k`-linear representations of `G`. If `V : fdRep k G`, there is a coercion that allows you to treat `V` as a type, and this type comes equipped with `module k V` and `finite_dimensional k V` instances. Also `V.ρ` gives the homomorphism `G →* (V →ₗ[k] V)`. Conversely, given a homomorphism `ρ : G →* (V →ₗ[k] V)`, you can construct the bundled representation as `Rep.of ρ`. We verify that `fdRep k G` is a `k`-linear monoidal category, and rigid when `G` is a group. `fdRep k G` has all finite limits. ## TODO * `fdRep k G ≌ full_subcategory (finite_dimensional k)` * Upgrade the right rigid structure to a rigid structure (this just needs to be done for `fgModule`). * `fdRep k G` has all finite colimits. * `fdRep k G` is abelian. * `fdRep k G ≌ fgModule (monoid_algebra k G)`. -/ universes u open category_theory open category_theory.limits /-- The category of finite dimensional `k`-linear representations of a monoid `G`. -/ @[derive [large_category, concrete_category, preadditive, has_finite_limits]] abbreviation fdRep (k G : Type u) [field k] [monoid G] := Action (fgModule.{u} k) (Mon.of G) namespace fdRep variables {k G : Type u} [field k] [monoid G] instance : linear k (fdRep k G) := by apply_instance instance : has_coe_to_sort (fdRep k G) (Type u) := concrete_category.has_coe_to_sort _ instance (V : fdRep k G) : add_comm_group V := by { change add_comm_group ((forget₂ (fdRep k G) (fgModule k)).obj V).obj, apply_instance, } instance (V : fdRep k G) : module k V := by { change module k ((forget₂ (fdRep k G) (fgModule k)).obj V).obj, apply_instance, } instance (V : fdRep k G) : finite_dimensional k V := by { change finite_dimensional k ((forget₂ (fdRep k G) (fgModule k)).obj V).obj, apply_instance, } /-- All hom spaces are finite dimensional. -/ instance (V W : fdRep k G) : finite_dimensional k (V ⟶ W) := finite_dimensional.of_injective ((forget₂ (fdRep k G) (fgModule k)).map_linear_map k) (functor.map_injective _) /-- The monoid homomorphism corresponding to the action of `G` onto `V : fdRep k G`. -/ def ρ (V : fdRep k G) : G →* (V →ₗ[k] V) := V.ρ /-- The underlying `linear_equiv` of an isomorphism of representations. -/ def iso_to_linear_equiv {V W : fdRep k G} (i : V ≅ W) : V ≃ₗ[k] W := fgModule.iso_to_linear_equiv ((Action.forget (fgModule k) (Mon.of G)).map_iso i) lemma iso.conj_ρ {V W : fdRep k G} (i : V ≅ W) (g : G) : W.ρ g = (fdRep.iso_to_linear_equiv i).conj (V.ρ g) := begin rw [fdRep.iso_to_linear_equiv, ←fgModule.iso.conj_eq_conj, iso.conj_apply], rw [iso.eq_inv_comp ((Action.forget (fgModule k) (Mon.of G)).map_iso i)], exact (i.hom.comm g).symm, end /-- Lift an unbundled representation to `fdRep`. -/ @[simps ρ] def of {V : Type u} [add_comm_group V] [module k V] [finite_dimensional k V] (ρ : representation k G V) : fdRep k G := ⟨fgModule.of k V, ρ⟩ instance : has_forget₂ (fdRep k G) (Rep k G) := { forget₂ := (forget₂ (fgModule k) (Module k)).map_Action (Mon.of G), } lemma forget₂_ρ (V : fdRep k G) : ((forget₂ (fdRep k G) (Rep k G)).obj V).ρ = V.ρ := by { ext g v, refl } -- Verify that the monoidal structure is available. example : monoidal_category (fdRep k G) := by apply_instance example : monoidal_preadditive (fdRep k G) := by apply_instance example : monoidal_linear k (fdRep k G) := by apply_instance open finite_dimensional open_locale classical -- We need to provide this instance explicitely as otherwise `finrank_hom_simple_simple` gives a -- deterministic timeout. instance : has_kernels (fdRep k G) := by apply_instance -- Verify that Schur's lemma applies out of the box. lemma finrank_hom_simple_simple [is_alg_closed k] (V W : fdRep k G) [simple V] [simple W] : finrank k (V ⟶ W) = if nonempty (V ≅ W) then 1 else 0 := category_theory.finrank_hom_simple_simple k V W /-- The forgetful functor to `Rep k G` preserves hom-sets and their vector space structure -/ def forget₂_hom_linear_equiv (X Y : fdRep k G) : (((forget₂ (fdRep k G) (Rep k G)).obj X) ⟶ ((forget₂ (fdRep k G) (Rep k G)).obj Y)) ≃ₗ[k] (X ⟶ Y) := { to_fun := λ f, ⟨f.hom, f.comm⟩, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl, inv_fun := λ f, ⟨(forget₂ (fgModule k) (Module k)).map f.hom, f.comm⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl } } end fdRep namespace fdRep variables {k G : Type u} [field k] [group G] -- Verify that the right rigid structure is available when the monoid is a group. noncomputable instance : right_rigid_category (fdRep k G) := by { change right_rigid_category (Action (fgModule k) (Group.of G)), apply_instance, } end fdRep namespace fdRep -- The variables in this section are slightly weird, living half in `representation` and half in -- `fdRep`. When we have a better API for general monoidal closed and rigid categories and these -- structures on `fdRep`, we should remove the dependancy of statements about `fdRep` on -- `representation.lin_hom` and `representation.dual`. The isomorphism `dual_tensor_iso_lin_hom` -- below should then just be obtained from general results about rigid categories. open representation variables {k G V : Type u} [field k] [group G] variables [add_comm_group V] [module k V] variables [finite_dimensional k V] variables (ρV : representation k G V) (W : fdRep k G) /-- Auxiliary definition for `fdRep.dual_tensor_iso_lin_hom`. -/ noncomputable def dual_tensor_iso_lin_hom_aux : ((fdRep.of ρV.dual) ⊗ W).V ≅ (fdRep.of (lin_hom ρV W.ρ)).V := (dual_tensor_hom_equiv k V W).to_fgModule_iso /-- When `V` and `W` are finite dimensional representations of a group `G`, the isomorphism `dual_tensor_hom_equiv k V W` of vector spaces induces an isomorphism of representations. -/ noncomputable def dual_tensor_iso_lin_hom : (fdRep.of ρV.dual) ⊗ W ≅ fdRep.of (lin_hom ρV W.ρ) := begin apply Action.mk_iso (dual_tensor_iso_lin_hom_aux ρV W), convert (dual_tensor_hom_comm ρV W.ρ), end @[simp] lemma dual_tensor_iso_lin_hom_hom_hom : (dual_tensor_iso_lin_hom ρV W).hom.hom = dual_tensor_hom k V W := rfl end fdRep
9764d037dd7fbc785153a27a53ecce4539c9589f
f2fbd9ce3f46053c664b74a5294d7d2f584e72d3
/src/Spa.lean
1635e78761f49519889eb64fb9a304748b12a052
[ "Apache-2.0" ]
permissive
jcommelin/lean-perfectoid-spaces
c656ae26a2338ee7a0072dab63baf577f079ca12
d5ed816bcc116fd4cde5ce9aaf03905d00ee391c
refs/heads/master
1,584,610,432,107
1,538,491,594,000
1,538,491,594,000
136,299,168
0
0
null
1,528,274,452,000
1,528,274,452,000
null
UTF-8
Lean
false
false
4,379
lean
import continuous_valuations import Huber_pair universes u₁ u₂ u₃ local attribute [instance] classical.prop_decidable open set Spv -- Wedhorn def 7.23. definition Spa (A : Huber_pair) : set (Spv A) := {v | (v ∈ Cont A) ∧ ∀ r, r ∈ A⁺ → v r ≤ 1} lemma mk_mem_Spa {A : Huber_pair} {v : Valuation A} : mk v ∈ Spa A ↔ (mk v ∈ Cont A) ∧ ∀ r, r ∈ A⁺ → v r ≤ 1 := begin split; intro h; split; try { exact h.left }; intros r hr, { rw ← (v.val).map_one, apply (out_mk r 1).mp, convert h.right r hr, exact valuation.map_one _, }, { rw ← (v.val).map_one at h, convert (out_mk r 1).mpr (h.right r hr), exact (valuation.map_one _).symm } end namespace Spa variable {A : Huber_pair} instance : has_coe (Spa A) (Spv A) := ⟨subtype.val⟩ definition basic_open (r s : A) : set (Spa A) := {v | v r ≤ v s ∧ v s ≠ 0 } lemma mk_mem_basic_open {r s : A} {v : Valuation A} {hv : mk v ∈ Spa A} : (⟨mk v, hv⟩ : Spa A) ∈ basic_open r s ↔ v r ≤ v s ∧ v s ≠ 0 := begin split; intro h; split, { exact (out_mk r s).mp h.left }, { exact Valuation.ne_zero_of_equiv_ne_zero out_mk h.right }, { exact (out_mk r s).mpr h.left }, { exact Valuation.ne_zero_of_equiv_ne_zero (setoid.symm out_mk) h.right } end instance (A : Huber_pair) : topological_space (Spa A) := topological_space.generate_from {U : set (Spa A) | ∃ r s : A, U = basic_open r s} lemma basic_open.is_open (r s : A) : is_open (basic_open r s) := topological_space.generate_open.basic (basic_open r s) ⟨r, ⟨s, rfl⟩⟩ lemma basic_open_eq (s : A) : basic_open s s = {v | v s ≠ 0} := set.ext $ λ v, ⟨λ h, h.right, λ h, ⟨le_refl _, h⟩⟩ -- should only be applied with (HfinT : fintype T) and (Hopen: is_open (span T)) definition rational_open (s : A) (T : set A) : set (Spa A) := {v | (∀ t ∈ T, (v t ≤ v s)) ∧ (v s ≠ 0)} lemma mk_mem_rational_open {s : A} {T : set A} {v : Valuation A} {hv : mk v ∈ Spa A} : (⟨mk v, hv⟩ : Spa A) ∈ rational_open s T ↔ (∀ t ∈ T, (v t ≤ v s)) ∧ (v s ≠ 0) := begin split; intro h; split, { intros t ht, exact (out_mk t s).mp (h.left t ht) }, { exact Valuation.ne_zero_of_equiv_ne_zero out_mk h.right }, { intros t ht, exact (out_mk t s).mpr (h.left t ht) }, { exact Valuation.ne_zero_of_equiv_ne_zero (setoid.symm out_mk) h.right } end definition rational_open_Inter (s : A) (T : set A) : rational_open s T = (set.Inter (λ (t : T), basic_open t s)) ∩ {v | v s ≠ 0} := set.ext $ λ v, ⟨λ ⟨H1, H2⟩, ⟨set.mem_Inter.2 $ λ t, ⟨H1 _ t.property, H2⟩, H2⟩, λ ⟨H1, H2⟩, ⟨λ t ht, (set.mem_Inter.1 H1 ⟨t, ht⟩).1, H2⟩⟩ lemma rational_open_add_s (s : A.R) (T : set A.R) : rational_open s T = rational_open s (insert s T) := set.ext $ λ v, ⟨ λ ⟨H1, H2⟩, ⟨λ t Ht, or.rec_on Ht (λ H, by rw H; exact le_refl _) (H1 t), H2⟩, λ ⟨H1, H2⟩, ⟨λ t Ht, H1 t $ set.mem_insert_of_mem _ Ht,H2⟩⟩ lemma rational_open.is_open (s : A) (T : set A) (HfinT : fintype T) : is_open (rational_open s T) := begin rw rational_open_Inter, apply is_open_inter, swap, rw ← basic_open_eq s, exact basic_open.is_open s s, simpa using @is_open_bInter _ _ _ _ (λ t : T, basic_open t.1 s) (finite_mem_finset finset.univ) (λ t ht, basic_open.is_open t s), end end Spa -- goal now to define the 𝓞_X on *rational subsets* and then to extend. -- to define it on rational subsets it's just a ring completion. -- remember that a rational open is not actually `rational_open s T` in full -- generality -- we also need that T is finite and that T generates an open ideal in A. -- The construction on p73/74 (note typo in first line of p74 -- ideal should be I.D) -- gives A<T/s> (need completion) and A<T/s>^+ (need integral closure). -- Once we have this, we see mid way through p75 that the definition of the presheaf -- on V is proj lim of O_X(U) as U runs through rationals opens in V. This gets -- the projective limit topology and then we have a presheaf (hopefully this is -- straightforward) of complete topological rings (need proj lim of complete is complete) -- We then need the valuations on the stalks (this is direct limit in cat of rings, forget -- the topology). This will be fiddly but not impossible. -- We then have an object in V^pre and I think then everything should follow.
e5623e86ad2e5dae058248c1c8b167146c722237
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/group_theory/congruence.lean
e3e9751a7a47659e8634ceae4ff1e4e0b6f024b3
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
44,345
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.group.pi import algebra.group.prod import data.equiv.mul_add import group_theory.submonoid.operations /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) /-- The equivalence relation underlying an additive congruence relation. -/ add_decl_doc add_con.to_setoid /-- The equivalence relation underlying a multiplicative congruence relation. -/ add_decl_doc con.to_setoid variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_coe {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw [Sup_eq_con_gen, Sup_image], congr' with x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected noncomputable def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : {d // c ≤ d} ≃o (con c.quotient) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy, λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end end section mul_one_class variables {M} [mul_one_class M] [mul_one_class N] [mul_one_class P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance mul_one_class : mul_one_class c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨by rintros ⟨⟨y⟩, hy⟩; exact ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨↑y, hy⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective (ker_lift f) ⟨ker_lift_injective f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end mul_one_class section monoids /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid {M : Type*} [monoid M] (c : con M): monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, .. c.mul_one_class } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {M : Type*} [comm_monoid M] (c : con M) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} end monoids section groups variables {M} [group M] [group N] [group P] (c : con M) /-- Multiplicative congruence relations preserve inversion. -/ @[to_additive "Additive congruence relations preserve negation."] protected lemma inv : ∀ {w x}, c w x → c w⁻¹ x⁻¹ := λ x y h, by simpa using c.symm (c.mul (c.mul (c.refl x⁻¹) h) (c.refl y⁻¹)) /-- The inversion induced on the quotient by a congruence relation on a type with a inversion. -/ @[to_additive "The negation induced on the quotient by an additive congruence relation on a type with an negation."] instance has_inv : has_inv c.quotient := ⟨λ x, quotient.lift_on' x (λ w, ((w⁻¹ : M) : c.quotient)) $ λ x y h, c.eq.2 $ c.inv h⟩ /-- The quotient of a group by a congruence relation is a group. -/ @[to_additive "The quotient of an `add_group` by an additive congruence relation is an `add_group`."] instance group : group c.quotient := { inv := λ x, x⁻¹, mul_left_inv := λ x, show x⁻¹ * x = 1, from quotient.induction_on' x $ λ _, congr_arg coe $ mul_left_inv _, .. con.monoid c} end groups end con
dff25970201b670979c5470a74b139484f2563a9
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/meta/smt/ematch.lean
1c4f6eaa80cb5ef9de21f7a7ef081ab020897e1e
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,233
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.congruence_closure import init.meta.attribute init.meta.simp_tactic open tactic /- Heuristic instantiation lemma -/ meta constant hinst_lemma : Type meta constant hinst_lemmas : Type /- (mk_core m e as_simp), m is used to decide which definitions will be unfolded in patterns. If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion as a pattern. -/ meta constant hinst_lemma.mk_core : transparency → expr → bool → tactic hinst_lemma meta constant hinst_lemma.mk_from_decl_core : transparency → name → bool → tactic hinst_lemma meta constant hinst_lemma.pp : hinst_lemma → tactic format meta constant hinst_lemma.id : hinst_lemma → name meta instance : has_to_tactic_format hinst_lemma := ⟨hinst_lemma.pp⟩ meta def hinst_lemma.mk (h : expr) : tactic hinst_lemma := hinst_lemma.mk_core reducible h ff meta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma := hinst_lemma.mk_from_decl_core reducible h ff meta constant hinst_lemmas.mk : hinst_lemmas meta constant hinst_lemmas.add : hinst_lemmas → hinst_lemma → hinst_lemmas meta constant hinst_lemmas.fold {α : Type} : hinst_lemmas → α → (hinst_lemma → α → α) → α meta constant hinst_lemmas.merge : hinst_lemmas → hinst_lemmas → hinst_lemmas meta def mk_hinst_singleton : hinst_lemma → hinst_lemmas := hinst_lemmas.add hinst_lemmas.mk meta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format := let tac := s^.fold (return format.nil) (λ h tac, do hpp ← h^.pp, r ← tac, if r^.is_nil then return hpp else return (r ++ to_fmt "," ++ format.line ++ hpp)) in do r ← tac, return $ format.cbrace (format.group r) meta instance : has_to_tactic_format hinst_lemmas := ⟨hinst_lemmas.pp⟩ open tactic private meta def add_lemma (m : transparency) (as_simp : bool) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas := do h ← hinst_lemma.mk_from_decl_core m h as_simp, return $ hs^.add h meta def to_hinst_lemmas_core (m : transparency) : bool → list name → hinst_lemmas → tactic hinst_lemmas | as_simp [] hs := return hs | as_simp (n::ns) hs := let add n := add_lemma m as_simp n hs >>= to_hinst_lemmas_core as_simp ns in do /- First check if n is the name of a function with equational lemmas associated with it -/ eqns ← tactic.get_eqn_lemmas_for tt n, match eqns with | [] := do /- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/ add n | _ := do p ← is_prop_decl n, if p then add n /- n is a proposition -/ else do /- Add equational lemmas to resulting hinst_lemmas -/ new_hs ← to_hinst_lemmas_core tt eqns hs, to_hinst_lemmas_core as_simp ns new_hs end meta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command := do t ← to_expr ``(caching_user_attribute hinst_lemmas), b ← if as_simp then to_expr ``(tt) else to_expr ``(ff), v ← to_expr ``({name := %%(quote attr_name), descr := "hinst_lemma attribute", mk_cache := λ ns, to_hinst_lemmas_core reducible %%b ns hinst_lemmas.mk, dependencies := [`reducibility] } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name → command | [] := skip | (n::ns) := (mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns) <|> (do type ← infer_type (expr.const n []), expected ← to_expr ``(caching_user_attribute hinst_lemmas), (is_def_eq type expected <|> fail ("failed to create hinst_lemma attribute '" ++ n^.to_string ++ "', declaration already exists and has different type.")), mk_hinst_lemma_attrs_core ns) meta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name → hinst_lemmas → tactic hinst_lemmas | [] hs := return hs | (attr::attrs) hs := do ns ← attribute.get_instances attr, new_hs ← to_hinst_lemmas_core m as_simp ns hs, merge_hinst_lemma_attrs attrs new_hs /-- Create a new "cached" attribute (attr_name : caching_user_attribute hinst_lemmas). It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with attr_name, attrs_name, and simp_attr_names. For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern. -/ meta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command := do mk_hinst_lemma_attrs_core ff attr_names, mk_hinst_lemma_attrs_core tt simp_attr_names, t ← to_expr ``(caching_user_attribute hinst_lemmas), l1 ← return $ quote attr_names, l2 ← return $ quote simp_attr_names, v ← to_expr ``({name := %%(quote attr_name), descr := "hinst_lemma attribute set", mk_cache := λ ns, let aux1 : list name := %%l1, aux2 : list name := %%l2 in do { hs₁ ← to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk, hs₂ ← merge_hinst_lemma_attrs reducible ff aux1 hs₁, merge_hinst_lemma_attrs reducible tt aux2 hs₂}, dependencies := [`reducibility] ++ %%l1 ++ %%l2 } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas := do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute hinst_lemmas) cnst, caching_user_attribute.get_cache attr structure ematch_config := (max_instances : nat := 10000) (max_generation : nat := 10) /- Ematching -/ meta constant ematch_state : Type meta constant ematch_state.mk : ematch_config → ematch_state meta constant ematch_state.internalize : ematch_state → expr → tactic ematch_state namespace tactic meta constant ematch_core : transparency → cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) meta constant ematch_all_core : transparency → cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) meta def ematch : cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_core reducible meta def ematch_all : cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_all_core reducible end tactic
b670e4c481089273eb92d8b317ebf9302cad91be
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/normed_snake_dual.lean
0c8a17d36fb00c02576bfdeebdd0ca05f9de536c
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,790
lean
import system_of_complexes.basic /-! # The normed snake dual lemma: weak and non-weak This file proves the weak normed snake dual lemma and the normed snake dual lemma: they are the statements `weak_normed_snake_dual` and `normed_snake_dual`, respectively. The principal definitions of the concepts in this file appear in Section 4 of the blueprint. The two main results prove `is_(weak_)bounded_exact` for certain `system_of_complexes`. The Lean-definitions of these concepts appears in `system_of_complexes.basic`. Intuitively, the two predicates assert a version of exactness for a complex whose overall shape is an inequality of the form ```lean ∥res ? - (M.d ??) ?∥ ≤ const * ∥(M.d ?? ?∥ + ε. ``` (Recall that `res` is a restriction among certain complexes, `M.d` stands for a differential, `const` is a constant; the error `ε` is a non-negative real number. For the weak version, we quantify over all `0 < ε ∈ ℝ`. For the non-weak version, we use `ε = 0`.) More in detail, at the heart of the computation, is a proof of an inequality of the form ```lean ∥res m - (M.d (i - 1) i) y∥ ≤ K * (1 + K' * r₁ * r₂) * ∥(M.d i (i + 1)) m∥ + ε. ``` In the weak normed snake dual lemma, for any choice of positive `0 < ε`, we should be able to fix the parameters so that the inequality above is satisfied. In the normed snake dual lemma, we want the inequality above with `ε = 0`. As you will see, the bulk of the proof of the normed snake dual lemma recycles the proof of the weak version. The proof involves several estimations: we broke these proofs into smaller partial inequalities, for three reasons. First, it streamlines the formalization. Second, it helps Lean processing the statements, reducing processing times. Third, it allows us to us a large part of the argument for both `weak_normed_snake_dual` and `normed_snake_dual`. # Remark While following the proof, keep an eye out for how the factor `ρ = 1 + K' * r₁ * r₂` forms itself. Once the factor `ρ` is formed, we can almost treat it as a new strictly positive variable. -/ universe variables u noncomputable theory open_locale nnreal open category_theory opposite normed_group_hom system_of_complexes variables {M N P : system_of_complexes.{u}} {f : M ⟶ N} {g : N ⟶ P} /- I (DT) extracted this lemma to speed up the proof of `weak_normed_snake_dual`. -/ lemma ε₁_le_ε {ε ε₁ : ℝ} (hε : 0 ≤ ε) (mK : ℝ≥0) (hε₁ : ε₁ = ε / 2 * (1 + mK)⁻¹) : ε₁ ≤ ε := by { rw [hε₁, div_eq_mul_inv, mul_assoc, ← mul_inv'], exact mul_le_of_le_one_right hε (inv_le_one $ nnreal.coe_le_coe.mpr $ one_le_mul one_le_two $ le_add_of_nonneg_right mK.2) } /-! First, we break off the main term `∥res m - (M.d i' i) m₁∥` into a sum of two expressions: * `∥(res (f m) : N c i) - N.d i' i (res n₁)∥`, and * `∥(N.d i' i ((N.d i'' i') n₂ + nnew₁) : N c i)∥`. -/ lemma norm_sub_le_split {k' c c₁ : ℝ≥0} {i i' i'' : ℕ} [hk' : fact (1 ≤ k')] [fc : fact (c ≤ c₁)] (hfnorm : ∀ (c : ℝ≥0) (i : ℕ) (x : (M c i)), ∥(f.apply) x∥ = ∥x∥) {n₁ : N (k' * c) i'} {n₂ : N c i''} {nnew₁ : N c i'} {m₁ : M c i'} {m : (M c₁ i)} (hm₁ : f m₁ = res n₁ - ((N.d i'' i') n₂) - nnew₁) : ∥res m - (M.d i' i) m₁∥ ≤ ∥(res (f m) : N c i) - N.d i' i (res n₁)∥ + ∥(N.d i' i ((N.d i'' i') n₂ + nnew₁) : N c i)∥ := calc ∥res m - (M.d i' i) m₁∥ = ∥f (res m - (M.d i' i) m₁)∥ : (hfnorm _ _ _).symm ... = ∥res (f m) - (N.d i' i (res n₁) - N.d i' i ((N.d i'' i') n₂ + nnew₁))∥ : by rw [hom_apply, normed_group_hom.map_sub, ←hom_apply, ←hom_apply, ←res_apply, ←d_apply, hm₁, sub_sub, normed_group_hom.map_sub] ... = ∥(res (f m) - N.d i' i (res n₁)) + N.d i' i ((N.d i'' i') n₂ + nnew₁)∥ : by rw [sub_eq_add_neg, neg_sub, sub_eq_neg_add, ← add_assoc, ← sub_eq_add_neg] ... ≤ ∥res (f m) - N.d i' i (res n₁)∥ + ∥N.d i' i ((N.d i'' i') n₂ + nnew₁)∥ : norm_add_le _ _ /-! We then massage the left-hand side. The proof of this lemma is deceptively simple, since there is a lot of typeclass work happening in the background. In particular, the `c` in the sea of underscores of the second line is crucial for the *previous* line to compile. (The hypothesis `(hN_adm : N.admissible)` is only used via `(hN_adm.res_norm_noninc _ c _ _ _)`, producing the inequality `(dis : ∥(res (res (f m) - (N.d i' i) n₁) : N c i)∥ ≤ ∥res (f m) - (N.d i' i) n₁∥)`.) -/ lemma norm_sub_le_mul_norm_add_lhs {k' K c c₁ : ℝ≥0} {ε₁ : ℝ} {i i' : ℕ} [hk' : fact (1 ≤ k')] [fc₁ : fact (k' * c ≤ c₁)] [fc : fact (c ≤ c₁)] {n₁ : N (k' * c) i'} {m : (M c₁ i)} (hN_adm : N.admissible) (hn₁ : ∥res (f m) - (N.d i' i) n₁∥ ≤ K * ∥(N.d i (i + 1)) (f m)∥ + ε₁) : ∥(res (f m) : N c i) - N.d i' i (res n₁)∥ ≤ K * ∥(N.d i (i + 1)) (f m)∥ + ε₁ := calc ∥(res (f m) : N c i) - N.d i' i (res n₁)∥ = ∥res (res (f m) - (N.d i' i) n₁)∥ : by rw [normed_group_hom.map_sub, d_res, ← res_res] ... ≤ K * ∥(N.d i (i + 1)) (f m)∥ + ε₁ : trans (hN_adm.res_norm_noninc _ c _ _ _) hn₁ /-! And we also massage the right-hand side. Here, the factor `K' * r₁ * r₂` appears. (The hypothesis `(hN_adm : N.admissible)` is only used via `(hN_adm.d_norm_noninc _ _ i' i nnew₁)`, producing the inequality `(dis : ∥(N.d i' i) nnew₁∥ ≤ ∥nnew₁∥)`.) -/ lemma norm_sub_le_mul_norm_add_rhs {k' K K' r₁ r₂ c c₁ : ℝ≥0} {ε₁ ε₂ : ℝ} {i i' i'' : ℕ} (hii' : i' + 1 = i) [hk' : fact (1 ≤ k')] [fc₁ : fact (k' * c ≤ c₁)] (hgnorm : ∀ (c : ℝ≥0) (i : ℕ) (x : (N c i)), ∥g x∥ ≤ ↑r₁ * ∥x∥) {n₁ : N (k' * c) i'} {n₂ : N c i''} {nnew₁ : N c i'} {m : (M c₁ i)} (hN_adm : N.admissible) (hn₁ : ∥res (f m) - (N.d i' i) n₁∥ ≤ K * ∥(N.d i (i + 1)) (f m)∥ + ε₁) (hp₂ : ∥res (g n₁) - (P.d i'' i') (g n₂)∥ ≤ K' * ∥(P.d i' (i' + 1)) (g n₁)∥ + ε₂) (hnormnnew₁ : ∥nnew₁∥ ≤ r₂ * ∥g (res n₁ - ((N.d i'' i') n₂))∥) (hfm : ∥g ((N.d i' i) n₁)∥ = ∥g (res (f m) - (N.d i' i) n₁)∥) : ∥(N.d i' i ((N.d i'' i') n₂ + nnew₁) : N c i)∥ ≤ K * K' * r₁ * r₂ * ∥(N.d i (i+1)) (f m)∥ + K' * r₁ * r₂ * ε₁ + r₂ * ε₂ := calc ∥(N.d i' i ((N.d i'' i') n₂ + nnew₁) : N c i)∥ = ∥N.d i' i nnew₁∥ : by simp only [map_add, zero_add, d_d] ... ≤ r₂ * ∥g (res n₁ - (N.d i'' i') n₂)∥ : trans (hN_adm.d_norm_noninc _ _ i' i nnew₁) hnormnnew₁ ... = r₂ * ∥res (g n₁) - P.d i'' i' (g n₂)∥ : by rw [hom_apply, normed_group_hom.map_sub, ←hom_apply, ←hom_apply, ←res_apply _ _ g, ←d_apply] ... ≤ r₂ * (K' * ∥P.d i' (i'+1) (g n₁)∥ + ε₂) : mul_le_mul_of_nonneg_left hp₂ r₂.coe_nonneg ... = r₂ * (K' * ∥g (res (f m) - N.d i' i n₁)∥ + ε₂) : by rw [d_apply _ _ g _, hii', hfm] ... ≤ r₂ * (K' * (r₁ * ∥res (f m) - N.d i' i n₁∥) + ε₂) : mul_le_mul_of_nonneg_left (add_le_add_right (mul_le_mul_of_nonneg_left (hgnorm _ _ _) K'.coe_nonneg) _) $ r₂.coe_nonneg ... = r₂ * (K' * r₁ * ∥res (f m) - N.d i' i n₁∥ + ε₂) : by rw mul_assoc ... ≤ r₂ * (K' * r₁ * (K * ∥(N.d i (i+1)) (f m)∥ + ε₁) + ε₂) : mul_le_mul_of_nonneg_left (add_le_add_right (mul_le_mul_of_nonneg_left hn₁ $ mul_nonneg K'.coe_nonneg r₁.coe_nonneg) _) r₂.coe_nonneg ... = _ : by ring /-! We collect the inequalities obtained so far: * use `norm_sub_le_split` to split the norm into a sum of two terme; * apply `norm_sub_le_mul_norm_add_lhs` to the left-hand-side; * apply `norm_sub_le_mul_norm_add_rhs` to the right-hand-side. The rest is simple manipulations of real numbers. -/ lemma norm_sub_le_mul_norm_add {k' K K' r₁ r₂ c c₁ : ℝ≥0} {ε ε₁ ε₂ : ℝ} {i i' i'' : ℕ} (hii' : i' + 1 = i) [hk' : fact (1 ≤ k')] [fc₁ : fact (k' * c ≤ c₁)] [fc : fact (c ≤ c₁)] (hN_adm : N.admissible) (hgnorm : ∀ (c : ℝ≥0) (i : ℕ) (x : (N c i)), ∥g x∥ ≤ ↑r₁ * ∥x∥) (hfnorm : ∀ (c : ℝ≥0) (i : ℕ) (x : (M c i)), ∥(f.apply) x∥ = ∥x∥) {n₁ : N (k' * c) i'} {n₂ : N c i''} {nnew₁ : N c i'} {m₁ : M c i'} {m : (M c₁ i)} (hmulε₁ : ε₁ * (1 + K' * r₁ * r₂) = ε / 2) (hle : (r₂ : ℝ) * ε₂ ≤ ε / 2) (hn₁ : ∥res (f m) - (N.d i' i) n₁∥ ≤ K * ∥(N.d i (i + 1)) (f m)∥ + ε₁) (hp₂ : ∥res (g n₁) - (P.d i'' i') (g n₂)∥ ≤ K' * ∥(P.d i' (i' + 1)) (g n₁)∥ + ε₂) (hnormnnew₁ : ∥nnew₁∥ ≤ r₂ * ∥g (res n₁ - ((N.d i'' i') n₂))∥) (hm₁ : f m₁ = res n₁ - ((N.d i'' i') n₂) - nnew₁) (hfm : ∥g ((N.d i' i) n₁)∥ = ∥g (res (f m) - (N.d i' i) n₁)∥) : ∥res m - (M.d i' i) m₁∥ ≤ (K + r₁ * r₂ * K * K') * ∥(M.d i (i + 1)) m∥ + ε := calc ∥res m - (M.d i' i) m₁∥ ≤ ∥res (f m) - N.d i' i (res n₁)∥ + ∥N.d i' i ((N.d i'' i') n₂ + nnew₁)∥ : norm_sub_le_split hfnorm hm₁ ... ≤ (K * ∥(N.d i (i + 1)) (f m)∥ + ε₁) + (K * K' * r₁ * r₂ * ∥(N.d i (i+1)) (f m)∥ + K' * r₁ * r₂ * ε₁ + r₂ * ε₂) : add_le_add (norm_sub_le_mul_norm_add_lhs hN_adm hn₁) (norm_sub_le_mul_norm_add_rhs hii' hgnorm hN_adm hn₁ hp₂ hnormnnew₁ hfm) ... = (K + r₁ * r₂ * K * K') * ∥N.d i (i+1) (f m)∥ + ε₁ * (1 + K' * r₁ * r₂) + r₂ * ε₂ : by ring ... = (K + r₁ * r₂ * K * K') * ∥N.d i (i+1) (f m)∥ + ε / 2 + r₂ * ε₂ : congr_arg (λ e, (↑K + ↑r₁ * ↑r₂ * ↑K * ↑K') * ∥(N.d i (i + 1)) (f m)∥ + e + ↑r₂ * ε₂) hmulε₁ ... ≤ (K + r₁ * r₂ * K * K') * ∥N.d i (i+1) (f m)∥ + ε / 2 + ε / 2 : add_le_add_left hle _ ... = (K + r₁ * r₂ * K * K') * ∥(M.d i (i+1)) m∥ + ε : by rw [add_assoc, add_halves', d_apply, hom_apply, hfnorm] /-! We shall apply this lemma with `ρ = K + r₁ * r₂ * K * K' = K * (1 + K' * r₁ * r₂)`. -/ lemma exists_norm_sub_le_mul_add {k k' c ρ : ℝ≥0} {i : ℕ} [hk : fact (1 ≤ k)] [hk' : fact (1 ≤ k')] (hM_adm : M.admissible) (ex_le : (∀ (m : (M (k * (k' * c)) i)) (ε : ℝ), 0 < ε → (∃ (i₀ : ℕ) (hi₀ : i₀ = i - 1) (y : (M c i₀)), ∥res m - (M.d i₀ i) y∥ ≤ ↑ρ * ∥(M.d i (i + 1)) m∥ + ε))) {m₁ : (M (k * k' * c) i)} {ε : ℝ} (hε : 0 < ε) : ∃ (i₀ j : ℕ) (hi₀ : i₀ = i - 1) (hj : i + 1 = j) (y : (M c i₀)), ∥res m₁ - (M.d i₀ i) y∥ ≤ ↑ρ * ∥(M.d i j) m₁∥ + ε := begin haveI : fact (k * (k' * c) ≤ k * k' * c) := { out := (mul_assoc _ _ _).symm.le }, rcases ex_le (res m₁) ε hε with ⟨i₀, rfl, y, hy⟩, rw [res_res, d_res] at hy, refine ⟨i - 1, _, rfl, rfl, _⟩, refine ⟨y, hy.trans (add_le_add_right (mul_le_mul_of_nonneg_left _ ρ.2) ε)⟩, exact hM_adm.res_norm_noninc _ _ _ _ _, end /-! This argument proves the main inequality in the case where the indices are `0` or `1`. -/ lemma norm_sub_le_mul_mul_norm_add {M N : system_of_complexes} {f : M ⟶ N} {k k' K c : ℝ≥0} (mK : ℝ≥0) {ε ε₁ : ℝ} {m : M (k * (k' * c)) 0} {n₁ : N (k' * c) 0} {m₁ : M c 0} (ee1 : ε₁ ≤ ε) [hk : fact (1 ≤ k)] [hk' : fact (1 ≤ k')] (hfnorm : ∀ (c : ℝ≥0) (i : ℕ) (x : (M c i)), ∥(f.apply) x∥ = ∥x∥) (inadm : ∥((res (res m : (M (k' * c) 0))) : (M c 0))∥ ≤ ∥(res m : (M (k' * c) 0))∥ ) (hn₁ : ∥res (f m) - (N.d 0 0) n₁∥ ≤ ↑K * ∥(N.d 0 (0 + 1)) (f m)∥ + ε₁) : ∥res m - (M.d 0 0) m₁∥ ≤ (K * (1 + mK)) * ∥(M.d 0 (0 + 1)) m∥ + ε := begin simp only [d_self_apply, sub_zero, nnreal.coe_add, nnreal.coe_mul] at hn₁ ⊢, rw [res_apply, hom_apply f (res m), hfnorm] at hn₁, have new : fact (c ≤ k' * c) := { out := le_mul_of_one_le_left c.2 hk'.out }, rw ←res_res _ _ _ new, refine le_trans inadm (le_trans hn₁ _), rw [d_apply, hom_apply f _, hfnorm], refine add_le_add _ ee1, rw mul_assoc, refine (mul_le_mul_of_nonneg_left _ K.2), exact le_mul_of_one_le_left (norm_nonneg _) (le_add_of_nonneg_right mK.2), end /-! Note that `ε = 0` is allowed. Indeed, the weak normed snake dual lemma uses `0 ≤ ε`, while the normed snake dual lemma uses `ε = 0`. -/ lemma exist_norm_sub_le_mul_norm_add {k k' K K' r₁ r₂ c₀ c : ℝ≥0} {a i : ℕ} {ε : ℝ} (hε : 0 ≤ ε) [hk : fact (1 ≤ k)] [hk' : fact (1 ≤ k')] (hN_adm : N.admissible) (hgnrm : ∀ (c : ℝ≥0) (i : ℕ) (x : (N c i)), ∥g x∥ ≤ r₁ * ∥x∥) (Hg : ∀ (c : ℝ≥0) [_inst_1 : fact (c₀ ≤ c)] (i : ℕ), i ≤ a + 1 + 1 → ∀ (y : (P c i)), ∃ (x : (N c i)), g x = y ∧ ∥x∥ ≤ r₂ * ∥y∥) (hg : ∀ (c : ℝ≥0) (i : ℕ), (range f.apply : add_subgroup (N c i)) = ker g.apply) (hf : ∀ (c : ℝ≥0) (i : ℕ), (isometry (f.apply : M c i ⟶ N c i) : _)) (hc : fact (c₀ ≤ c)) (hi : i ≤ a) {m : M (k * (k' * c)) i} {n₁ : N (k' * c) (i - 1)} (hn₁ : ∥res (f m) - (N.d (i - 1) i) n₁∥ ≤ K * ∥(N.d i (i + 1)) (f m)∥ + ε / 2 * (1 + K' * r₁ * r₂)⁻¹) (Hi' : i - 1 ≤ a + 1) (p₂ : P c (i - 1 - 1)) (hp₂ : ∥res (g n₁) - (P.d (i - 1 - 1) (i - 1)) p₂∥ ≤ K' * ∥(P.d (i - 1) (i - 1 + 1)) (g n₁)∥ + ite (r₂ = 0) 1 (ε / 2 * (r₂)⁻¹)) : ∃ (i₀ : ℕ) (hi₀ : i₀ = i - 1) (y : (M c i₀)), ∥res m - (M.d i₀ i) y∥ ≤ (K + r₁ * r₂ * K * K') * ∥(M.d i (i + 1)) m∥ + ε := begin obtain ⟨n₂, rfl, hnormn₂⟩ := Hg c (i - 1 - 1) (trans (nat.pred_le _) (trans Hi' (nat.le_succ _))) p₂, let n₁' := N.d (i - 1 - 1) (i - 1) n₂, obtain ⟨nnew₁, hnnew₁, hnrmnew₁⟩ := Hg c (i - 1) (trans Hi' a.succ.le_succ) (g (res n₁ - n₁')), have hker : (res n₁ - n₁') - nnew₁ ∈ g.apply.ker, { rw [mem_ker, normed_group_hom.map_sub, sub_eq_zero, ←hom_apply, ←hom_apply, hnnew₁] }, rw ←hg at hker, obtain ⟨m₁, hm₁ : f m₁ = res n₁ - n₁' - nnew₁⟩ := (mem_range _ _).1 hker, refine ⟨i - 1, rfl, m₁, _⟩, have hfnrm : ∀ c i (x : M c i), ∥f.apply x∥ = ∥x∥ := λ c i x, (isometry_iff_norm _).1 (hf c i) x, by_cases hizero : i = 0, { subst hizero, convert norm_sub_le_mul_mul_norm_add (K' * r₁ * r₂) _ hfnrm _ hn₁, { norm_cast, ring }, { exact ε₁_le_ε hε (K' * r₁ * r₂) rfl }, { exact (admissible_of_isometry hN_adm hf).res_norm_noninc _ _ _ _ _ } }, { refine norm_sub_le_mul_norm_add _ hN_adm hgnrm hfnrm _ _ hn₁ hp₂ hnrmnew₁ hm₁ _, { exact nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hizero) }, { rw inv_mul_cancel_right', exact ne_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (zero_le (K' * r₁ * r₂))) }, { by_cases H : r₂ = 0, { simp only [H, nnreal.coe_zero, if_true, zero_mul, (div_nonneg hε zero_le_two)] }, { simp only [H, nnreal.coe_eq_zero, if_false, mul_comm, mul_inv_cancel_left' (nnreal.coe_ne_zero.mpr H)] } }, { have : f (res m : M (k' * c) i) ∈ f.apply.range, { rw mem_range, exact ⟨res m, rfl⟩ }, rw [hg, mem_ker] at this, rw [hom_apply g (res (f m) - (N.d (i - 1) i) n₁), res_apply, normed_group_hom.map_sub, this, zero_sub, norm_neg, ←hom_apply] } } end /-! We apply this lemma with `ρ = K + r₁ * r₂ * K * K'`. -/ lemma exists_norm_sub_le_mul {M : system_of_complexes} {k k' c ρ : ℝ≥0} {i : ℕ} [hk : fact (1 ≤ k)] [hk' : fact (1 ≤ k')] (hM_adm : M.admissible) (ex_le : (∀ (m : (M (k * (k' * c)) i)), (∃ (i₀ : ℕ) (hi₀ : i₀ = i - 1) (y : (M c i₀)), ∥res m - (M.d i₀ i) y∥ ≤ ↑ρ * ∥(M.d i (i + 1)) m∥))) (m₁ : (M (k * k' * c) i)) : ∃ (i₀ j : ℕ) (hi₀ : i₀ = i - 1) (hj : i + 1 = j) (y : (M c i₀)), ∥res m₁ - (M.d i₀ i) y∥ ≤ ↑ρ * ∥(M.d i j) m₁∥ := begin haveI : fact (k * (k' * c) ≤ k * k' * c) := { out := (mul_assoc _ _ _).symm.le }, rcases ex_le (res m₁) with ⟨i₀, rfl, y, hy⟩, rw [res_res, d_res] at hy, refine ⟨i - 1, _, rfl, rfl, _⟩, refine ⟨y, hy.trans (mul_le_mul_of_nonneg_left _ ρ.2)⟩, exact hM_adm.res_norm_noninc _ _ _ _ _, end variables (M N P f g) /-! Finally, we state and prove the weak normed snake dual lemma. -/ lemma weak_normed_snake_dual (k k' K K' r₁ r₂ : ℝ≥0) [hk : fact (1 ≤ k)] [hk' : fact (1 ≤ k')] {a : ℕ} {c₀ : ℝ≥0} (hN : N.is_weak_bounded_exact k K (a + 1) c₀) (hP : P.is_weak_bounded_exact k' K' (a + 1) c₀) (hN_adm : N.admissible) (hgnrm : ∀ c i (x : N c i), ∥g x∥ ≤ r₁ * ∥x∥) (Hg : ∀ (c : ℝ≥0) [fact (c₀ ≤ c)] (i : ℕ) (hi : i ≤ a + 1 + 1) (y : P c i), ∃ (x : N c i), g x = y ∧ ∥x∥ ≤ r₂ * ∥y∥) (hg : ∀ c i, (f.apply : M c i ⟶ N c i).range = g.apply.ker) (hf : ∀ c i, @isometry (M c i) (N c i) _ _ f.apply) : M.is_weak_bounded_exact (k * k') (K + r₁ * r₂ * K * K') a c₀ := begin introsI c hc i hi, apply exists_norm_sub_le_mul_add (admissible_of_isometry hN_adm hf), intros m ε hε, have hε₁ : 0 < ε / 2 * (1 + K' * r₁ * r₂)⁻¹ := mul_pos (half_pos hε) (inv_pos.2 $ add_pos_of_pos_of_nonneg zero_lt_one ((K' * r₁ * r₂).coe_nonneg)), obtain ⟨_, _, rfl, rfl, n₁, hn₁⟩ := hN _ ⟨hc.out.trans $ le_mul_of_one_le_left' hk'.out⟩ _ (trans hi a.le_succ) (f m) _ hε₁, have Hi' : i - 1 ≤ a + 1 := trans i.pred_le (trans hi a.le_succ), obtain ⟨_, _, rfl, rfl, p₂, hp₂⟩ := hP _ hc _ Hi' (g n₁) (if (r₂ : ℝ) = 0 then 1 else (ε / 2) * r₂⁻¹) _, { simp_rw [nnreal.coe_eq_zero r₂] at hp₂, apply exist_norm_sub_le_mul_norm_add hε.le hN_adm hgnrm Hg hg hf hc hi hn₁ Hi' p₂, convert hp₂, }, { by_cases H : r₂ = 0, { simp only [H, zero_lt_one, if_true, eq_self_iff_true, nnreal.coe_eq_zero] }, { simp only [H, nnreal.coe_eq_zero, if_false], exact mul_pos (half_pos hε) (inv_pos.2 (nnreal.coe_pos.2 (zero_lt_iff.2 H))) } } end /-! And also the normed snake dual lemma. -/ lemma normed_snake_dual {k k' K K' r₁ r₂ : ℝ≥0} [hk : fact (1 ≤ k)] [hk' : fact (1 ≤ k')] {a : ℕ} {c₀ : ℝ≥0} (hN : N.is_bounded_exact k K (a + 1) c₀) (hP : P.is_bounded_exact k' K' (a + 1) c₀) (hN_adm : N.admissible) (hgnorm : ∀ c i (x : N c i), ∥g x∥ ≤ r₁ * ∥x∥) (Hg : ∀ (c : ℝ≥0) [fact (c₀ ≤ c)] (i : ℕ) (hi : i ≤ a + 1 + 1) (y : P c i), ∃ (x : N c i), g x = y ∧ ∥x∥ ≤ r₂ * ∥y∥) (hg : ∀ c i, (f.apply : M c i ⟶ N c i).range = g.apply.ker) (hf : ∀ c i, @isometry (M c i) (N c i) _ _ f.apply) : M.is_bounded_exact (k * k') (K + r₁ * r₂ * K * K') a c₀ := begin introsI c hc i hi, refine exists_norm_sub_le_mul (admissible_of_isometry hN_adm hf) _, intro m, obtain ⟨_, _, rfl, rfl, n₁, hn₁⟩ := hN _ ⟨hc.out.trans $ le_mul_of_one_le_left' hk'.out⟩ _ (trans hi a.le_succ) (f m), have Hi' : (i - 1) ≤ a + 1 := trans i.pred_le (trans hi a.le_succ), obtain ⟨_, _, rfl, rfl, p₂, hp₂⟩ := hP _ hc _ Hi' (g n₁), rw ← add_zero (_ * ∥_∥) at ⊢, have hn₁₁ : ∥res (f m) - (N.d (i - 1) i) n₁∥ ≤ K * ∥(N.d i (i + 1)) (f m)∥ + 0 / 2 * (1 + K' * r₁ * r₂)⁻¹, rwa [zero_div, zero_mul, add_zero], obtain F := exist_norm_sub_le_mul_norm_add rfl.le hN_adm hgnorm Hg hg hf hc hi hn₁₁ Hi' p₂, by_cases hr : r₂ = 0, { subst hr, simp at ⊢ F, exact F (trans hp₂ (le_add_of_nonneg_right zero_le_one)) }, { exact F (by { convert hp₂, simp [hr] } ) } end
f5bac1f5614c5875a8e530a420496ccf014ea250
c6da0300d417abe3464e750ab51a63502b93acfa
/src/struct_tact/break_tactics.lean
1ca48b5414f13e2fc913a8e6b3ec2a61e1a4395e
[ "Apache-2.0" ]
permissive
uwplse/struct_tact
55bc1d260fac498cff83a4d71461041f8ed74bd6
22188ea2e97705d1185f75dde24e6bab88054ab0
refs/heads/master
1,630,670,592,496
1,515,453,299,000
1,515,453,299,000
104,603,771
0
0
null
null
null
null
UTF-8
Lean
false
false
7,377
lean
import .traversals import .debugging open tactic /- We match on names which are generated by the internal match-wrapper machinery. -/ meta def is_match_wrapper (n : name): bool := match n.components.ilast with | name.mk_string s _ := s.to_list.take 7 = "_match_".to_list | _ := bool.ff end /- Select the scrutinee from a list of arguments to the match expression, current heuristic is simple and non-robust. -/ meta def find_scrutinee : list expr → tactic expr := fun xs, return (xs.ilast) meta def rw_one (hyp_name : option name) (eq_n : name) : tactic unit := match hyp_name with | none := do eq ← get_local eq_n, rewrite_target eq | some hn := do eq ← get_local eq_n, H ← get_local hn, rewrite_hyp eq H, return () end /- Removes reflexive equalities (i.e a = a). -/ meta def clear_refl_eqs : tactic unit := do ls ← local_context, for_m ls (λ l, do ty ← infer_type l, -- is there a better way to write this? (do (a, b) ← match_eq ty, if a = b then clear l else return ()) <|> return ()), return () meta def intros_and_subst (hyp_name : option name) : tactic unit := do tgt ← target, if tgt.is_pi then do n ← get_unused_name `a, H ← intro n, -- trace H, ty ← infer_type H, try (rw_one hyp_name n), intros_and_subst else return () meta def split_app (e : expr) : tactic (expr × list expr) := match e with | (expr.app _ _) := let head := expr.get_app_fn e, args := expr.get_app_args e in return (head, args) | _ := tactic.fail "expected an application found ..." end meta def find_match (head : expr) (args : list expr) : tactic (name × expr) := if is_match_wrapper head.const_name then do scrut ← find_scrutinee args, return $ (head.const_name, scrut) else tactic.fail "head is not match" -- todo improve me meta def prune_case : tactic unit := try (contradiction <|> cc) meta def destruct_subst_dsimp (hyp_name : option name) (match_name : name) (scrut : expr) := seq (destruct scrut) $ seq (intros_and_subst hyp_name) $ seq (prune_case) (match hyp_name with | none := dsimp_target none [match_name, `id_rhs] | some n := do H ← get_local n, dsimp_hyp H none [match_name, `id_rhs], return () end) meta def dsimp_at (hyp_name : option name) : tactic unit := match hyp_name with | none := dsimp_target | some hyp := get_local hyp >>= dsimp_hyp end meta def cases_ (e : expr) : tactic unit := cases e >> return () meta def case_split_rec (hyp_name : option name) (rec : name) (args : list expr) : tactic unit := do scrutinee ← find_scrutinee args, seq (cases_ scrutinee) (seq (try $ dsimp_at hyp_name) prune_case) meta def case_split_cases_on (hyp_name : option name) (rec : name) (args : list expr) : tactic unit := do let scrutinee := list.head args, seq (cases_ scrutinee) (seq (try $ dsimp_at hyp_name) prune_case) meta def case_split_exposed_recursor (hyp_name : option name) : tactic unit := do term ← match hyp_name with | none := target | some v := get_local v >>= infer_type end, (rhs, lhs) ← match_eq term, -- trace $ "RHS: " ++ to_string rhs, if rhs.is_app then let fn := rhs.get_app_fn, args := rhs.get_app_args in if fn.is_constant && (fn.const_name.components.ilast = `rec) then case_split_rec hyp_name fn.const_name args else if fn.is_constant && (fn.const_name.components.ilast = `cases_on) then case_split_cases_on hyp_name fn.const_name args else tactic.fail "no recursor found" else return () -- tactic.fail "not an equality" meta def break_match_or_fail (hyp_name : option name) : expr → tactic unit | (expr.app f g) := subterms (expr.app f g) (fun head args, do -- trace head, (match_name, scrut) ← find_match head args, tree_repeat (destruct_subst_dsimp hyp_name match_name scrut) $ try $ case_split_exposed_recursor hyp_name, return ()) | _ := tactic.fail "break_match: does not support this term" meta def break_match_hyp : tactic unit := -- The English name for `;`. seq -- First try to find a hypothesis where break_match succeds (until_first_hyp (λ loc, do ty ← infer_type loc, break_match_or_fail loc.local_pp_name ty)) -- If one succeds, clean up the context for all goals, by first clearing redundant equalities -- then try to prune goals using contradiction. (do clear_refl_eqs, try contradiction) meta def break_match_goal : tactic unit := do tgt ← target, match tgt with | (expr.app f g) := break_match_or_fail none (expr.app f g) | _ := return () end meta def break_if_or_fail (loc : option name) : expr → tactic unit | (expr.app f g) := subterms (expr.app f g) (fun head args, match head with -- add support for dite | (expr.const `ite _) := match args with | (pred :: _ ) := do n ← get_unused_name `p, -- tactic.trace pred, by_cases pred n, all_goals `[simp * at *; prune_case] -- replace this -- | (expr.const `dite _) := -- do n ← get_unused_name `p, -- tactic.trace pred, -- by_cases pred n, -- all_goals `[simp * at *] -- replace this -- | (expr.const `dite _) := | [] := tactic.fail "should be unreachable" end | _ := tactic.fail "no if" end) | _ := tactic.fail "break_if: does not support this term" meta def is_recursor : name → tactic bool | (name.mk_string s n) := if s = "rec" then return true else return false | _ := return false #eval (is_recursor `prod.rec) meta def break_irrefutable_or_fail (hyp_name : option name) (h : expr) : tactic unit := subterms h (fun h args, do is_rec ← (fun b, h.is_constant && b) <$> is_recursor h.const_name, if is_rec then destruct_subst_dsimp hyp_name h.const_name args.ilast else tactic.fail "") meta def break_irrefutable_hyp : tactic unit := until_first_hyp (λ loc, do ty ← infer_type loc, break_irrefutable_or_fail loc.local_pp_name ty) meta def break_if_hyp : tactic unit := (until_first_hyp (λ loc, do ty ← infer_type loc, break_if_or_fail loc.local_pp_name ty)) meta def break_if_target : tactic unit := do tgt ← target, match tgt with | (expr.app f g) := break_if_or_fail none (expr.app f g) | _ := return () end meta def break_match := break_match_hyp <|> break_match_goal meta def break_if := break_if_hyp <|> break_if_target meta def case_split := break_if <|> break_match open interactive.types meta def match_head (rhs lhs : expr) : tactic unit := let head_rhs := rhs.get_app_fn, head_lhs := lhs.get_app_fn in if head_rhs = head_lhs then return () else tactic.fail "match_head, no match" -- Not sure about this name anymore meta def find_inversion : tactic unit := until_first_hyp $ λ h, do ty ← infer_type h, (rhs, lhs) ← match_eq ty, match_head rhs lhs, cases_ h meta def break_conj_or_fail (ty : expr) (loc : expr) : tactic unit := do tactic.trace ty, tactic.trace loc, tactic.fail "foo" meta def break_conj : tactic unit := (until_first_hyp (λ loc, do ty ← infer_type loc, break_conj_or_fail ty loc))
cf5350b30e755e896338698fa1d4feef7393448b
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/bundled.lean
32d2378570a5ec7a9f8ab77b8ef951b68bfa50e6
[ "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
1,555
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Bundled structures -/ import algebra.group structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct : group carrier) attribute Group.struct [instance] structure CommGroup := (carrier : Type) (struct : comm_group carrier) attribute CommGroup.struct [instance] structure AddSemigroup := (carrier : Type) (struct : add_semigroup carrier) attribute AddSemigroup.struct [instance] structure AddCommSemigroup := (carrier : Type) (struct : add_comm_semigroup carrier) attribute AddCommSemigroup.struct [instance] structure AddMonoid := (carrier : Type) (struct : add_monoid carrier) attribute AddMonoid.struct [instance] structure AddCommMonoid := (carrier : Type) (struct : add_comm_monoid carrier) attribute AddCommMonoid.struct [instance] structure AddGroup := (carrier : Type) (struct : add_group carrier) attribute AddGroup.struct [instance] structure AddCommGroup := (carrier : Type) (struct : add_comm_group carrier) attribute AddCommGroup.struct [instance]
41a48e459df00b9e62f1357655dc4e4f98de7ada
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/exponential.lean
f51e1c0c4a303d4037cea90b5c670db5b732f91b
[ "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
27,318
lean
/- Copyright (c) 2021 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Eric Wieser -/ import analysis.analytic.basic import analysis.complex.basic import analysis.normed.field.infinite_sum import data.nat.choose.cast import data.finset.noncomm_prod import topology.algebra.algebra /-! # Exponential in a Banach algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we define `exp 𝕂 : 𝔸 → 𝔸`, the exponential map in a topological algebra `𝔸` over a field `𝕂`. While for most interesting results we need `𝔸` to be normed algebra, we do not require this in the definition in order to make `exp` independent of a particular choice of norm. The definition also does not require that `𝔸` be complete, but we need to assume it for most results. We then prove some basic results, but we avoid importing derivatives here to minimize dependencies. Results involving derivatives and comparisons with `real.exp` and `complex.exp` can be found in `analysis/special_functions/exponential`. ## Main results We prove most result for an arbitrary field `𝕂`, and then specialize to `𝕂 = ℝ` or `𝕂 = ℂ`. ### General case - `exp_add_of_commute_of_mem_ball` : if `𝕂` has characteristic zero, then given two commuting elements `x` and `y` in the disk of convergence, we have `exp 𝕂 (x+y) = (exp 𝕂 x) * (exp 𝕂 y)` - `exp_add_of_mem_ball` : if `𝕂` has characteristic zero and `𝔸` is commutative, then given two elements `x` and `y` in the disk of convergence, we have `exp 𝕂 (x+y) = (exp 𝕂 x) * (exp 𝕂 y)` - `exp_neg_of_mem_ball` : if `𝕂` has characteristic zero and `𝔸` is a division ring, then given an element `x` in the disk of convergence, we have `exp 𝕂 (-x) = (exp 𝕂 x)⁻¹`. ### `𝕂 = ℝ` or `𝕂 = ℂ` - `exp_series_radius_eq_top` : the `formal_multilinear_series` defining `exp 𝕂` has infinite radius of convergence - `exp_add_of_commute` : given two commuting elements `x` and `y`, we have `exp 𝕂 (x+y) = (exp 𝕂 x) * (exp 𝕂 y)` - `exp_add` : if `𝔸` is commutative, then we have `exp 𝕂 (x+y) = (exp 𝕂 x) * (exp 𝕂 y)` for any `x` and `y` - `exp_neg` : if `𝔸` is a division ring, then we have `exp 𝕂 (-x) = (exp 𝕂 x)⁻¹`. - `exp_sum_of_commute` : the analogous result to `exp_add_of_commute` for `finset.sum`. - `exp_sum` : the analogous result to `exp_add` for `finset.sum`. - `exp_nsmul` : repeated addition in the domain corresponds to repeated multiplication in the codomain. - `exp_zsmul` : repeated addition in the domain corresponds to repeated multiplication in the codomain. ### Other useful compatibility results - `exp_eq_exp` : if `𝔸` is a normed algebra over two fields `𝕂` and `𝕂'`, then `exp 𝕂 = exp 𝕂' 𝔸` -/ open filter is_R_or_C continuous_multilinear_map normed_field asymptotics open_locale nat topology big_operators ennreal section topological_algebra variables (𝕂 𝔸 : Type*) [field 𝕂] [ring 𝔸] [algebra 𝕂 𝔸] [topological_space 𝔸] [topological_ring 𝔸] /-- `exp_series 𝕂 𝔸` is the `formal_multilinear_series` whose `n`-th term is the map `(xᵢ) : 𝔸ⁿ ↦ (1/n! : 𝕂) • ∏ xᵢ`. Its sum is the exponential map `exp 𝕂 : 𝔸 → 𝔸`. -/ def exp_series : formal_multilinear_series 𝕂 𝔸 𝔸 := λ n, (n!⁻¹ : 𝕂) • continuous_multilinear_map.mk_pi_algebra_fin 𝕂 n 𝔸 variables {𝔸} /-- `exp 𝕂 : 𝔸 → 𝔸` is the exponential map determined by the action of `𝕂` on `𝔸`. It is defined as the sum of the `formal_multilinear_series` `exp_series 𝕂 𝔸`. Note that when `𝔸 = matrix n n 𝕂`, this is the **Matrix Exponential**; see [`analysis.normed_space.matrix_exponential`](../matrix_exponential) for lemmas specific to that case. -/ noncomputable def exp (x : 𝔸) : 𝔸 := (exp_series 𝕂 𝔸).sum x variables {𝕂} lemma exp_series_apply_eq (x : 𝔸) (n : ℕ) : exp_series 𝕂 𝔸 n (λ _, x) = (n!⁻¹ : 𝕂) • x^n := by simp [exp_series] lemma exp_series_apply_eq' (x : 𝔸) : (λ n, exp_series 𝕂 𝔸 n (λ _, x)) = (λ n, (n!⁻¹ : 𝕂) • x^n) := funext (exp_series_apply_eq x) lemma exp_series_sum_eq (x : 𝔸) : (exp_series 𝕂 𝔸).sum x = ∑' (n : ℕ), (n!⁻¹ : 𝕂) • x^n := tsum_congr (λ n, exp_series_apply_eq x n) lemma exp_eq_tsum : exp 𝕂 = (λ x : 𝔸, ∑' (n : ℕ), (n!⁻¹ : 𝕂) • x^n) := funext exp_series_sum_eq lemma exp_series_apply_zero (n : ℕ) : exp_series 𝕂 𝔸 n (λ _, (0 : 𝔸)) = pi.single 0 1 n := begin rw exp_series_apply_eq, cases n, { rw [pow_zero, nat.factorial_zero, nat.cast_one, inv_one, one_smul, pi.single_eq_same], }, { rw [zero_pow (nat.succ_pos _), smul_zero, pi.single_eq_of_ne (n.succ_ne_zero)], }, end @[simp] lemma exp_zero [t2_space 𝔸] : exp 𝕂 (0 : 𝔸) = 1 := by simp_rw [exp_eq_tsum, ←exp_series_apply_eq, exp_series_apply_zero, tsum_pi_single] @[simp] lemma exp_op [t2_space 𝔸] (x : 𝔸) : exp 𝕂 (mul_opposite.op x) = mul_opposite.op (exp 𝕂 x) := by simp_rw [exp, exp_series_sum_eq, ←mul_opposite.op_pow, ←mul_opposite.op_smul, tsum_op] @[simp] lemma exp_unop [t2_space 𝔸] (x : 𝔸ᵐᵒᵖ) : exp 𝕂 (mul_opposite.unop x) = mul_opposite.unop (exp 𝕂 x) := by simp_rw [exp, exp_series_sum_eq, ←mul_opposite.unop_pow, ←mul_opposite.unop_smul, tsum_unop] lemma star_exp [t2_space 𝔸] [star_ring 𝔸] [has_continuous_star 𝔸] (x : 𝔸) : star (exp 𝕂 x) = exp 𝕂 (star x) := by simp_rw [exp_eq_tsum, ←star_pow, ←star_inv_nat_cast_smul, ←tsum_star] variables (𝕂) lemma is_self_adjoint.exp [t2_space 𝔸] [star_ring 𝔸] [has_continuous_star 𝔸] {x : 𝔸} (h : is_self_adjoint x) : is_self_adjoint (exp 𝕂 x) := (star_exp x).trans $ h.symm ▸ rfl lemma commute.exp_right [t2_space 𝔸] {x y : 𝔸} (h : commute x y) : commute x (exp 𝕂 y) := begin rw exp_eq_tsum, exact commute.tsum_right x (λ n, (h.pow_right n).smul_right _), end lemma commute.exp_left [t2_space 𝔸] {x y : 𝔸} (h : commute x y) : commute (exp 𝕂 x) y := (h.symm.exp_right 𝕂).symm lemma commute.exp [t2_space 𝔸] {x y : 𝔸} (h : commute x y) : commute (exp 𝕂 x) (exp 𝕂 y) := (h.exp_left _).exp_right _ end topological_algebra section topological_division_algebra variables {𝕂 𝔸 : Type*} [field 𝕂] [division_ring 𝔸] [algebra 𝕂 𝔸] [topological_space 𝔸] [topological_ring 𝔸] lemma exp_series_apply_eq_div (x : 𝔸) (n : ℕ) : exp_series 𝕂 𝔸 n (λ _, x) = x^n / n! := by rw [div_eq_mul_inv, ←(nat.cast_commute n! (x ^ n)).inv_left₀.eq, ←smul_eq_mul, exp_series_apply_eq, inv_nat_cast_smul_eq _ _ _ _] lemma exp_series_apply_eq_div' (x : 𝔸) : (λ n, exp_series 𝕂 𝔸 n (λ _, x)) = (λ n, x^n / n!) := funext (exp_series_apply_eq_div x) lemma exp_series_sum_eq_div (x : 𝔸) : (exp_series 𝕂 𝔸).sum x = ∑' (n : ℕ), x^n / n! := tsum_congr (exp_series_apply_eq_div x) lemma exp_eq_tsum_div : exp 𝕂 = (λ x : 𝔸, ∑' (n : ℕ), x^n / n!) := funext exp_series_sum_eq_div end topological_division_algebra section normed section any_field_any_algebra variables {𝕂 𝔸 𝔹 : Type*} [nontrivially_normed_field 𝕂] variables [normed_ring 𝔸] [normed_ring 𝔹] [normed_algebra 𝕂 𝔸] [normed_algebra 𝕂 𝔹] lemma norm_exp_series_summable_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, ‖exp_series 𝕂 𝔸 n (λ _, x)‖) := (exp_series 𝕂 𝔸).summable_norm_apply hx lemma norm_exp_series_summable_of_mem_ball' (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, ‖(n!⁻¹ : 𝕂) • x^n‖) := begin change summable (norm ∘ _), rw ← exp_series_apply_eq', exact norm_exp_series_summable_of_mem_ball x hx end section complete_algebra variables [complete_space 𝔸] lemma exp_series_summable_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, exp_series 𝕂 𝔸 n (λ _, x)) := summable_of_summable_norm (norm_exp_series_summable_of_mem_ball x hx) lemma exp_series_summable_of_mem_ball' (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, (n!⁻¹ : 𝕂) • x^n) := summable_of_summable_norm (norm_exp_series_summable_of_mem_ball' x hx) lemma exp_series_has_sum_exp_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : has_sum (λ n, exp_series 𝕂 𝔸 n (λ _, x)) (exp 𝕂 x) := formal_multilinear_series.has_sum (exp_series 𝕂 𝔸) hx lemma exp_series_has_sum_exp_of_mem_ball' (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : has_sum (λ n, (n!⁻¹ : 𝕂) • x^n) (exp 𝕂 x):= begin rw ← exp_series_apply_eq', exact exp_series_has_sum_exp_of_mem_ball x hx end lemma has_fpower_series_on_ball_exp_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) : has_fpower_series_on_ball (exp 𝕂) (exp_series 𝕂 𝔸) 0 (exp_series 𝕂 𝔸).radius := (exp_series 𝕂 𝔸).has_fpower_series_on_ball h lemma has_fpower_series_at_exp_zero_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) : has_fpower_series_at (exp 𝕂) (exp_series 𝕂 𝔸) 0 := (has_fpower_series_on_ball_exp_of_radius_pos h).has_fpower_series_at lemma continuous_on_exp : continuous_on (exp 𝕂 : 𝔸 → 𝔸) (emetric.ball 0 (exp_series 𝕂 𝔸).radius) := formal_multilinear_series.continuous_on lemma analytic_at_exp_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : analytic_at 𝕂 (exp 𝕂) x:= begin by_cases h : (exp_series 𝕂 𝔸).radius = 0, { rw h at hx, exact (ennreal.not_lt_zero hx).elim }, { have h := pos_iff_ne_zero.mpr h, exact (has_fpower_series_on_ball_exp_of_radius_pos h).analytic_at_of_mem hx } end /-- In a Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero, if `x` and `y` are in the disk of convergence and commute, then `exp 𝕂 (x + y) = (exp 𝕂 x) * (exp 𝕂 y)`. -/ lemma exp_add_of_commute_of_mem_ball [char_zero 𝕂] {x y : 𝔸} (hxy : commute x y) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) (hy : y ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : exp 𝕂 (x + y) = (exp 𝕂 x) * (exp 𝕂 y) := begin rw [exp_eq_tsum, tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm (norm_exp_series_summable_of_mem_ball' x hx) (norm_exp_series_summable_of_mem_ball' y hy)], dsimp only, conv_lhs {congr, funext, rw [hxy.add_pow' _, finset.smul_sum]}, refine tsum_congr (λ n, finset.sum_congr rfl $ λ kl hkl, _), rw [nsmul_eq_smul_cast 𝕂, smul_smul, smul_mul_smul, ← (finset.nat.mem_antidiagonal.mp hkl), nat.cast_add_choose, (finset.nat.mem_antidiagonal.mp hkl)], congr' 1, have : (n! : 𝕂) ≠ 0 := nat.cast_ne_zero.mpr n.factorial_ne_zero, field_simp [this] end /-- `exp 𝕂 x` has explicit two-sided inverse `exp 𝕂 (-x)`. -/ noncomputable def invertible_exp_of_mem_ball [char_zero 𝕂] {x : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : invertible (exp 𝕂 x) := { inv_of := exp 𝕂 (-x), inv_of_mul_self := begin have hnx : -x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius, { rw [emetric.mem_ball, ←neg_zero, edist_neg_neg], exact hx }, rw [←exp_add_of_commute_of_mem_ball (commute.neg_left $ commute.refl x) hnx hx, neg_add_self, exp_zero], end, mul_inv_of_self := begin have hnx : -x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius, { rw [emetric.mem_ball, ←neg_zero, edist_neg_neg], exact hx }, rw [←exp_add_of_commute_of_mem_ball (commute.neg_right $ commute.refl x) hx hnx, add_neg_self, exp_zero], end } lemma is_unit_exp_of_mem_ball [char_zero 𝕂] {x : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : is_unit (exp 𝕂 x) := @is_unit_of_invertible _ _ _ (invertible_exp_of_mem_ball hx) lemma inv_of_exp_of_mem_ball [char_zero 𝕂] {x : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) [invertible (exp 𝕂 x)] : ⅟(exp 𝕂 x) = exp 𝕂 (-x) := by { letI := invertible_exp_of_mem_ball hx, convert (rfl : ⅟(exp 𝕂 x) = _) } /-- Any continuous ring homomorphism commutes with `exp`. -/ lemma map_exp_of_mem_ball {F} [ring_hom_class F 𝔸 𝔹] (f : F) (hf : continuous f) (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : f (exp 𝕂 x) = exp 𝕂 (f x) := begin rw [exp_eq_tsum, exp_eq_tsum], refine ((exp_series_summable_of_mem_ball' _ hx).has_sum.map f hf).tsum_eq.symm.trans _, dsimp only [function.comp], simp_rw [one_div, map_inv_nat_cast_smul f 𝕂 𝕂, map_pow], end end complete_algebra lemma algebra_map_exp_comm_of_mem_ball [complete_space 𝕂] (x : 𝕂) (hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : algebra_map 𝕂 𝔸 (exp 𝕂 x) = exp 𝕂 (algebra_map 𝕂 𝔸 x) := map_exp_of_mem_ball _ (continuous_algebra_map 𝕂 𝔸) _ hx end any_field_any_algebra section any_field_division_algebra variables {𝕂 𝔸 : Type*} [nontrivially_normed_field 𝕂] [normed_division_ring 𝔸] [normed_algebra 𝕂 𝔸] variables (𝕂) lemma norm_exp_series_div_summable_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, ‖x^n / n!‖) := begin change summable (norm ∘ _), rw ← exp_series_apply_eq_div' x, exact norm_exp_series_summable_of_mem_ball x hx end lemma exp_series_div_summable_of_mem_ball [complete_space 𝔸] (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, x^n / n!) := summable_of_summable_norm (norm_exp_series_div_summable_of_mem_ball 𝕂 x hx) lemma exp_series_div_has_sum_exp_of_mem_ball [complete_space 𝔸] (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : has_sum (λ n, x^n / n!) (exp 𝕂 x) := begin rw ← exp_series_apply_eq_div' x, exact exp_series_has_sum_exp_of_mem_ball x hx end variables {𝕂} lemma exp_neg_of_mem_ball [char_zero 𝕂] [complete_space 𝔸] {x : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : exp 𝕂 (-x) = (exp 𝕂 x)⁻¹ := begin letI := invertible_exp_of_mem_ball hx, exact inv_of_eq_inv (exp 𝕂 x), end end any_field_division_algebra section any_field_comm_algebra variables {𝕂 𝔸 : Type*} [nontrivially_normed_field 𝕂] [normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸] /-- In a commutative Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero, `exp 𝕂 (x+y) = (exp 𝕂 x) * (exp 𝕂 y)` for all `x`, `y` in the disk of convergence. -/ lemma exp_add_of_mem_ball [char_zero 𝕂] {x y : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) (hy : y ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : exp 𝕂 (x + y) = (exp 𝕂 x) * (exp 𝕂 y) := exp_add_of_commute_of_mem_ball (commute.all x y) hx hy end any_field_comm_algebra section is_R_or_C section any_algebra variables (𝕂 𝔸 𝔹 : Type*) [is_R_or_C 𝕂] [normed_ring 𝔸] [normed_algebra 𝕂 𝔸] variables [normed_ring 𝔹] [normed_algebra 𝕂 𝔹] /-- In a normed algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, the series defining the exponential map has an infinite radius of convergence. -/ lemma exp_series_radius_eq_top : (exp_series 𝕂 𝔸).radius = ∞ := begin refine (exp_series 𝕂 𝔸).radius_eq_top_of_summable_norm (λ r, _), refine summable_of_norm_bounded_eventually _ (real.summable_pow_div_factorial r) _, filter_upwards [eventually_cofinite_ne 0] with n hn, rw [norm_mul, norm_norm (exp_series 𝕂 𝔸 n), exp_series, norm_smul, norm_inv, norm_pow, nnreal.norm_eq, norm_nat_cast, mul_comm, ←mul_assoc, ←div_eq_mul_inv], have : ‖continuous_multilinear_map.mk_pi_algebra_fin 𝕂 n 𝔸‖ ≤ 1 := norm_mk_pi_algebra_fin_le_of_pos (nat.pos_of_ne_zero hn), exact mul_le_of_le_one_right (div_nonneg (pow_nonneg r.coe_nonneg n) n!.cast_nonneg) this end lemma exp_series_radius_pos : 0 < (exp_series 𝕂 𝔸).radius := begin rw exp_series_radius_eq_top, exact with_top.zero_lt_top end variables {𝕂 𝔸 𝔹} lemma norm_exp_series_summable (x : 𝔸) : summable (λ n, ‖exp_series 𝕂 𝔸 n (λ _, x)‖) := norm_exp_series_summable_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) lemma norm_exp_series_summable' (x : 𝔸) : summable (λ n, ‖(n!⁻¹ : 𝕂) • x^n‖) := norm_exp_series_summable_of_mem_ball' x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) section complete_algebra variables [complete_space 𝔸] lemma exp_series_summable (x : 𝔸) : summable (λ n, exp_series 𝕂 𝔸 n (λ _, x)) := summable_of_summable_norm (norm_exp_series_summable x) lemma exp_series_summable' (x : 𝔸) : summable (λ n, (n!⁻¹ : 𝕂) • x^n) := summable_of_summable_norm (norm_exp_series_summable' x) lemma exp_series_has_sum_exp (x : 𝔸) : has_sum (λ n, exp_series 𝕂 𝔸 n (λ _, x)) (exp 𝕂 x) := exp_series_has_sum_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) lemma exp_series_has_sum_exp' (x : 𝔸) : has_sum (λ n, (n!⁻¹ : 𝕂) • x^n) (exp 𝕂 x):= exp_series_has_sum_exp_of_mem_ball' x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) lemma exp_has_fpower_series_on_ball : has_fpower_series_on_ball (exp 𝕂) (exp_series 𝕂 𝔸) 0 ∞ := exp_series_radius_eq_top 𝕂 𝔸 ▸ has_fpower_series_on_ball_exp_of_radius_pos (exp_series_radius_pos _ _) lemma exp_has_fpower_series_at_zero : has_fpower_series_at (exp 𝕂) (exp_series 𝕂 𝔸) 0 := exp_has_fpower_series_on_ball.has_fpower_series_at @[continuity] lemma exp_continuous : continuous (exp 𝕂 : 𝔸 → 𝔸) := begin rw [continuous_iff_continuous_on_univ, ← metric.eball_top_eq_univ (0 : 𝔸), ← exp_series_radius_eq_top 𝕂 𝔸], exact continuous_on_exp end lemma exp_analytic (x : 𝔸) : analytic_at 𝕂 (exp 𝕂) x := analytic_at_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) /-- In a Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, if `x` and `y` commute, then `exp 𝕂 (x+y) = (exp 𝕂 x) * (exp 𝕂 y)`. -/ lemma exp_add_of_commute {x y : 𝔸} (hxy : commute x y) : exp 𝕂 (x + y) = (exp 𝕂 x) * (exp 𝕂 y) := exp_add_of_commute_of_mem_ball hxy ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) section variables (𝕂) /-- `exp 𝕂 x` has explicit two-sided inverse `exp 𝕂 (-x)`. -/ noncomputable def invertible_exp (x : 𝔸) : invertible (exp 𝕂 x) := invertible_exp_of_mem_ball $ (exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _ lemma is_unit_exp (x : 𝔸) : is_unit (exp 𝕂 x) := is_unit_exp_of_mem_ball $ (exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _ lemma inv_of_exp (x : 𝔸) [invertible (exp 𝕂 x)] : ⅟(exp 𝕂 x) = exp 𝕂 (-x) := inv_of_exp_of_mem_ball $ (exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _ lemma ring.inverse_exp (x : 𝔸) : ring.inverse (exp 𝕂 x) = exp 𝕂 (-x) := begin letI := invertible_exp 𝕂 x, exact ring.inverse_invertible _, end lemma exp_mem_unitary_of_mem_skew_adjoint [star_ring 𝔸] [has_continuous_star 𝔸] {x : 𝔸} (h : x ∈ skew_adjoint 𝔸) : exp 𝕂 x ∈ unitary 𝔸 := by rw [unitary.mem_iff, star_exp, skew_adjoint.mem_iff.mp h, ←exp_add_of_commute (commute.refl x).neg_left, ←exp_add_of_commute (commute.refl x).neg_right, add_left_neg, add_right_neg, exp_zero, and_self] end /-- In a Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, if a family of elements `f i` mutually commute then `exp 𝕂 (∑ i, f i) = ∏ i, exp 𝕂 (f i)`. -/ lemma exp_sum_of_commute {ι} (s : finset ι) (f : ι → 𝔸) (h : (s : set ι).pairwise $ λ i j, commute (f i) (f j)) : exp 𝕂 (∑ i in s, f i) = s.noncomm_prod (λ i, exp 𝕂 (f i)) (λ i hi j hj _, (h.of_refl hi hj).exp 𝕂) := begin classical, induction s using finset.induction_on with a s ha ih, { simp }, rw [finset.noncomm_prod_insert_of_not_mem _ _ _ _ ha, finset.sum_insert ha, exp_add_of_commute, ih (h.mono $ finset.subset_insert _ _)], refine commute.sum_right _ _ _ (λ i hi, _), exact h.of_refl (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hi), end lemma exp_nsmul (n : ℕ) (x : 𝔸) : exp 𝕂 (n • x) = exp 𝕂 x ^ n := begin induction n with n ih, { rw [zero_smul, pow_zero, exp_zero], }, { rw [succ_nsmul, pow_succ, exp_add_of_commute ((commute.refl x).smul_right n), ih] } end variables (𝕂) /-- Any continuous ring homomorphism commutes with `exp`. -/ lemma map_exp {F} [ring_hom_class F 𝔸 𝔹] (f : F) (hf : continuous f) (x : 𝔸) : f (exp 𝕂 x) = exp 𝕂 (f x) := map_exp_of_mem_ball f hf x $ (exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _ lemma exp_smul {G} [monoid G] [mul_semiring_action G 𝔸] [has_continuous_const_smul G 𝔸] (g : G) (x : 𝔸) : exp 𝕂 (g • x) = g • exp 𝕂 x := (map_exp 𝕂 (mul_semiring_action.to_ring_hom G 𝔸 g) (continuous_const_smul _) x).symm lemma exp_units_conj (y : 𝔸ˣ) (x : 𝔸) : exp 𝕂 (y * x * ↑(y⁻¹) : 𝔸) = y * exp 𝕂 x * ↑(y⁻¹) := exp_smul _ (conj_act.to_conj_act y) x lemma exp_units_conj' (y : 𝔸ˣ) (x : 𝔸) : exp 𝕂 (↑(y⁻¹) * x * y) = ↑(y⁻¹) * exp 𝕂 x * y := exp_units_conj _ _ _ @[simp] lemma prod.fst_exp [complete_space 𝔹] (x : 𝔸 × 𝔹) : (exp 𝕂 x).fst = exp 𝕂 x.fst := map_exp _ (ring_hom.fst 𝔸 𝔹) continuous_fst x @[simp] lemma prod.snd_exp [complete_space 𝔹] (x : 𝔸 × 𝔹) : (exp 𝕂 x).snd = exp 𝕂 x.snd := map_exp _ (ring_hom.snd 𝔸 𝔹) continuous_snd x @[simp] lemma pi.exp_apply {ι : Type*} {𝔸 : ι → Type*} [fintype ι] [Π i, normed_ring (𝔸 i)] [Π i, normed_algebra 𝕂 (𝔸 i)] [Π i, complete_space (𝔸 i)] (x : Π i, 𝔸 i) (i : ι) : exp 𝕂 x i = exp 𝕂 (x i) := begin -- Lean struggles to infer this instance due to it wanting `[Π i, semi_normed_ring (𝔸 i)]` letI : normed_algebra 𝕂 (Π i, 𝔸 i) := pi.normed_algebra _, exact map_exp _ (pi.eval_ring_hom 𝔸 i) (continuous_apply _) x end lemma pi.exp_def {ι : Type*} {𝔸 : ι → Type*} [fintype ι] [Π i, normed_ring (𝔸 i)] [Π i, normed_algebra 𝕂 (𝔸 i)] [Π i, complete_space (𝔸 i)] (x : Π i, 𝔸 i) : exp 𝕂 x = λ i, exp 𝕂 (x i) := funext $ pi.exp_apply 𝕂 x lemma function.update_exp {ι : Type*} {𝔸 : ι → Type*} [fintype ι] [decidable_eq ι] [Π i, normed_ring (𝔸 i)] [Π i, normed_algebra 𝕂 (𝔸 i)] [Π i, complete_space (𝔸 i)] (x : Π i, 𝔸 i) (j : ι) (xj : 𝔸 j) : function.update (exp 𝕂 x) j (exp 𝕂 xj) = exp 𝕂 (function.update x j xj) := begin ext i, simp_rw [pi.exp_def], exact (function.apply_update (λ i, exp 𝕂) x j xj i).symm, end end complete_algebra lemma algebra_map_exp_comm (x : 𝕂) : algebra_map 𝕂 𝔸 (exp 𝕂 x) = exp 𝕂 (algebra_map 𝕂 𝔸 x) := algebra_map_exp_comm_of_mem_ball x $ (exp_series_radius_eq_top 𝕂 𝕂).symm ▸ edist_lt_top _ _ end any_algebra section division_algebra variables {𝕂 𝔸 : Type*} [is_R_or_C 𝕂] [normed_division_ring 𝔸] [normed_algebra 𝕂 𝔸] variables (𝕂) lemma norm_exp_series_div_summable (x : 𝔸) : summable (λ n, ‖x^n / n!‖) := norm_exp_series_div_summable_of_mem_ball 𝕂 x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) variables [complete_space 𝔸] lemma exp_series_div_summable (x : 𝔸) : summable (λ n, x^n / n!) := summable_of_summable_norm (norm_exp_series_div_summable 𝕂 x) lemma exp_series_div_has_sum_exp (x : 𝔸) : has_sum (λ n, x^n / n!) (exp 𝕂 x):= exp_series_div_has_sum_exp_of_mem_ball 𝕂 x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) variables {𝕂} lemma exp_neg (x : 𝔸) : exp 𝕂 (-x) = (exp 𝕂 x)⁻¹ := exp_neg_of_mem_ball $ (exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _ lemma exp_zsmul (z : ℤ) (x : 𝔸) : exp 𝕂 (z • x) = (exp 𝕂 x) ^ z := begin obtain ⟨n, rfl | rfl⟩ := z.eq_coe_or_neg, { rw [zpow_coe_nat, coe_nat_zsmul, exp_nsmul] }, { rw [zpow_neg, zpow_coe_nat, neg_smul, exp_neg, coe_nat_zsmul, exp_nsmul] }, end lemma exp_conj (y : 𝔸) (x : 𝔸) (hy : y ≠ 0) : exp 𝕂 (y * x * y⁻¹) = y * exp 𝕂 x * y⁻¹ := exp_units_conj _ (units.mk0 y hy) x lemma exp_conj' (y : 𝔸) (x : 𝔸) (hy : y ≠ 0) : exp 𝕂 (y⁻¹ * x * y) = y⁻¹ * exp 𝕂 x * y := exp_units_conj' _ (units.mk0 y hy) x end division_algebra section comm_algebra variables {𝕂 𝔸 : Type*} [is_R_or_C 𝕂] [normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸] /-- In a commutative Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, `exp 𝕂 (x+y) = (exp 𝕂 x) * (exp 𝕂 y)`. -/ lemma exp_add {x y : 𝔸} : exp 𝕂 (x + y) = (exp 𝕂 x) * (exp 𝕂 y) := exp_add_of_mem_ball ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) /-- A version of `exp_sum_of_commute` for a commutative Banach-algebra. -/ lemma exp_sum {ι} (s : finset ι) (f : ι → 𝔸) : exp 𝕂 (∑ i in s, f i) = ∏ i in s, exp 𝕂 (f i) := begin rw [exp_sum_of_commute, finset.noncomm_prod_eq_prod], exact λ i hi j hj _, commute.all _ _, end end comm_algebra end is_R_or_C end normed section scalar_tower variables (𝕂 𝕂' 𝔸 : Type*) [field 𝕂] [field 𝕂'] [ring 𝔸] [algebra 𝕂 𝔸] [algebra 𝕂' 𝔸] [topological_space 𝔸] [topological_ring 𝔸] /-- If a normed ring `𝔸` is a normed algebra over two fields, then they define the same `exp_series` on `𝔸`. -/ lemma exp_series_eq_exp_series (n : ℕ) (x : 𝔸) : (exp_series 𝕂 𝔸 n (λ _, x)) = (exp_series 𝕂' 𝔸 n (λ _, x)) := by rw [exp_series_apply_eq, exp_series_apply_eq, inv_nat_cast_smul_eq 𝕂 𝕂'] /-- If a normed ring `𝔸` is a normed algebra over two fields, then they define the same exponential function on `𝔸`. -/ lemma exp_eq_exp : (exp 𝕂 : 𝔸 → 𝔸) = exp 𝕂' := begin ext, rw [exp, exp], refine tsum_congr (λ n, _), rw exp_series_eq_exp_series 𝕂 𝕂' 𝔸 n x end lemma exp_ℝ_ℂ_eq_exp_ℂ_ℂ : (exp ℝ : ℂ → ℂ) = exp ℂ := exp_eq_exp ℝ ℂ ℂ /-- A version of `complex.of_real_exp` for `exp` instead of `complex.exp` -/ @[simp, norm_cast] lemma of_real_exp_ℝ_ℝ (r : ℝ) : ↑(exp ℝ r) = exp ℂ (r : ℂ) := (map_exp ℝ (algebra_map ℝ ℂ) (continuous_algebra_map _ _) r).trans (congr_fun exp_ℝ_ℂ_eq_exp_ℂ_ℂ _) end scalar_tower
3697bb69b4f1a330e56ef4b2ffab0b66a856a550
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/Tactic/Injection.lean
400cfde0c570853caf46164c2a7f0279215b95b3
[ "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
4,070
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Intro namespace Lean.Meta def getCtorNumPropFields (ctorInfo : ConstructorVal) : MetaM Nat := do forallTelescopeReducing ctorInfo.type fun xs _ => do let mut numProps := 0 for i in [:ctorInfo.numFields] do if (← isProp (← inferType xs[ctorInfo.numParams + i])) then numProps := numProps + 1 return numProps inductive InjectionResultCore where | solved | subgoal (mvarId : MVarId) (numNewEqs : Nat) def injectionCore (mvarId : MVarId) (fvarId : FVarId) : MetaM InjectionResultCore := withMVarContext mvarId do checkNotAssigned mvarId `injection let decl ← getLocalDecl fvarId let type ← whnf decl.type match type.eq? with | none => throwTacticEx `injection mvarId "equality expected" | some (α, a, b) => let a ← whnf a let b ← whnf b let target ← getMVarType mvarId let env ← getEnv match a.isConstructorApp? env, b.isConstructorApp? env with | some aCtor, some bCtor => let val ← mkNoConfusion target (mkFVar fvarId) if aCtor.name != bCtor.name then assignExprMVar mvarId val pure InjectionResultCore.solved else let valType ← inferType val let valType ← whnf valType match valType with | Expr.forallE _ newTarget _ _ => let newTarget := newTarget.headBeta let tag ← getMVarTag mvarId let newMVar ← mkFreshExprSyntheticOpaqueMVar newTarget tag assignExprMVar mvarId (mkApp val newMVar) let mvarId ← tryClear newMVar.mvarId! fvarId /- Recall that `noConfusion` does not include equalities for propositions since they are trivial due to proof irrelevance. -/ let numPropFields ← getCtorNumPropFields aCtor return InjectionResultCore.subgoal mvarId (aCtor.numFields - numPropFields) | _ => throwTacticEx `injection mvarId "ill-formed noConfusion auxiliary construction" | _, _ => throwTacticEx `injection mvarId "equality of constructor applications expected" inductive InjectionResult where | solved | subgoal (mvarId : MVarId) (newEqs : Array FVarId) (remainingNames : List Name) private def heqToEq (mvarId : MVarId) (fvarId : FVarId) : MetaM (FVarId × MVarId) := withMVarContext mvarId do let decl ← getLocalDecl fvarId let type ← whnf decl.type match type.heq? with | none => pure (fvarId, mvarId) | some (α, a, β, b) => if (← isDefEq α β) then let pr ← mkEqOfHEq (mkFVar fvarId) let eq ← mkEq a b let mvarId ← assert mvarId decl.userName eq pr let mvarId ← clear mvarId fvarId let (fvarId, mvarId) ← intro1P mvarId pure (fvarId, mvarId) else pure (fvarId, mvarId) def injectionIntro : Nat → MVarId → Array FVarId → List Name → MetaM InjectionResult | 0, mvarId, fvarIds, remainingNames => pure $ InjectionResult.subgoal mvarId fvarIds remainingNames | n+1, mvarId, fvarIds, name::remainingNames => do let (fvarId, mvarId) ← intro mvarId name let (fvarId, mvarId) ← heqToEq mvarId fvarId injectionIntro n mvarId (fvarIds.push fvarId) remainingNames | n+1, mvarId, fvarIds, [] => do let (fvarId, mvarId) ← intro1 mvarId let (fvarId, mvarId) ← heqToEq mvarId fvarId injectionIntro n mvarId (fvarIds.push fvarId) [] def injection (mvarId : MVarId) (fvarId : FVarId) (newNames : List Name := []) (useUnusedNames : Bool := true) : MetaM InjectionResult := do match (← injectionCore mvarId fvarId) with | InjectionResultCore.solved => pure InjectionResult.solved | InjectionResultCore.subgoal mvarId numEqs => injectionIntro numEqs mvarId #[] newNames end Lean.Meta
7d0e6bb1acc8c2edf91f469ec80203fa1c8fe37c
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/normed_space/operator_norm.lean
a2a0e71b7316eb4003b981148f5539f6132a2073
[ "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
83,104
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import algebra.algebra.tower import analysis.asymptotics.asymptotics import analysis.normed_space.continuous_linear_map import analysis.normed_space.linear_isometry import topology.algebra.module.strong_topology /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous (semi)linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. Since a lot of elementary properties don't require `‖x‖ = 0 → x = 0` we start setting up the theory for `seminormed_add_comm_group` and we specialize to `normed_add_comm_group` at the end. Note that most of statements that apply to semilinear maps only hold when the ring homomorphism is isometric, as expressed by the typeclass `[ring_hom_isometric σ]`. -/ noncomputable theory open_locale classical nnreal topology -- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps variables {𝕜 𝕜₂ 𝕜₃ E Eₗ F Fₗ G Gₗ 𝓕 : Type*} section semi_normed open metric continuous_linear_map variables [seminormed_add_comm_group E] [seminormed_add_comm_group Eₗ] [seminormed_add_comm_group F] [seminormed_add_comm_group Fₗ] [seminormed_add_comm_group G] [seminormed_add_comm_group Gₗ] variables [nontrivially_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] [nontrivially_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜 Eₗ] [normed_space 𝕜₂ F] [normed_space 𝕜 Fₗ] [normed_space 𝕜₃ G] [normed_space 𝕜 Gₗ] {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₃ : 𝕜₂ →+* 𝕜₃} {σ₁₃ : 𝕜 →+* 𝕜₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] /-- If `‖x‖ = 0` and `f` is continuous then `‖f x‖ = 0`. -/ lemma norm_image_of_norm_zero [semilinear_map_class 𝓕 σ₁₂ E F] (f : 𝓕) (hf : continuous f) {x : E} (hx : ‖x‖ = 0) : ‖f x‖ = 0 := begin refine le_antisymm (le_of_forall_pos_le_add (λ ε hε, _)) (norm_nonneg (f x)), rcases normed_add_comm_group.tendsto_nhds_nhds.1 (hf.tendsto 0) ε hε with ⟨δ, δ_pos, hδ⟩, replace hδ := hδ x, rw [sub_zero, hx] at hδ, replace hδ := le_of_lt (hδ δ_pos), rw [map_zero, sub_zero] at hδ, rwa [zero_add] end section variables [ring_hom_isometric σ₁₂] [ring_hom_isometric σ₂₃] lemma semilinear_map_class.bound_of_shell_semi_normed [semilinear_map_class 𝓕 σ₁₂ E F] (f : 𝓕) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ‖c‖) (hf : ∀ x, ε / ‖c‖ ≤ ‖x‖ → ‖x‖ < ε → ‖f x‖ ≤ C * ‖x‖) {x : E} (hx : ‖x‖ ≠ 0) : ‖f x‖ ≤ C * ‖x‖ := begin rcases rescale_to_shell_semi_normed hc ε_pos hx with ⟨δ, hδ, δxle, leδx, δinv⟩, have := hf (δ • x) leδx δxle, simpa only [map_smulₛₗ, norm_smul, mul_left_comm C, mul_le_mul_left (norm_pos_iff.2 hδ), ring_hom_isometric.is_iso] using hf (δ • x) leδx δxle end /-- A continuous linear map between seminormed spaces is bounded when the field is nontrivially normed. The continuity ensures boundedness on a ball of some radius `ε`. The nontriviality of the norm is then used to rescale any element into an element of norm in `[ε/C, ε]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma semilinear_map_class.bound_of_continuous [semilinear_map_class 𝓕 σ₁₂ E F] (f : 𝓕) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ‖f x‖ ≤ C * ‖x‖) := begin rcases normed_add_comm_group.tendsto_nhds_nhds.1 (hf.tendsto 0) 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, simp only [sub_zero, map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, have : 0 < ‖c‖ / ε, from div_pos (zero_lt_one.trans hc) ε_pos, refine ⟨‖c‖ / ε, this, λ x, _⟩, by_cases hx : ‖x‖ = 0, { rw [hx, mul_zero], exact le_of_eq (norm_image_of_norm_zero f hf hx) }, refine semilinear_map_class.bound_of_shell_semi_normed f ε_pos hc (λ x hle hlt, _) hx, refine (hε _ hlt).le.trans _, rwa [← div_le_iff' this, one_div_div] end end namespace continuous_linear_map theorem bound [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) : ∃ C, 0 < C ∧ (∀ x : E, ‖f x‖ ≤ C * ‖x‖) := semilinear_map_class.bound_of_continuous f f.2 section open filter variables (𝕜 E) /-- Given a unit-length element `x` of a normed space `E` over a field `𝕜`, the natural linear isometry map from `𝕜` to `E` by taking multiples of `x`.-/ def _root_.linear_isometry.to_span_singleton {v : E} (hv : ‖v‖ = 1) : 𝕜 →ₗᵢ[𝕜] E := { norm_map' := λ x, by simp [norm_smul, hv], .. linear_map.to_span_singleton 𝕜 E v } variables {𝕜 E} @[simp] lemma _root_.linear_isometry.to_span_singleton_apply {v : E} (hv : ‖v‖ = 1) (a : 𝕜) : linear_isometry.to_span_singleton 𝕜 E hv a = a • v := rfl @[simp] lemma _root_.linear_isometry.coe_to_span_singleton {v : E} (hv : ‖v‖ = 1) : (linear_isometry.to_span_singleton 𝕜 E hv).to_linear_map = linear_map.to_span_singleton 𝕜 E v := rfl end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm (f : E →SL[σ₁₂] F) := Inf {c | 0 ≤ c ∧ ∀ x, ‖f x‖ ≤ c * ‖x‖} instance has_op_norm : has_norm (E →SL[σ₁₂] F) := ⟨op_norm⟩ lemma norm_def (f : E →SL[σ₁₂] F) : ‖f‖ = Inf {c | 0 ≤ c ∧ ∀ x, ‖f x‖ ≤ c * ‖x‖} := rfl -- So that invocations of `le_cInf` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty [ring_hom_isometric σ₁₂] {f : E →SL[σ₁₂] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ‖f x‖ ≤ c * ‖x‖ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →SL[σ₁₂] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ‖f x‖ ≤ c * ‖x‖ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound (f : E →SL[σ₁₂] F) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ‖f x‖ ≤ M * ‖x‖) : ‖f‖ ≤ M := cInf_le bounds_bdd_below ⟨hMp, hM⟩ /-- If one controls the norm of every `A x`, `‖x‖ ≠ 0`, then one controls the norm of `A`. -/ lemma op_norm_le_bound' (f : E →SL[σ₁₂] F) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ‖x‖ ≠ 0 → ‖f x‖ ≤ M * ‖x‖) : ‖f‖ ≤ M := op_norm_le_bound f hMp $ λ x, (ne_or_eq (‖x‖) 0).elim (hM x) $ λ h, by simp only [h, mul_zero, norm_image_of_norm_zero f f.2 h] theorem op_norm_le_of_lipschitz {f : E →SL[σ₁₂] F} {K : ℝ≥0} (hf : lipschitz_with K f) : ‖f‖ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_eq_of_bounds {φ : E →SL[σ₁₂] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ‖φ x‖ ≤ M*‖x‖) (h_below : ∀ N ≥ 0, (∀ x, ‖φ x‖ ≤ N*‖x‖) → M ≤ N) : ‖φ‖ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) lemma op_norm_neg (f : E →SL[σ₁₂] F) : ‖-f‖ = ‖f‖ := by simp only [norm_def, neg_apply, norm_neg] section variables [ring_hom_isometric σ₁₂] [ring_hom_isometric σ₂₃] (f g : E →SL[σ₁₂] F) (h : F →SL[σ₂₃] G) (x : E) lemma op_norm_nonneg : 0 ≤ ‖f‖ := le_cInf bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `‖f x‖ ≤ ‖f‖ * ‖x‖`. -/ theorem le_op_norm : ‖f x‖ ≤ ‖f‖ * ‖x‖ := begin obtain ⟨C, Cpos, hC⟩ := f.bound, replace hC := hC x, by_cases h : ‖x‖ = 0, { rwa [h, mul_zero] at ⊢ hC }, have hlt : 0 < ‖x‖ := lt_of_le_of_ne (norm_nonneg x) (ne.symm h), exact (div_le_iff hlt).mp (le_cInf bounds_nonempty (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc })), end theorem dist_le_op_norm (x y : E) : dist (f x) (f y) ≤ ‖f‖ * dist x y := by simp_rw [dist_eq_norm, ← map_sub, f.le_op_norm] theorem le_op_norm_of_le {c : ℝ} {x} (h : ‖x‖ ≤ c) : ‖f x‖ ≤ ‖f‖ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ‖f‖ ≤ c) (x : E) : ‖f x‖ ≤ c * ‖x‖ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) lemma ratio_le_op_norm : ‖f x‖ / ‖x‖ ≤ ‖f‖ := div_le_of_nonneg_of_le_mul (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ‖x‖ ≤ 1 → ‖f x‖ ≤ ‖f‖ := mul_one ‖f‖ ▸ f.le_op_norm_of_le lemma op_norm_le_of_shell {f : E →SL[σ₁₂] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : 1 < ‖c‖) (hf : ∀ x, ε / ‖c‖ ≤ ‖x‖ → ‖x‖ < ε → ‖f x‖ ≤ C * ‖x‖) : ‖f‖ ≤ C := f.op_norm_le_bound' hC $ λ x hx, semilinear_map_class.bound_of_shell_semi_normed f ε_pos hc hf hx lemma op_norm_le_of_ball {f : E →SL[σ₁₂] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ‖f x‖ ≤ C * ‖x‖) : ‖f‖ ≤ C := begin rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine op_norm_le_of_shell ε_pos hC hc (λ x _ hx, hf x _), rwa ball_zero_eq end lemma op_norm_le_of_nhds_zero {f : E →SL[σ₁₂] F} {C : ℝ} (hC : 0 ≤ C) (hf : ∀ᶠ x in 𝓝 (0 : E), ‖f x‖ ≤ C * ‖x‖) : ‖f‖ ≤ C := let ⟨ε, ε0, hε⟩ := metric.eventually_nhds_iff_ball.1 hf in op_norm_le_of_ball ε0 hC hε lemma op_norm_le_of_shell' {f : E →SL[σ₁₂] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : ‖c‖ < 1) (hf : ∀ x, ε * ‖c‖ ≤ ‖x‖ → ‖x‖ < ε → ‖f x‖ ≤ C * ‖x‖) : ‖f‖ ≤ C := begin by_cases h0 : c = 0, { refine op_norm_le_of_ball ε_pos hC (λ x hx, hf x _ _), { simp [h0] }, { rwa ball_zero_eq at hx } }, { rw [← inv_inv c, norm_inv, inv_lt_one_iff_of_pos (norm_pos_iff.2 $ inv_ne_zero h0)] at hc, refine op_norm_le_of_shell ε_pos hC hc _, rwa [norm_inv, div_eq_mul_inv, inv_inv] } end /-- For a continuous real linear map `f`, if one controls the norm of every `f x`, `‖x‖ = 1`, then one controls the norm of `f`. -/ lemma op_norm_le_of_unit_norm [normed_space ℝ E] [normed_space ℝ F] {f : E →L[ℝ] F} {C : ℝ} (hC : 0 ≤ C) (hf : ∀ x, ‖x‖ = 1 → ‖f x‖ ≤ C) : ‖f‖ ≤ C := begin refine op_norm_le_bound' f hC (λ x hx, _), have H₁ : ‖(‖x‖⁻¹ • x)‖ = 1, by rw [norm_smul, norm_inv, norm_norm, inv_mul_cancel hx], have H₂ := hf _ H₁, rwa [map_smul, norm_smul, norm_inv, norm_norm, ← div_eq_inv_mul, div_le_iff] at H₂, exact (norm_nonneg x).lt_of_ne' hx end /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ‖f + g‖ ≤ ‖f‖ + ‖g‖ := (f + g).op_norm_le_bound (add_nonneg f.op_norm_nonneg g.op_norm_nonneg) $ λ x, (norm_add_le_of_le (f.le_op_norm x) (g.le_op_norm x)).trans_eq (add_mul _ _ _).symm /-- The norm of the `0` operator is `0`. -/ theorem op_norm_zero : ‖(0 : E →SL[σ₁₂] F)‖ = 0 := le_antisymm (cInf_le bounds_bdd_below ⟨le_rfl, λ _, le_of_eq (by { rw [zero_mul], exact norm_zero })⟩) (op_norm_nonneg _) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ‖id 𝕜 E‖ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If there is an element with norm different from `0`, then the norm of the identity equals `1`. (Since we are working with seminorms supposing that the space is non-trivial is not enough.) -/ lemma norm_id_of_nontrivial_seminorm (h : ∃ (x : E), ‖x‖ ≠ 0) : ‖id 𝕜 E‖ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := h in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self hx] at this lemma op_norm_smul_le {𝕜' : Type*} [normed_field 𝕜'] [normed_space 𝕜' F] [smul_comm_class 𝕜₂ 𝕜' F] (c : 𝕜') (f : E →SL[σ₁₂] F) : ‖c • f‖ ≤ ‖c‖ * ‖f‖ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) /-- Continuous linear maps themselves form a seminormed space with respect to the operator norm. This is only a temporary definition because we want to replace the topology with `continuous_linear_map.topological_space` to avoid diamond issues. See Note [forgetful inheritance] -/ protected def tmp_seminormed_add_comm_group : seminormed_add_comm_group (E →SL[σ₁₂] F) := add_group_seminorm.to_seminormed_add_comm_group { to_fun := norm, map_zero' := op_norm_zero, add_le' := op_norm_add_le, neg' := op_norm_neg } /-- The `pseudo_metric_space` structure on `E →SL[σ₁₂] F` coming from `continuous_linear_map.tmp_seminormed_add_comm_group`. See Note [forgetful inheritance] -/ protected def tmp_pseudo_metric_space : pseudo_metric_space (E →SL[σ₁₂] F) := continuous_linear_map.tmp_seminormed_add_comm_group.to_pseudo_metric_space /-- The `uniform_space` structure on `E →SL[σ₁₂] F` coming from `continuous_linear_map.tmp_seminormed_add_comm_group`. See Note [forgetful inheritance] -/ protected def tmp_uniform_space : uniform_space (E →SL[σ₁₂] F) := continuous_linear_map.tmp_pseudo_metric_space.to_uniform_space /-- The `topological_space` structure on `E →SL[σ₁₂] F` coming from `continuous_linear_map.tmp_seminormed_add_comm_group`. See Note [forgetful inheritance] -/ protected def tmp_topological_space : topological_space (E →SL[σ₁₂] F) := continuous_linear_map.tmp_uniform_space.to_topological_space section tmp local attribute [-instance] continuous_linear_map.topological_space local attribute [-instance] continuous_linear_map.uniform_space local attribute [instance] continuous_linear_map.tmp_seminormed_add_comm_group protected lemma tmp_topological_add_group : topological_add_group (E →SL[σ₁₂] F) := infer_instance protected lemma tmp_closed_ball_div_subset {a b : ℝ} (ha : 0 < a) (hb : 0 < b) : closed_ball (0 : E →SL[σ₁₂] F) (a / b) ⊆ {f | ∀ x ∈ closed_ball (0 : E) b, f x ∈ closed_ball (0 : F) a} := begin intros f hf x hx, rw mem_closed_ball_zero_iff at ⊢ hf hx, calc ‖f x‖ ≤ ‖f‖ * ‖x‖ : le_op_norm _ _ ... ≤ (a/b) * b : mul_le_mul hf hx (norm_nonneg _) (div_pos ha hb).le ... = a : div_mul_cancel a hb.ne.symm end end tmp protected theorem tmp_topology_eq : (continuous_linear_map.tmp_topological_space : topological_space (E →SL[σ₁₂] F)) = continuous_linear_map.topological_space := begin refine continuous_linear_map.tmp_topological_add_group.ext infer_instance ((@metric.nhds_basis_closed_ball _ continuous_linear_map.tmp_pseudo_metric_space 0).ext (continuous_linear_map.has_basis_nhds_zero_of_basis metric.nhds_basis_closed_ball) _ _), { rcases normed_field.exists_norm_lt_one 𝕜 with ⟨c, hc₀, hc₁⟩, refine λ ε hε, ⟨⟨closed_ball 0 (1 / ‖c‖), ε⟩, ⟨normed_space.is_vonN_bounded_closed_ball _ _ _, hε⟩, λ f hf, _⟩, change ∀ x, _ at hf, simp_rw mem_closed_ball_zero_iff at hf, rw @mem_closed_ball_zero_iff _ seminormed_add_comm_group.to_seminormed_add_group, refine op_norm_le_of_shell' (div_pos one_pos hc₀) hε.le hc₁ (λ x hx₁ hxc, _), rw div_mul_cancel 1 hc₀.ne.symm at hx₁, exact (hf x hxc.le).trans (le_mul_of_one_le_right hε.le hx₁) }, { rintros ⟨S, ε⟩ ⟨hS, hε⟩, rw [normed_space.is_vonN_bounded_iff, ← bounded_iff_is_bounded] at hS, rcases hS.subset_ball_lt 0 0 with ⟨δ, hδ, hSδ⟩, exact ⟨ε/δ, div_pos hε hδ, (continuous_linear_map.tmp_closed_ball_div_subset hε hδ).trans $ λ f hf x hx, hf x $ hSδ hx⟩ } end protected theorem tmp_uniform_space_eq : (continuous_linear_map.tmp_uniform_space : uniform_space (E →SL[σ₁₂] F)) = continuous_linear_map.uniform_space := begin rw [← @uniform_add_group.to_uniform_space_eq _ continuous_linear_map.tmp_uniform_space, ← @uniform_add_group.to_uniform_space_eq _ continuous_linear_map.uniform_space], congr' 1, exact continuous_linear_map.tmp_topology_eq end instance to_pseudo_metric_space : pseudo_metric_space (E →SL[σ₁₂] F) := continuous_linear_map.tmp_pseudo_metric_space.replace_uniformity (congr_arg _ continuous_linear_map.tmp_uniform_space_eq.symm) /-- Continuous linear maps themselves form a seminormed space with respect to the operator norm. -/ instance to_seminormed_add_comm_group : seminormed_add_comm_group (E →SL[σ₁₂] F) := { dist_eq := continuous_linear_map.tmp_seminormed_add_comm_group.dist_eq } lemma nnnorm_def (f : E →SL[σ₁₂] F) : ‖f‖₊ = Inf {c | ∀ x, ‖f x‖₊ ≤ c * ‖x‖₊} := begin ext, rw [nnreal.coe_Inf, coe_nnnorm, norm_def, nnreal.coe_image], simp_rw [← nnreal.coe_le_coe, nnreal.coe_mul, coe_nnnorm, mem_set_of_eq, subtype.coe_mk, exists_prop], end /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_nnnorm_le_bound (f : E →SL[σ₁₂] F) (M : ℝ≥0) (hM : ∀ x, ‖f x‖₊ ≤ M * ‖x‖₊) : ‖f‖₊ ≤ M := op_norm_le_bound f (zero_le M) hM /-- If one controls the norm of every `A x`, `‖x‖₊ ≠ 0`, then one controls the norm of `A`. -/ lemma op_nnnorm_le_bound' (f : E →SL[σ₁₂] F) (M : ℝ≥0) (hM : ∀ x, ‖x‖₊ ≠ 0 → ‖f x‖₊ ≤ M * ‖x‖₊) : ‖f‖₊ ≤ M := op_norm_le_bound' f (zero_le M) $ λ x hx, hM x $ by rwa [← nnreal.coe_ne_zero] /-- For a continuous real linear map `f`, if one controls the norm of every `f x`, `‖x‖₊ = 1`, then one controls the norm of `f`. -/ lemma op_nnnorm_le_of_unit_nnnorm [normed_space ℝ E] [normed_space ℝ F] {f : E →L[ℝ] F} {C : ℝ≥0} (hf : ∀ x, ‖x‖₊ = 1 → ‖f x‖₊ ≤ C) : ‖f‖₊ ≤ C := op_norm_le_of_unit_norm C.coe_nonneg $ λ x hx, hf x $ by rwa [← nnreal.coe_eq_one] theorem op_nnnorm_le_of_lipschitz {f : E →SL[σ₁₂] F} {K : ℝ≥0} (hf : lipschitz_with K f) : ‖f‖₊ ≤ K := op_norm_le_of_lipschitz hf lemma op_nnnorm_eq_of_bounds {φ : E →SL[σ₁₂] F} (M : ℝ≥0) (h_above : ∀ x, ‖φ x‖ ≤ M*‖x‖) (h_below : ∀ N, (∀ x, ‖φ x‖₊ ≤ N*‖x‖₊) → M ≤ N) : ‖φ‖₊ = M := subtype.ext $ op_norm_eq_of_bounds (zero_le M) h_above $ subtype.forall'.mpr h_below instance to_normed_space {𝕜' : Type*} [normed_field 𝕜'] [normed_space 𝕜' F] [smul_comm_class 𝕜₂ 𝕜' F] : normed_space 𝕜' (E →SL[σ₁₂] F) := ⟨op_norm_smul_le⟩ include σ₁₃ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →SL[σ₁₂] F) : ‖h.comp f‖ ≤ ‖h‖ * ‖f‖ := (cInf_le bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) lemma op_nnnorm_comp_le [ring_hom_isometric σ₁₃] (f : E →SL[σ₁₂] F) : ‖h.comp f‖₊ ≤ ‖h‖₊ * ‖f‖₊ := op_norm_comp_le h f omit σ₁₃ /-- Continuous linear maps form a seminormed ring with respect to the operator norm. -/ instance to_semi_normed_ring : semi_normed_ring (E →L[𝕜] E) := { norm_mul := λ f g, op_norm_comp_le f g, .. continuous_linear_map.to_seminormed_add_comm_group, .. continuous_linear_map.ring } /-- For a normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra : normed_algebra 𝕜 (E →L[𝕜] E) := { .. continuous_linear_map.to_normed_space, .. continuous_linear_map.algebra } theorem le_op_nnnorm : ‖f x‖₊ ≤ ‖f‖₊ * ‖x‖₊ := f.le_op_norm x theorem nndist_le_op_nnnorm (x y : E) : nndist (f x) (f y) ≤ ‖f‖₊ * nndist x y := dist_le_op_norm f x y /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ‖f‖₊ f := add_monoid_hom_class.lipschitz_of_bound_nnnorm f _ f.le_op_nnnorm /-- Evaluation of a continuous linear map `f` at a point is Lipschitz continuous in `f`. -/ theorem lipschitz_apply (x : E) : lipschitz_with ‖x‖₊ (λ f : E →SL[σ₁₂] F, f x) := lipschitz_with_iff_norm_sub_le.2 $ λ f g, ((f - g).le_op_norm x).trans_eq (mul_comm _ _) end section Sup variables [ring_hom_isometric σ₁₂] lemma exists_mul_lt_apply_of_lt_op_nnnorm (f : E →SL[σ₁₂] F) {r : ℝ≥0} (hr : r < ‖f‖₊) : ∃ x, r * ‖x‖₊ < ‖f x‖₊ := by simpa only [not_forall, not_le, set.mem_set_of] using not_mem_of_lt_cInf (nnnorm_def f ▸ hr : r < Inf {c : ℝ≥0 | ∀ x, ‖f x‖₊ ≤ c * ‖x‖₊}) (order_bot.bdd_below _) lemma exists_mul_lt_of_lt_op_norm (f : E →SL[σ₁₂] F) {r : ℝ} (hr₀ : 0 ≤ r) (hr : r < ‖f‖) : ∃ x, r * ‖x‖ < ‖f x‖ := by { lift r to ℝ≥0 using hr₀, exact f.exists_mul_lt_apply_of_lt_op_nnnorm hr } lemma exists_lt_apply_of_lt_op_nnnorm {𝕜 𝕜₂ E F : Type*} [normed_add_comm_group E] [seminormed_add_comm_group F] [densely_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜 →+* 𝕜₂} [normed_space 𝕜 E] [normed_space 𝕜₂ F] [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) {r : ℝ≥0} (hr : r < ‖f‖₊) : ∃ x : E, ‖x‖₊ < 1 ∧ r < ‖f x‖₊ := begin obtain ⟨y, hy⟩ := f.exists_mul_lt_apply_of_lt_op_nnnorm hr, have hy' : ‖y‖₊ ≠ 0 := nnnorm_ne_zero_iff.2 (λ heq, by simpa only [heq, nnnorm_zero, map_zero, not_lt_zero'] using hy), have hfy : ‖f y‖₊ ≠ 0 := (zero_le'.trans_lt hy).ne', rw [←inv_inv (‖f y‖₊), nnreal.lt_inv_iff_mul_lt (inv_ne_zero hfy), mul_assoc, mul_comm (‖y‖₊), ←mul_assoc, ←nnreal.lt_inv_iff_mul_lt hy'] at hy, obtain ⟨k, hk₁, hk₂⟩ := normed_field.exists_lt_nnnorm_lt 𝕜 hy, refine ⟨k • y, (nnnorm_smul k y).symm ▸ (nnreal.lt_inv_iff_mul_lt hy').1 hk₂, _⟩, have : ‖σ₁₂ k‖₊ = ‖k‖₊ := subtype.ext ring_hom_isometric.is_iso, rwa [map_smulₛₗ f, nnnorm_smul, ←nnreal.div_lt_iff hfy, div_eq_mul_inv, this], end lemma exists_lt_apply_of_lt_op_norm {𝕜 𝕜₂ E F : Type*} [normed_add_comm_group E] [seminormed_add_comm_group F] [densely_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜 →+* 𝕜₂} [normed_space 𝕜 E] [normed_space 𝕜₂ F] [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) {r : ℝ} (hr : r < ‖f‖) : ∃ x : E, ‖x‖ < 1 ∧ r < ‖f x‖ := begin by_cases hr₀ : r < 0, { exact ⟨0, by simpa using hr₀⟩, }, { lift r to ℝ≥0 using not_lt.1 hr₀, exact f.exists_lt_apply_of_lt_op_nnnorm hr, } end lemma Sup_unit_ball_eq_nnnorm {𝕜 𝕜₂ E F : Type*} [normed_add_comm_group E] [seminormed_add_comm_group F] [densely_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜 →+* 𝕜₂} [normed_space 𝕜 E] [normed_space 𝕜₂ F] [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) : Sup ((λ x, ‖f x‖₊) '' ball 0 1) = ‖f‖₊ := begin refine cSup_eq_of_forall_le_of_forall_lt_exists_gt ((nonempty_ball.mpr zero_lt_one).image _) _ (λ ub hub, _), { rintro - ⟨x, hx, rfl⟩, simpa only [mul_one] using f.le_op_norm_of_le (mem_ball_zero_iff.1 hx).le }, { obtain ⟨x, hx, hxf⟩ := f.exists_lt_apply_of_lt_op_nnnorm hub, exact ⟨_, ⟨x, mem_ball_zero_iff.2 hx, rfl⟩, hxf⟩ }, end lemma Sup_unit_ball_eq_norm {𝕜 𝕜₂ E F : Type*} [normed_add_comm_group E] [seminormed_add_comm_group F] [densely_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜 →+* 𝕜₂} [normed_space 𝕜 E] [normed_space 𝕜₂ F] [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) : Sup ((λ x, ‖f x‖) '' ball 0 1) = ‖f‖ := by simpa only [nnreal.coe_Sup, set.image_image] using nnreal.coe_eq.2 f.Sup_unit_ball_eq_nnnorm lemma Sup_closed_unit_ball_eq_nnnorm {𝕜 𝕜₂ E F : Type*} [normed_add_comm_group E] [seminormed_add_comm_group F] [densely_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜 →+* 𝕜₂} [normed_space 𝕜 E] [normed_space 𝕜₂ F] [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) : Sup ((λ x, ‖f x‖₊) '' closed_ball 0 1) = ‖f‖₊ := begin have hbdd : ∀ y ∈ (λ x, ‖f x‖₊) '' closed_ball 0 1, y ≤ ‖f‖₊, { rintro - ⟨x, hx, rfl⟩, exact f.unit_le_op_norm x (mem_closed_ball_zero_iff.1 hx) }, refine le_antisymm (cSup_le ((nonempty_closed_ball.mpr zero_le_one).image _) hbdd) _, rw ←Sup_unit_ball_eq_nnnorm, exact cSup_le_cSup ⟨‖f‖₊, hbdd⟩ ((nonempty_ball.2 zero_lt_one).image _) (set.image_subset _ ball_subset_closed_ball), end lemma Sup_closed_unit_ball_eq_norm {𝕜 𝕜₂ E F : Type*} [normed_add_comm_group E] [seminormed_add_comm_group F] [densely_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜 →+* 𝕜₂} [normed_space 𝕜 E] [normed_space 𝕜₂ F] [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) : Sup ((λ x, ‖f x‖) '' closed_ball 0 1) = ‖f‖ := by simpa only [nnreal.coe_Sup, set.image_image] using nnreal.coe_eq.2 f.Sup_closed_unit_ball_eq_nnnorm end Sup section lemma op_norm_ext [ring_hom_isometric σ₁₃] (f : E →SL[σ₁₂] F) (g : E →SL[σ₁₃] G) (h : ∀ x, ‖f x‖ = ‖g x‖) : ‖f‖ = ‖g‖ := op_norm_eq_of_bounds (norm_nonneg _) (λ x, by { rw h x, exact le_op_norm _ _ }) (λ c hc h₂, op_norm_le_bound _ hc (λ z, by { rw ←h z, exact h₂ z })) variables [ring_hom_isometric σ₂₃] theorem op_norm_le_bound₂ (f : E →SL[σ₁₃] F →SL[σ₂₃] G) {C : ℝ} (h0 : 0 ≤ C) (hC : ∀ x y, ‖f x y‖ ≤ C * ‖x‖ * ‖y‖) : ‖f‖ ≤ C := f.op_norm_le_bound h0 $ λ x, (f x).op_norm_le_bound (mul_nonneg h0 (norm_nonneg _)) $ hC x theorem le_op_norm₂ [ring_hom_isometric σ₁₃] (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (x : E) (y : F) : ‖f x y‖ ≤ ‖f‖ * ‖x‖ * ‖y‖ := (f x).le_of_op_norm_le (f.le_op_norm x) y end @[simp] lemma op_norm_prod (f : E →L[𝕜] Fₗ) (g : E →L[𝕜] Gₗ) : ‖f.prod g‖ = ‖(f, g)‖ := le_antisymm (op_norm_le_bound _ (norm_nonneg _) $ λ x, by simpa only [prod_apply, prod.norm_def, max_mul_of_nonneg, norm_nonneg] using max_le_max (le_op_norm f x) (le_op_norm g x)) $ max_le (op_norm_le_bound _ (norm_nonneg _) $ λ x, (le_max_left _ _).trans ((f.prod g).le_op_norm x)) (op_norm_le_bound _ (norm_nonneg _) $ λ x, (le_max_right _ _).trans ((f.prod g).le_op_norm x)) @[simp] lemma op_nnnorm_prod (f : E →L[𝕜] Fₗ) (g : E →L[𝕜] Gₗ) : ‖f.prod g‖₊ = ‖(f, g)‖₊ := subtype.ext $ op_norm_prod f g /-- `continuous_linear_map.prod` as a `linear_isometry_equiv`. -/ def prodₗᵢ (R : Type*) [semiring R] [module R Fₗ] [module R Gₗ] [has_continuous_const_smul R Fₗ] [has_continuous_const_smul R Gₗ] [smul_comm_class 𝕜 R Fₗ] [smul_comm_class 𝕜 R Gₗ] : (E →L[𝕜] Fₗ) × (E →L[𝕜] Gₗ) ≃ₗᵢ[R] (E →L[𝕜] Fₗ × Gₗ) := ⟨prodₗ R, λ ⟨f, g⟩, op_norm_prod f g⟩ variables [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) @[simp, nontriviality] lemma op_norm_subsingleton [subsingleton E] : ‖f‖ = 0 := begin refine le_antisymm _ (norm_nonneg _), apply op_norm_le_bound _ rfl.ge, intros x, simp [subsingleton.elim x 0] end end op_norm section is_O variables [ring_hom_isometric σ₁₂] (c : 𝕜) (f g : E →SL[σ₁₂] F) (h : F →SL[σ₂₃] G) (x y z : E) open asymptotics theorem is_O_with_id (l : filter E) : is_O_with ‖f‖ l f (λ x, x) := is_O_with_of_le' _ f.le_op_norm theorem is_O_id (l : filter E) : f =O[l] (λ x, x) := (f.is_O_with_id l).is_O theorem is_O_with_comp [ring_hom_isometric σ₂₃] {α : Type*} (g : F →SL[σ₂₃] G) (f : α → F) (l : filter α) : is_O_with ‖g‖ l (λ x', g (f x')) f := (g.is_O_with_id ⊤).comp_tendsto le_top theorem is_O_comp [ring_hom_isometric σ₂₃] {α : Type*} (g : F →SL[σ₂₃] G) (f : α → F) (l : filter α) : (λ x', g (f x')) =O[l] f := (g.is_O_with_comp f l).is_O theorem is_O_with_sub (f : E →SL[σ₁₂] F) (l : filter E) (x : E) : is_O_with ‖f‖ l (λ x', f (x' - x)) (λ x', x' - x) := f.is_O_with_comp _ l theorem is_O_sub (f : E →SL[σ₁₂] F) (l : filter E) (x : E) : (λ x', f (x' - x)) =O[l] (λ x', x' - x) := f.is_O_comp _ l end is_O end continuous_linear_map namespace linear_isometry lemma norm_to_continuous_linear_map_le (f : E →ₛₗᵢ[σ₁₂] F) : ‖f.to_continuous_linear_map‖ ≤ 1 := f.to_continuous_linear_map.op_norm_le_bound zero_le_one $ λ x, by simp end linear_isometry namespace linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma mk_continuous_norm_le (f : E →ₛₗ[σ₁₂] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ‖f x‖ ≤ C * ‖x‖) : ‖f.mk_continuous C h‖ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound or zero if bound is negative. -/ lemma mk_continuous_norm_le' (f : E →ₛₗ[σ₁₂] F) {C : ℝ} (h : ∀x, ‖f x‖ ≤ C * ‖x‖) : ‖f.mk_continuous C h‖ ≤ max C 0 := continuous_linear_map.op_norm_le_bound _ (le_max_right _ _) $ λ x, (h x).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg x) variables [ring_hom_isometric σ₂₃] /-- Create a bilinear map (represented as a map `E →L[𝕜] F →L[𝕜] G`) from the corresponding linear map and a bound on the norm of the image. The linear map can be constructed using `linear_map.mk₂`. -/ def mk_continuous₂ (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) (C : ℝ) (hC : ∀ x y, ‖f x y‖ ≤ C * ‖x‖ * ‖y‖) : E →SL[σ₁₃] F →SL[σ₂₃] G := linear_map.mk_continuous { to_fun := λ x, (f x).mk_continuous (C * ‖x‖) (hC x), map_add' := λ x y, begin ext z, rw [continuous_linear_map.add_apply, mk_continuous_apply, mk_continuous_apply, mk_continuous_apply, map_add, add_apply] end, map_smul' := λ c x, begin ext z, rw [continuous_linear_map.smul_apply, mk_continuous_apply, mk_continuous_apply, map_smulₛₗ, smul_apply] end, } (max C 0) $ λ x, (mk_continuous_norm_le' _ _).trans_eq $ by rw [max_mul_of_nonneg _ _ (norm_nonneg x), zero_mul] @[simp] lemma mk_continuous₂_apply (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) {C : ℝ} (hC : ∀ x y, ‖f x y‖ ≤ C * ‖x‖ * ‖y‖) (x : E) (y : F) : f.mk_continuous₂ C hC x y = f x y := rfl lemma mk_continuous₂_norm_le' (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) {C : ℝ} (hC : ∀ x y, ‖f x y‖ ≤ C * ‖x‖ * ‖y‖) : ‖f.mk_continuous₂ C hC‖ ≤ max C 0 := mk_continuous_norm_le _ (le_max_iff.2 $ or.inr le_rfl) _ lemma mk_continuous₂_norm_le (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) {C : ℝ} (h0 : 0 ≤ C) (hC : ∀ x y, ‖f x y‖ ≤ C * ‖x‖ * ‖y‖) : ‖f.mk_continuous₂ C hC‖ ≤ C := (f.mk_continuous₂_norm_le' hC).trans_eq $ max_eq_left h0 end linear_map namespace continuous_linear_map variables [ring_hom_isometric σ₂₃] [ring_hom_isometric σ₁₃] /-- Flip the order of arguments of a continuous bilinear map. For a version bundled as `linear_isometry_equiv`, see `continuous_linear_map.flipL`. -/ def flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : F →SL[σ₂₃] E →SL[σ₁₃] G := linear_map.mk_continuous₂ (linear_map.mk₂'ₛₗ σ₂₃ σ₁₃ (λ y x, f x y) (λ x y z, (f z).map_add x y) (λ c y x, (f x).map_smulₛₗ c y) (λ z x y, by rw [f.map_add, add_apply]) (λ c y x, by rw [f.map_smulₛₗ, smul_apply])) ‖f‖ (λ y x, (f.le_op_norm₂ x y).trans_eq $ by rw mul_right_comm) private lemma le_norm_flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : ‖f‖ ≤ ‖flip f‖ := f.op_norm_le_bound₂ (norm_nonneg _) $ λ x y, by { rw mul_right_comm, exact (flip f).le_op_norm₂ y x } @[simp] lemma flip_apply (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (x : E) (y : F) : f.flip y x = f x y := rfl @[simp] lemma flip_flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : f.flip.flip = f := by { ext, refl } @[simp] lemma op_norm_flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : ‖f.flip‖ = ‖f‖ := le_antisymm (by simpa only [flip_flip] using le_norm_flip f.flip) (le_norm_flip f) @[simp] lemma flip_add (f g : E →SL[σ₁₃] F →SL[σ₂₃] G) : (f + g).flip = f.flip + g.flip := rfl @[simp] lemma flip_smul (c : 𝕜₃) (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : (c • f).flip = c • f.flip := rfl variables (E F G σ₁₃ σ₂₃) /-- Flip the order of arguments of a continuous bilinear map. This is a version bundled as a `linear_isometry_equiv`. For an unbundled version see `continuous_linear_map.flip`. -/ def flipₗᵢ' : (E →SL[σ₁₃] F →SL[σ₂₃] G) ≃ₗᵢ[𝕜₃] (F →SL[σ₂₃] E →SL[σ₁₃] G) := { to_fun := flip, inv_fun := flip, map_add' := flip_add, map_smul' := flip_smul, left_inv := flip_flip, right_inv := flip_flip, norm_map' := op_norm_flip } variables {E F G σ₁₃ σ₂₃} @[simp] lemma flipₗᵢ'_symm : (flipₗᵢ' E F G σ₂₃ σ₁₃).symm = flipₗᵢ' F E G σ₁₃ σ₂₃ := rfl @[simp] lemma coe_flipₗᵢ' : ⇑(flipₗᵢ' E F G σ₂₃ σ₁₃) = flip := rfl variables (𝕜 E Fₗ Gₗ) /-- Flip the order of arguments of a continuous bilinear map. This is a version bundled as a `linear_isometry_equiv`. For an unbundled version see `continuous_linear_map.flip`. -/ def flipₗᵢ : (E →L[𝕜] Fₗ →L[𝕜] Gₗ) ≃ₗᵢ[𝕜] (Fₗ →L[𝕜] E →L[𝕜] Gₗ) := { to_fun := flip, inv_fun := flip, map_add' := flip_add, map_smul' := flip_smul, left_inv := flip_flip, right_inv := flip_flip, norm_map' := op_norm_flip } variables {𝕜 E Fₗ Gₗ} @[simp] lemma flipₗᵢ_symm : (flipₗᵢ 𝕜 E Fₗ Gₗ).symm = flipₗᵢ 𝕜 Fₗ E Gₗ := rfl @[simp] lemma coe_flipₗᵢ : ⇑(flipₗᵢ 𝕜 E Fₗ Gₗ) = flip := rfl variables (F σ₁₂) [ring_hom_isometric σ₁₂] /-- The continuous semilinear map obtained by applying a continuous semilinear map at a given vector. This is the continuous version of `linear_map.applyₗ`. -/ def apply' : E →SL[σ₁₂] (E →SL[σ₁₂] F) →L[𝕜₂] F := flip (id 𝕜₂ (E →SL[σ₁₂] F)) variables {F σ₁₂} @[simp] lemma apply_apply' (v : E) (f : E →SL[σ₁₂] F) : apply' F σ₁₂ v f = f v := rfl variables (𝕜 Fₗ) /-- The continuous semilinear map obtained by applying a continuous semilinear map at a given vector. This is the continuous version of `linear_map.applyₗ`. -/ def apply : E →L[𝕜] (E →L[𝕜] Fₗ) →L[𝕜] Fₗ := flip (id 𝕜 (E →L[𝕜] Fₗ)) variables {𝕜 Fₗ} @[simp] lemma apply_apply (v : E) (f : E →L[𝕜] Fₗ) : apply 𝕜 Fₗ v f = f v := rfl variables (σ₁₂ σ₂₃ E F G) /-- Composition of continuous semilinear maps as a continuous semibilinear map. -/ def compSL : (F →SL[σ₂₃] G) →L[𝕜₃] (E →SL[σ₁₂] F) →SL[σ₂₃] (E →SL[σ₁₃] G) := linear_map.mk_continuous₂ (linear_map.mk₂'ₛₗ (ring_hom.id 𝕜₃) σ₂₃ comp add_comp smul_comp comp_add (λ c f g, by { ext, simp only [continuous_linear_map.map_smulₛₗ, coe_smul', coe_comp', function.comp_app, pi.smul_apply] })) 1 $ λ f g, by simpa only [one_mul] using op_norm_comp_le f g include σ₁₃ lemma norm_compSL_le : ‖compSL E F G σ₁₂ σ₂₃‖ ≤ 1 := linear_map.mk_continuous₂_norm_le _ zero_le_one _ variables {𝕜 σ₁₂ σ₂₃ E F G} @[simp] lemma compSL_apply (f : F →SL[σ₂₃] G) (g : E →SL[σ₁₂] F) : compSL E F G σ₁₂ σ₂₃ f g = f.comp g := rfl lemma _root_.continuous.const_clm_comp {X} [topological_space X] {f : X → E →SL[σ₁₂] F} (hf : continuous f) (g : F →SL[σ₂₃] G) : continuous (λ x, g.comp (f x) : X → E →SL[σ₁₃] G) := (compSL E F G σ₁₂ σ₂₃ g).continuous.comp hf -- Giving the implicit argument speeds up elaboration significantly lemma _root_.continuous.clm_comp_const {X} [topological_space X] {g : X → F →SL[σ₂₃] G} (hg : continuous g) (f : E →SL[σ₁₂] F) : continuous (λ x, (g x).comp f : X → E →SL[σ₁₃] G) := (@continuous_linear_map.flip _ _ _ _ _ (E →SL[σ₁₃] G) _ _ _ _ _ _ _ _ _ _ _ _ _ (compSL E F G σ₁₂ σ₂₃) f).continuous.comp hg omit σ₁₃ variables (𝕜 σ₁₂ σ₂₃ E Fₗ Gₗ) /-- Composition of continuous linear maps as a continuous bilinear map. -/ def compL : (Fₗ →L[𝕜] Gₗ) →L[𝕜] (E →L[𝕜] Fₗ) →L[𝕜] (E →L[𝕜] Gₗ) := compSL E Fₗ Gₗ (ring_hom.id 𝕜) (ring_hom.id 𝕜) lemma norm_compL_le : ‖compL 𝕜 E Fₗ Gₗ‖ ≤ 1 := norm_compSL_le _ _ _ _ _ @[simp] lemma compL_apply (f : Fₗ →L[𝕜] Gₗ) (g : E →L[𝕜] Fₗ) : compL 𝕜 E Fₗ Gₗ f g = f.comp g := rfl variables (Eₗ) {𝕜 E Fₗ Gₗ} /-- Apply `L(x,-)` pointwise to bilinear maps, as a continuous bilinear map -/ @[simps apply] def precompR (L : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : E →L[𝕜] (Eₗ →L[𝕜] Fₗ) →L[𝕜] (Eₗ →L[𝕜] Gₗ) := (compL 𝕜 Eₗ Fₗ Gₗ).comp L /-- Apply `L(-,y)` pointwise to bilinear maps, as a continuous bilinear map -/ def precompL (L : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : (Eₗ →L[𝕜] E) →L[𝕜] Fₗ →L[𝕜] (Eₗ →L[𝕜] Gₗ) := (precompR Eₗ (flip L)).flip lemma norm_precompR_le (L : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : ‖precompR Eₗ L‖ ≤ ‖L‖ := calc ‖precompR Eₗ L‖ ≤ ‖compL 𝕜 Eₗ Fₗ Gₗ‖ * ‖L‖ : op_norm_comp_le _ _ ... ≤ 1 * ‖L‖ : mul_le_mul_of_nonneg_right (norm_compL_le _ _ _ _) (norm_nonneg _) ... = ‖L‖ : by rw one_mul lemma norm_precompL_le (L : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : ‖precompL Eₗ L‖ ≤ ‖L‖ := by { rw [precompL, op_norm_flip, ← op_norm_flip L], exact norm_precompR_le _ L.flip } section prod universes u₁ u₂ u₃ u₄ variables (M₁ : Type u₁) [seminormed_add_comm_group M₁] [normed_space 𝕜 M₁] (M₂ : Type u₂) [seminormed_add_comm_group M₂] [normed_space 𝕜 M₂] (M₃ : Type u₃) [seminormed_add_comm_group M₃] [normed_space 𝕜 M₃] (M₄ : Type u₄) [seminormed_add_comm_group M₄] [normed_space 𝕜 M₄] variables {Eₗ} (𝕜) /-- `continuous_linear_map.prod_map` as a continuous linear map. -/ def prod_mapL : ((M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) →L[𝕜] ((M₁ × M₃) →L[𝕜] (M₂ × M₄)) := continuous_linear_map.copy (have Φ₁ : (M₁ →L[𝕜] M₂) →L[𝕜] (M₁ →L[𝕜] M₂ × M₄), from continuous_linear_map.compL 𝕜 M₁ M₂ (M₂ × M₄) (continuous_linear_map.inl 𝕜 M₂ M₄), have Φ₂ : (M₃ →L[𝕜] M₄) →L[𝕜] (M₃ →L[𝕜] M₂ × M₄), from continuous_linear_map.compL 𝕜 M₃ M₄ (M₂ × M₄) (continuous_linear_map.inr 𝕜 M₂ M₄), have Φ₁' : _, from (continuous_linear_map.compL 𝕜 (M₁ × M₃) M₁ (M₂ × M₄)).flip (continuous_linear_map.fst 𝕜 M₁ M₃), have Φ₂' : _ , from (continuous_linear_map.compL 𝕜 (M₁ × M₃) M₃ (M₂ × M₄)).flip (continuous_linear_map.snd 𝕜 M₁ M₃), have Ψ₁ : ((M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) →L[𝕜] (M₁ →L[𝕜] M₂), from continuous_linear_map.fst 𝕜 (M₁ →L[𝕜] M₂) (M₃ →L[𝕜] M₄), have Ψ₂ : ((M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) →L[𝕜] (M₃ →L[𝕜] M₄), from continuous_linear_map.snd 𝕜 (M₁ →L[𝕜] M₂) (M₃ →L[𝕜] M₄), Φ₁' ∘L Φ₁ ∘L Ψ₁ + Φ₂' ∘L Φ₂ ∘L Ψ₂) (λ p : (M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄), p.1.prod_map p.2) (begin apply funext, rintros ⟨φ, ψ⟩, apply continuous_linear_map.ext (λ x, _), simp only [add_apply, coe_comp', coe_fst', function.comp_app, compL_apply, flip_apply, coe_snd', inl_apply, inr_apply, prod.mk_add_mk, add_zero, zero_add, coe_prod_map', prod_map, prod.mk.inj_iff, eq_self_iff_true, and_self], refl end) variables {M₁ M₂ M₃ M₄} @[simp] lemma prod_mapL_apply (p : (M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) : continuous_linear_map.prod_mapL 𝕜 M₁ M₂ M₃ M₄ p = p.1.prod_map p.2 := rfl variables {X : Type*} [topological_space X] lemma _root_.continuous.prod_mapL {f : X → M₁ →L[𝕜] M₂} {g : X → M₃ →L[𝕜] M₄} (hf : continuous f) (hg : continuous g) : continuous (λ x, (f x).prod_map (g x)) := (prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp (hf.prod_mk hg) lemma _root_.continuous.prod_map_equivL {f : X → M₁ ≃L[𝕜] M₂} {g : X → M₃ ≃L[𝕜] M₄} (hf : continuous (λ x, (f x : M₁ →L[𝕜] M₂))) (hg : continuous (λ x, (g x : M₃ →L[𝕜] M₄))) : continuous (λ x, ((f x).prod (g x) : M₁ × M₃ →L[𝕜] M₂ × M₄)) := (prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp (hf.prod_mk hg) lemma _root_.continuous_on.prod_mapL {f : X → M₁ →L[𝕜] M₂} {g : X → M₃ →L[𝕜] M₄} {s : set X} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ x, (f x).prod_map (g x)) s := ((prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp_continuous_on (hf.prod hg) : _) lemma _root_.continuous_on.prod_map_equivL {f : X → M₁ ≃L[𝕜] M₂} {g : X → M₃ ≃L[𝕜] M₄} {s : set X} (hf : continuous_on (λ x, (f x : M₁ →L[𝕜] M₂)) s) (hg : continuous_on (λ x, (g x : M₃ →L[𝕜] M₄)) s) : continuous_on (λ x, ((f x).prod (g x) : M₁ × M₃ →L[𝕜] M₂ × M₄)) s := (prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp_continuous_on (hf.prod hg) end prod variables {𝕜 E Fₗ Gₗ} section multiplication_linear section non_unital variables (𝕜) (𝕜' : Type*) [non_unital_semi_normed_ring 𝕜'] [normed_space 𝕜 𝕜'] [is_scalar_tower 𝕜 𝕜' 𝕜'] [smul_comm_class 𝕜 𝕜' 𝕜'] /-- Multiplication in a non-unital normed algebra as a continuous bilinear map. -/ def mul : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := (linear_map.mul 𝕜 𝕜').mk_continuous₂ 1 $ λ x y, by simpa using norm_mul_le x y @[simp] lemma mul_apply' (x y : 𝕜') : mul 𝕜 𝕜' x y = x * y := rfl @[simp] lemma op_norm_mul_apply_le (x : 𝕜') : ‖mul 𝕜 𝕜' x‖ ≤ ‖x‖ := (op_norm_le_bound _ (norm_nonneg x) (norm_mul_le x)) lemma op_norm_mul_le : ‖mul 𝕜 𝕜'‖ ≤ 1 := linear_map.mk_continuous₂_norm_le _ zero_le_one _ /-- Simultaneous left- and right-multiplication in a non-unital normed algebra, considered as a continuous trilinear map. This is akin to its non-continuous version `linear_map.mul_left_right`, but there is a minor difference: `linear_map.mul_left_right` is uncurried. -/ def mul_left_right : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := ((compL 𝕜 𝕜' 𝕜' 𝕜').comp (mul 𝕜 𝕜').flip).flip.comp (mul 𝕜 𝕜') @[simp] lemma mul_left_right_apply (x y z : 𝕜') : mul_left_right 𝕜 𝕜' x y z = x * z * y := rfl lemma op_norm_mul_left_right_apply_apply_le (x y : 𝕜') : ‖mul_left_right 𝕜 𝕜' x y‖ ≤ ‖x‖ * ‖y‖ := (op_norm_comp_le _ _).trans $ (mul_comm _ _).trans_le $ mul_le_mul (op_norm_mul_apply_le _ _ _) (op_norm_le_bound _ (norm_nonneg _) (λ _, (norm_mul_le _ _).trans_eq (mul_comm _ _))) (norm_nonneg _) (norm_nonneg _) lemma op_norm_mul_left_right_apply_le (x : 𝕜') : ‖mul_left_right 𝕜 𝕜' x‖ ≤ ‖x‖ := op_norm_le_bound _ (norm_nonneg x) (op_norm_mul_left_right_apply_apply_le 𝕜 𝕜' x) lemma op_norm_mul_left_right_le : ‖mul_left_right 𝕜 𝕜'‖ ≤ 1 := op_norm_le_bound _ zero_le_one (λ x, (one_mul ‖x‖).symm ▸ op_norm_mul_left_right_apply_le 𝕜 𝕜' x) end non_unital section unital variables (𝕜) (𝕜' : Type*) [semi_normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] [norm_one_class 𝕜'] /-- Multiplication in a normed algebra as a linear isometry to the space of continuous linear maps. -/ def mulₗᵢ : 𝕜' →ₗᵢ[𝕜] 𝕜' →L[𝕜] 𝕜' := { to_linear_map := mul 𝕜 𝕜', norm_map' := λ x, le_antisymm (op_norm_mul_apply_le _ _ _) (by { convert ratio_le_op_norm _ (1 : 𝕜'), simp [norm_one], apply_instance }) } @[simp] lemma coe_mulₗᵢ : ⇑(mulₗᵢ 𝕜 𝕜') = mul 𝕜 𝕜' := rfl @[simp] lemma op_norm_mul_apply (x : 𝕜') : ‖mul 𝕜 𝕜' x‖ = ‖x‖ := (mulₗᵢ 𝕜 𝕜').norm_map x end unital end multiplication_linear section smul_linear variables (𝕜) (𝕜' : Type*) [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] /-- Scalar multiplication as a continuous bilinear map. -/ def lsmul : 𝕜' →L[𝕜] E →L[𝕜] E := ((algebra.lsmul 𝕜 E).to_linear_map : 𝕜' →ₗ[𝕜] E →ₗ[𝕜] E).mk_continuous₂ 1 $ λ c x, by simpa only [one_mul] using norm_smul_le c x @[simp] lemma lsmul_apply (c : 𝕜') (x : E) : lsmul 𝕜 𝕜' c x = c • x := rfl variables {𝕜'} lemma norm_to_span_singleton (x : E) : ‖to_span_singleton 𝕜 x‖ = ‖x‖ := begin refine op_norm_eq_of_bounds (norm_nonneg _) (λ x, _) (λ N hN_nonneg h, _), { rw [to_span_singleton_apply, norm_smul, mul_comm], }, { specialize h 1, rw [to_span_singleton_apply, norm_smul, mul_comm] at h, exact (mul_le_mul_right (by simp)).mp h, }, end variables {𝕜} lemma op_norm_lsmul_apply_le (x : 𝕜') : ‖(lsmul 𝕜 𝕜' x : E →L[𝕜] E)‖ ≤ ‖x‖ := continuous_linear_map.op_norm_le_bound _ (norm_nonneg x) $ λ y, norm_smul_le x y /-- The norm of `lsmul` is at most 1 in any semi-normed group. -/ lemma op_norm_lsmul_le : ‖(lsmul 𝕜 𝕜' : 𝕜' →L[𝕜] E →L[𝕜] E)‖ ≤ 1 := begin refine continuous_linear_map.op_norm_le_bound _ zero_le_one (λ x, _), simp_rw [one_mul], exact op_norm_lsmul_apply_le _, end end smul_linear section restrict_scalars variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] variables [normed_space 𝕜' E] [is_scalar_tower 𝕜' 𝕜 E] variables [normed_space 𝕜' Fₗ] [is_scalar_tower 𝕜' 𝕜 Fₗ] @[simp] lemma norm_restrict_scalars (f : E →L[𝕜] Fₗ) : ‖f.restrict_scalars 𝕜'‖ = ‖f‖ := le_antisymm (op_norm_le_bound _ (norm_nonneg _) $ λ x, f.le_op_norm x) (op_norm_le_bound _ (norm_nonneg _) $ λ x, f.le_op_norm x) variables (𝕜 E Fₗ 𝕜') (𝕜'' : Type*) [ring 𝕜''] [module 𝕜'' Fₗ] [has_continuous_const_smul 𝕜'' Fₗ] [smul_comm_class 𝕜 𝕜'' Fₗ] [smul_comm_class 𝕜' 𝕜'' Fₗ] /-- `continuous_linear_map.restrict_scalars` as a `linear_isometry`. -/ def restrict_scalars_isometry : (E →L[𝕜] Fₗ) →ₗᵢ[𝕜''] (E →L[𝕜'] Fₗ) := ⟨restrict_scalarsₗ 𝕜 E Fₗ 𝕜' 𝕜'', norm_restrict_scalars⟩ variables {𝕜 E Fₗ 𝕜' 𝕜''} @[simp] lemma coe_restrict_scalars_isometry : ⇑(restrict_scalars_isometry 𝕜 E Fₗ 𝕜' 𝕜'') = restrict_scalars 𝕜' := rfl @[simp] lemma restrict_scalars_isometry_to_linear_map : (restrict_scalars_isometry 𝕜 E Fₗ 𝕜' 𝕜'').to_linear_map = restrict_scalarsₗ 𝕜 E Fₗ 𝕜' 𝕜'' := rfl variables (𝕜 E Fₗ 𝕜' 𝕜'') /-- `continuous_linear_map.restrict_scalars` as a `continuous_linear_map`. -/ def restrict_scalarsL : (E →L[𝕜] Fₗ) →L[𝕜''] (E →L[𝕜'] Fₗ) := (restrict_scalars_isometry 𝕜 E Fₗ 𝕜' 𝕜'').to_continuous_linear_map variables {𝕜 E Fₗ 𝕜' 𝕜''} @[simp] lemma coe_restrict_scalarsL : (restrict_scalarsL 𝕜 E Fₗ 𝕜' 𝕜'' : (E →L[𝕜] Fₗ) →ₗ[𝕜''] (E →L[𝕜'] Fₗ)) = restrict_scalarsₗ 𝕜 E Fₗ 𝕜' 𝕜'' := rfl @[simp] lemma coe_restrict_scalarsL' : ⇑(restrict_scalarsL 𝕜 E Fₗ 𝕜' 𝕜'') = restrict_scalars 𝕜' := rfl end restrict_scalars end continuous_linear_map namespace submodule lemma norm_subtypeL_le (K : submodule 𝕜 E) : ‖K.subtypeL‖ ≤ 1 := K.subtypeₗᵢ.norm_to_continuous_linear_map_le end submodule namespace continuous_linear_equiv section variables {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] [ring_hom_isometric σ₁₂] variables (e : E ≃SL[σ₁₂] F) include σ₂₁ protected lemma lipschitz : lipschitz_with (‖(e : E →SL[σ₁₂] F)‖₊) e := (e : E →SL[σ₁₂] F).lipschitz theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : (λ x', e (f x')) =O[l] f := (e : E →SL[σ₁₂] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : (λ x', e (x' - x)) =O[l] (λ x', x' - x) := (e : E →SL[σ₁₂] F).is_O_sub l x end variables {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] variables [ring_hom_isometric σ₂₁] (e : E ≃SL[σ₁₂] F) include σ₂₁ theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : f =O[l] (λ x', e (f x')) := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : (λ x', x' - x) =O[l] (λ x', e (x' - x)) := e.is_O_comp_rev _ _ end continuous_linear_equiv variables {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] namespace continuous_linear_map variables {E' F' : Type*} [seminormed_add_comm_group E'] [seminormed_add_comm_group F'] variables {𝕜₁' : Type*} {𝕜₂' : Type*} [nontrivially_normed_field 𝕜₁'] [nontrivially_normed_field 𝕜₂'] [normed_space 𝕜₁' E'] [normed_space 𝕜₂' F'] {σ₁' : 𝕜₁' →+* 𝕜} {σ₁₃' : 𝕜₁' →+* 𝕜₃} {σ₂' : 𝕜₂' →+* 𝕜₂} {σ₂₃' : 𝕜₂' →+* 𝕜₃} [ring_hom_comp_triple σ₁' σ₁₃ σ₁₃'] [ring_hom_comp_triple σ₂' σ₂₃ σ₂₃'] [ring_hom_isometric σ₂₃] [ring_hom_isometric σ₁₃'] [ring_hom_isometric σ₂₃'] /-- Compose a bilinear map `E →SL[σ₁₃] F →SL[σ₂₃] G` with two linear maps `E' →SL[σ₁'] E` and `F' →SL[σ₂'] F`. -/ def bilinear_comp (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (gE : E' →SL[σ₁'] E) (gF : F' →SL[σ₂'] F) : E' →SL[σ₁₃'] F' →SL[σ₂₃'] G := ((f.comp gE).flip.comp gF).flip include σ₁₃' σ₂₃' @[simp] lemma bilinear_comp_apply (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (gE : E' →SL[σ₁'] E) (gF : F' →SL[σ₂'] F) (x : E') (y : F') : f.bilinear_comp gE gF x y = f (gE x) (gF y) := rfl omit σ₁₃' σ₂₃' variables [ring_hom_isometric σ₁₃] [ring_hom_isometric σ₁'] [ring_hom_isometric σ₂'] /-- Derivative of a continuous bilinear map `f : E →L[𝕜] F →L[𝕜] G` interpreted as a map `E × F → G` at point `p : E × F` evaluated at `q : E × F`, as a continuous bilinear map. -/ def deriv₂ (f : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : (E × Fₗ) →L[𝕜] (E × Fₗ) →L[𝕜] Gₗ := f.bilinear_comp (fst _ _ _) (snd _ _ _) + f.flip.bilinear_comp (snd _ _ _) (fst _ _ _) @[simp] lemma coe_deriv₂ (f : E →L[𝕜] Fₗ →L[𝕜] Gₗ) (p : E × Fₗ) : ⇑(f.deriv₂ p) = λ q : E × Fₗ, f p.1 q.2 + f q.1 p.2 := rfl lemma map_add_add (f : E →L[𝕜] Fₗ →L[𝕜] Gₗ) (x x' : E) (y y' : Fₗ) : f (x + x') (y + y') = f x y + f.deriv₂ (x, y) (x', y') + f x' y' := by simp only [map_add, add_apply, coe_deriv₂, add_assoc] end continuous_linear_map end semi_normed section normed variables [normed_add_comm_group E] [normed_add_comm_group F] [normed_add_comm_group G] [normed_add_comm_group Fₗ] open metric continuous_linear_map section variables [nontrivially_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] [nontrivially_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] [normed_space 𝕜₃ G] [normed_space 𝕜 Fₗ] (c : 𝕜) {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₃ : 𝕜₂ →+* 𝕜₃} (f g : E →SL[σ₁₂] F) (x y z : E) namespace linear_map lemma bound_of_shell [ring_hom_isometric σ₁₂] (f : E →ₛₗ[σ₁₂] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ‖c‖) (hf : ∀ x, ε / ‖c‖ ≤ ‖x‖ → ‖x‖ < ε → ‖f x‖ ≤ C * ‖x‖) (x : E) : ‖f x‖ ≤ C * ‖x‖ := begin by_cases hx : x = 0, { simp [hx] }, exact semilinear_map_class.bound_of_shell_semi_normed f ε_pos hc hf (ne_of_lt (norm_pos_iff.2 hx)).symm end /-- `linear_map.bound_of_ball_bound'` is a version of this lemma over a field satisfying `is_R_or_C` that produces a concrete bound. -/ lemma bound_of_ball_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] Fₗ) (h : ∀ z ∈ metric.ball (0 : E) r, ‖f z‖ ≤ c) : ∃ C, ∀ (z : E), ‖f z‖ ≤ C * ‖z‖ := begin cases @nontrivially_normed_field.non_trivial 𝕜 _ with k hk, use c * (‖k‖ / r), intro z, refine bound_of_shell _ r_pos hk (λ x hko hxo, _) _, calc ‖f x‖ ≤ c : h _ (mem_ball_zero_iff.mpr hxo) ... ≤ c * ((‖x‖ * ‖k‖) / r) : le_mul_of_one_le_right _ _ ... = _ : by ring, { exact le_trans (norm_nonneg _) (h 0 (by simp [r_pos])) }, { rw [div_le_iff (zero_lt_one.trans hk)] at hko, exact (one_le_div r_pos).mpr hko } end lemma antilipschitz_of_comap_nhds_le [h : ring_hom_isometric σ₁₂] (f : E →ₛₗ[σ₁₂] F) (hf : (𝓝 0).comap f ≤ 𝓝 0) : ∃ K, antilipschitz_with K f := begin rcases ((nhds_basis_ball.comap _).le_basis_iff nhds_basis_ball).1 hf 1 one_pos with ⟨ε, ε0, hε⟩, simp only [set.subset_def, set.mem_preimage, mem_ball_zero_iff] at hε, lift ε to ℝ≥0 using ε0.le, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨ε⁻¹ * ‖c‖₊, add_monoid_hom_class.antilipschitz_of_bound f $ λ x, _⟩, by_cases hx : f x = 0, { rw [← hx] at hf, obtain rfl : x = 0 := specializes.eq (specializes_iff_pure.2 $ ((filter.tendsto_pure_pure _ _).mono_right (pure_le_nhds _)).le_comap.trans hf), exact norm_zero.trans_le (mul_nonneg (nnreal.coe_nonneg _) (norm_nonneg _)) }, have hc₀ : c ≠ 0 := norm_pos_iff.1 (one_pos.trans hc), rw [← h.1] at hc, rcases rescale_to_shell_zpow hc ε0 hx with ⟨n, -, hlt, -, hle⟩, simp only [← map_zpow₀, h.1, ← map_smulₛₗ] at hlt hle, calc ‖x‖ = ‖c ^ n‖⁻¹ * ‖c ^ n • x‖ : by rwa [← norm_inv, ← norm_smul, inv_smul_smul₀ (zpow_ne_zero _ _)] ... ≤ ‖c ^ n‖⁻¹ * 1 : mul_le_mul_of_nonneg_left (hε _ hlt).le (inv_nonneg.2 (norm_nonneg _)) ... ≤ ε⁻¹ * ‖c‖ * ‖f x‖ : by rwa [mul_one] end end linear_map namespace continuous_linear_map section op_norm open set real /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff [ring_hom_isometric σ₁₂] : ‖f‖ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ‖f‖ * ‖x‖ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (by { rintro rfl, exact op_norm_zero }) /-- If a normed space is non-trivial, then the norm of the identity equals `1`. -/ @[simp] lemma norm_id [nontrivial E] : ‖id 𝕜 E‖ = 1 := begin refine norm_id_of_nontrivial_seminorm _, obtain ⟨x, hx⟩ := exists_ne (0 : E), exact ⟨x, ne_of_gt (norm_pos_iff.2 hx)⟩, end instance norm_one_class [nontrivial E] : norm_one_class (E →L[𝕜] E) := ⟨norm_id⟩ /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_add_comm_group [ring_hom_isometric σ₁₂] : normed_add_comm_group (E →SL[σ₁₂] F) := normed_add_comm_group.of_separation (λ f, (op_norm_zero_iff f).mp) /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { .. continuous_linear_map.to_normed_add_comm_group, .. continuous_linear_map.to_semi_normed_ring } variable {f} lemma homothety_norm [ring_hom_isometric σ₁₂] [nontrivial E] (f : E →SL[σ₁₂] F) {a : ℝ} (hf : ∀x, ‖f x‖ = a * ‖x‖) : ‖f‖ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, rw ← norm_pos_iff at hx, have ha : 0 ≤ a, by simpa only [hf, hx, zero_le_mul_right] using norm_nonneg (f x), apply le_antisymm (f.op_norm_le_bound ha (λ y, le_of_eq (hf y))), simpa only [hf, hx, mul_le_mul_right] using f.le_op_norm x, end variable (f) /-- If a continuous linear map is a topology embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_embedding (f : E →L[𝕜] Fₗ) (hf : embedding f) : ∃ K, antilipschitz_with K f := f.to_linear_map.antilipschitz_of_comap_nhds_le $ map_zero f ▸ (hf.nhds_eq_comap 0).ge section completeness open_locale topology open filter variables {E' : Type*} [seminormed_add_comm_group E'] [normed_space 𝕜 E'] [ring_hom_isometric σ₁₂] /-- Construct a bundled continuous (semi)linear map from a map `f : E → F` and a proof of the fact that it belongs to the closure of the image of a bounded set `s : set (E →SL[σ₁₂] F)` under coercion to function. Coercion to function of the result is definitionally equal to `f`. -/ @[simps apply { fully_applied := ff }] def of_mem_closure_image_coe_bounded (f : E' → F) {s : set (E' →SL[σ₁₂] F)} (hs : bounded s) (hf : f ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s)) : E' →SL[σ₁₂] F := begin -- `f` is a linear map due to `linear_map_of_mem_closure_range_coe` refine (linear_map_of_mem_closure_range_coe f _).mk_continuous_of_exists_bound _, { refine closure_mono (image_subset_iff.2 $ λ g hg, _) hf, exact ⟨g, rfl⟩ }, { -- We need to show that `f` has bounded norm. Choose `C` such that `‖g‖ ≤ C` for all `g ∈ s`. rcases bounded_iff_forall_norm_le.1 hs with ⟨C, hC⟩, -- Then `‖g x‖ ≤ C * ‖x‖` for all `g ∈ s`, `x : E`, hence `‖f x‖ ≤ C * ‖x‖` for all `x`. have : ∀ x, is_closed {g : E' → F | ‖g x‖ ≤ C * ‖x‖}, from λ x, is_closed_Iic.preimage (@continuous_apply E' (λ _, F) _ x).norm, refine ⟨C, λ x, (this x).closure_subset_iff.2 (image_subset_iff.2 $ λ g hg, _) hf⟩, exact g.le_of_op_norm_le (hC _ hg) _ } end /-- Let `f : E → F` be a map, let `g : α → E →SL[σ₁₂] F` be a family of continuous (semi)linear maps that takes values in a bounded set and converges to `f` pointwise along a nontrivial filter. Then `f` is a continuous (semi)linear map. -/ @[simps apply { fully_applied := ff }] def of_tendsto_of_bounded_range {α : Type*} {l : filter α} [l.ne_bot] (f : E' → F) (g : α → E' →SL[σ₁₂] F) (hf : tendsto (λ a x, g a x) l (𝓝 f)) (hg : bounded (set.range g)) : E' →SL[σ₁₂] F := of_mem_closure_image_coe_bounded f hg $ mem_closure_of_tendsto hf $ eventually_of_forall $ λ a, mem_image_of_mem _ $ set.mem_range_self _ /-- If a Cauchy sequence of continuous linear map converges to a continuous linear map pointwise, then it converges to the same map in norm. This lemma is used to prove that the space of continuous linear maps is complete provided that the codomain is a complete space. -/ lemma tendsto_of_tendsto_pointwise_of_cauchy_seq {f : ℕ → E' →SL[σ₁₂] F} {g : E' →SL[σ₁₂] F} (hg : tendsto (λ n x, f n x) at_top (𝓝 g)) (hf : cauchy_seq f) : tendsto f at_top (𝓝 g) := begin /- Since `f` is a Cauchy sequence, there exists `b → 0` such that `‖f n - f m‖ ≤ b N` for any `m, n ≥ N`. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, hb₀, hfb, hb_lim⟩, -- Since `b → 0`, it suffices to show that `‖f n x - g x‖ ≤ b n * ‖x‖` for all `n` and `x`. suffices : ∀ n x, ‖f n x - g x‖ ≤ b n * ‖x‖, from tendsto_iff_norm_tendsto_zero.2 (squeeze_zero (λ n, norm_nonneg _) (λ n, op_norm_le_bound _ (hb₀ n) (this n)) hb_lim), intros n x, -- Note that `f m x → g x`, hence `‖f n x - f m x‖ → ‖f n x - g x‖` as `m → ∞` have : tendsto (λ m, ‖f n x - f m x‖) at_top (𝓝 (‖f n x - g x‖)), from (tendsto_const_nhds.sub $ tendsto_pi_nhds.1 hg _).norm, -- Thus it suffices to verify `‖f n x - f m x‖ ≤ b n * ‖x‖` for `m ≥ n`. refine le_of_tendsto this (eventually_at_top.2 ⟨n, λ m hm, _⟩), -- This inequality follows from `‖f n - f m‖ ≤ b n`. exact (f n - f m).le_of_op_norm_le (hfb _ _ _ le_rfl hm) _ end /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. This works also if the source space is seminormed. -/ instance [complete_space F] : complete_space (E' →SL[σ₁₂] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- The evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), from λ v, hf.map (lipschitz_apply v).uniform_continuous, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is a continuous linear map. -- This is done in `continuous_linear_map.of_tendsto_of_bounded_range`. set Glin : E' →SL[σ₁₂] F := of_tendsto_of_bounded_range _ _ (tendsto_pi_nhds.mpr hG) hf.bounded_range, -- Finally, `f n` converges to `Glin` in norm because of -- `continuous_linear_map.tendsto_of_tendsto_pointwise_of_cauchy_seq` exact ⟨Glin, tendsto_of_tendsto_pointwise_of_cauchy_seq (tendsto_pi_nhds.2 hG) hf⟩ end /-- Let `s` be a bounded set in the space of continuous (semi)linear maps `E →SL[σ] F` taking values in a proper space. Then `s` interpreted as a set in the space of maps `E → F` with topology of pointwise convergence is precompact: its closure is a compact set. -/ lemma is_compact_closure_image_coe_of_bounded [proper_space F] {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) : is_compact (closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s)) := have ∀ x, is_compact (closure (apply' F σ₁₂ x '' s)), from λ x, ((apply' F σ₁₂ x).lipschitz.bounded_image hb).is_compact_closure, is_compact_closure_of_subset_compact (is_compact_pi_infinite this) (image_subset_iff.2 $ λ g hg x, subset_closure $ mem_image_of_mem _ hg) /-- Let `s` be a bounded set in the space of continuous (semi)linear maps `E →SL[σ] F` taking values in a proper space. If `s` interpreted as a set in the space of maps `E → F` with topology of pointwise convergence is closed, then it is compact. TODO: reformulate this in terms of a type synonym with the right topology. -/ lemma is_compact_image_coe_of_bounded_of_closed_image [proper_space F] {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) (hc : is_closed ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s)) : is_compact ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) := hc.closure_eq ▸ is_compact_closure_image_coe_of_bounded hb /-- If a set `s` of semilinear functions is bounded and is closed in the weak-* topology, then its image under coercion to functions `E → F` is a closed set. We don't have a name for `E →SL[σ] F` with weak-* topology in `mathlib`, so we use an equivalent condition (see `is_closed_induced_iff'`). TODO: reformulate this in terms of a type synonym with the right topology. -/ lemma is_closed_image_coe_of_bounded_of_weak_closed {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) (hc : ∀ f, (⇑f : E' → F) ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) → f ∈ s) : is_closed ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) := is_closed_of_closure_subset $ λ f hf, ⟨of_mem_closure_image_coe_bounded f hb hf, hc (of_mem_closure_image_coe_bounded f hb hf) hf, rfl⟩ /-- If a set `s` of semilinear functions is bounded and is closed in the weak-* topology, then its image under coercion to functions `E → F` is a compact set. We don't have a name for `E →SL[σ] F` with weak-* topology in `mathlib`, so we use an equivalent condition (see `is_closed_induced_iff'`). -/ lemma is_compact_image_coe_of_bounded_of_weak_closed [proper_space F] {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) (hc : ∀ f, (⇑f : E' → F) ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) → f ∈ s) : is_compact ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) := is_compact_image_coe_of_bounded_of_closed_image hb $ is_closed_image_coe_of_bounded_of_weak_closed hb hc /-- A closed ball is closed in the weak-* topology. We don't have a name for `E →SL[σ] F` with weak-* topology in `mathlib`, so we use an equivalent condition (see `is_closed_induced_iff'`). -/ lemma is_weak_closed_closed_ball (f₀ : E' →SL[σ₁₂] F) (r : ℝ) ⦃f : E' →SL[σ₁₂] F⦄ (hf : ⇑f ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' (closed_ball f₀ r))) : f ∈ closed_ball f₀ r := begin have hr : 0 ≤ r, from nonempty_closed_ball.1 (nonempty_image_iff.1 (closure_nonempty_iff.1 ⟨_, hf⟩)), refine mem_closed_ball_iff_norm.2 (op_norm_le_bound _ hr $ λ x, _), have : is_closed {g : E' → F | ‖g x - f₀ x‖ ≤ r * ‖x‖}, from is_closed_Iic.preimage ((@continuous_apply E' (λ _, F) _ x).sub continuous_const).norm, refine this.closure_subset_iff.2 (image_subset_iff.2 $ λ g hg, _) hf, exact (g - f₀).le_of_op_norm_le (mem_closed_ball_iff_norm.1 hg) _ end /-- The set of functions `f : E → F` that represent continuous linear maps `f : E →SL[σ₁₂] F` at distance `≤ r` from `f₀ : E →SL[σ₁₂] F` is closed in the topology of pointwise convergence. This is one of the key steps in the proof of the **Banach-Alaoglu** theorem. -/ lemma is_closed_image_coe_closed_ball (f₀ : E →SL[σ₁₂] F) (r : ℝ) : is_closed ((coe_fn : (E →SL[σ₁₂] F) → E → F) '' closed_ball f₀ r) := is_closed_image_coe_of_bounded_of_weak_closed bounded_closed_ball (is_weak_closed_closed_ball f₀ r) /-- **Banach-Alaoglu** theorem. The set of functions `f : E → F` that represent continuous linear maps `f : E →SL[σ₁₂] F` at distance `≤ r` from `f₀ : E →SL[σ₁₂] F` is compact in the topology of pointwise convergence. Other versions of this theorem can be found in `analysis.normed_space.weak_dual`. -/ lemma is_compact_image_coe_closed_ball [proper_space F] (f₀ : E →SL[σ₁₂] F) (r : ℝ) : is_compact ((coe_fn : (E →SL[σ₁₂] F) → E → F) '' closed_ball f₀ r) := is_compact_image_coe_of_bounded_of_weak_closed bounded_closed_ball $ is_weak_closed_closed_ball f₀ r end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] Fₗ) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →SL[σ₁₂] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] Fₗ`. -/ def extend : Fₗ →SL[σ₁₂] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const_smul _)) ((continuous_const_smul _).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact continuous_linear_map.map_smulₛₗ _ _ _ }, end, cont := cont } @[simp] lemma extend_eq (x : E) : extend f e h_dense h_e (e x) = f x := dense_inducing.extend_eq _ f.cont _ lemma extend_unique (g : Fₗ →SL[σ₁₂] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.coe_fn_injective $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →SL[σ₁₂] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : ℝ≥0} (h_e : ∀x, ‖x‖ ≤ N * ‖e x‖) [ring_hom_isometric σ₁₂] local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ‖f‖`. -/ lemma op_norm_extend_le : ‖ψ‖ ≤ N * ‖f‖ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ‖f x‖ ≤ ‖f‖ * ‖x‖ : le_op_norm _ _ ... ≤ ‖f‖ * (N * ‖e x‖) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ‖f‖ * ‖e x‖ : by rw [mul_comm ↑N ‖f‖, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map namespace linear_isometry @[simp] lemma norm_to_continuous_linear_map [nontrivial E] [ring_hom_isometric σ₁₂] (f : E →ₛₗᵢ[σ₁₂] F) : ‖f.to_continuous_linear_map‖ = 1 := f.to_continuous_linear_map.homothety_norm $ by simp variables {σ₁₃ : 𝕜 →+* 𝕜₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] include σ₁₃ /-- Postcomposition of a continuous linear map with a linear isometry preserves the operator norm. -/ lemma norm_to_continuous_linear_map_comp [ring_hom_isometric σ₁₂] (f : F →ₛₗᵢ[σ₂₃] G) {g : E →SL[σ₁₂] F} : ‖f.to_continuous_linear_map.comp g‖ = ‖g‖ := op_norm_ext (f.to_continuous_linear_map.comp g) g (λ x, by simp only [norm_map, coe_to_continuous_linear_map, coe_comp']) omit σ₁₃ end linear_isometry end namespace continuous_linear_map variables [nontrivially_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] [nontrivially_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] [normed_space 𝕜₃ G] [normed_space 𝕜 Fₗ] (c : 𝕜) {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₃ : 𝕜₂ →+* 𝕜₃} variables {𝕜₂' : Type*} [nontrivially_normed_field 𝕜₂'] {F' : Type*} [normed_add_comm_group F'] [normed_space 𝕜₂' F'] {σ₂' : 𝕜₂' →+* 𝕜₂} {σ₂'' : 𝕜₂ →+* 𝕜₂'} {σ₂₃' : 𝕜₂' →+* 𝕜₃} [ring_hom_inv_pair σ₂' σ₂''] [ring_hom_inv_pair σ₂'' σ₂'] [ring_hom_comp_triple σ₂' σ₂₃ σ₂₃'] [ring_hom_comp_triple σ₂'' σ₂₃' σ₂₃] [ring_hom_isometric σ₂₃] [ring_hom_isometric σ₂'] [ring_hom_isometric σ₂''] [ring_hom_isometric σ₂₃'] include σ₂'' σ₂₃' /-- Precomposition with a linear isometry preserves the operator norm. -/ lemma op_norm_comp_linear_isometry_equiv (f : F →SL[σ₂₃] G) (g : F' ≃ₛₗᵢ[σ₂'] F) : ‖f.comp g.to_linear_isometry.to_continuous_linear_map‖ = ‖f‖ := begin casesI subsingleton_or_nontrivial F', { haveI := g.symm.to_linear_equiv.to_equiv.subsingleton, simp }, refine le_antisymm _ _, { convert f.op_norm_comp_le g.to_linear_isometry.to_continuous_linear_map, simp [g.to_linear_isometry.norm_to_continuous_linear_map] }, { convert (f.comp g.to_linear_isometry.to_continuous_linear_map).op_norm_comp_le g.symm.to_linear_isometry.to_continuous_linear_map, { ext, simp }, haveI := g.symm.surjective.nontrivial, simp [g.symm.to_linear_isometry.norm_to_continuous_linear_map] }, end omit σ₂'' σ₂₃' /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : Fₗ) : ‖smul_right c f‖ = ‖c‖ * ‖f‖ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ‖(c x) • f‖ = ‖c x‖ * ‖f‖ : norm_smul _ _ ... ≤ (‖c‖ * ‖x‖) * ‖f‖ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ‖c‖ * ‖f‖ * ‖x‖ : by ring }, { by_cases h : f = 0, { simp [h] }, { have : 0 < ‖f‖ := norm_pos_iff.2 h, rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ‖c x‖ * ‖f‖ = ‖c x • f‖ : (norm_smul _ _).symm ... = ‖smul_right c f x‖ : rfl ... ≤ ‖smul_right c f‖ * ‖x‖ : le_op_norm _ _ } }, end /-- The non-negative norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the non-negative norms. -/ @[simp] lemma nnnorm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : Fₗ) : ‖smul_right c f‖₊ = ‖c‖₊ * ‖f‖₊ := nnreal.eq $ c.norm_smul_right_apply f variables (𝕜 E Fₗ) /-- `continuous_linear_map.smul_right` as a continuous trilinear map: `smul_rightL (c : E →L[𝕜] 𝕜) (f : F) (x : E) = c x • f`. -/ def smul_rightL : (E →L[𝕜] 𝕜) →L[𝕜] Fₗ →L[𝕜] E →L[𝕜] Fₗ := linear_map.mk_continuous₂ { to_fun := smul_rightₗ, map_add' := λ c₁ c₂, by { ext x, simp only [add_smul, coe_smul_rightₗ, add_apply, smul_right_apply, linear_map.add_apply] }, map_smul' := λ m c, by { ext x, simp only [smul_smul, coe_smul_rightₗ, algebra.id.smul_eq_mul, coe_smul', smul_right_apply, linear_map.smul_apply, ring_hom.id_apply, pi.smul_apply] } } 1 $ λ c x, by simp only [coe_smul_rightₗ, one_mul, norm_smul_right_apply, linear_map.coe_mk] variables {𝕜 E Fₗ} @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : Fₗ) : ‖smul_rightL 𝕜 E Fₗ c f‖ = ‖c‖ * ‖f‖ := norm_smul_right_apply c f @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial Fₗ] : ‖smul_rightL 𝕜 E Fₗ c‖ = ‖c‖ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜) (𝕜' : Type*) section variables [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma op_norm_mul [norm_one_class 𝕜'] : ‖mul 𝕜 𝕜'‖ = 1 := by haveI := norm_one_class.nontrivial 𝕜'; exact (mulₗᵢ 𝕜 𝕜').norm_to_continuous_linear_map end /-- The norm of `lsmul` equals 1 in any nontrivial normed group. This is `continuous_linear_map.op_norm_lsmul_le` as an equality. -/ @[simp] lemma op_norm_lsmul [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] [nontrivial E] : ‖(lsmul 𝕜 𝕜' : 𝕜' →L[𝕜] E →L[𝕜] E)‖ = 1 := begin refine continuous_linear_map.op_norm_eq_of_bounds zero_le_one (λ x, _) (λ N hN h, _), { rw one_mul, exact op_norm_lsmul_apply_le _, }, obtain ⟨y, hy⟩ := exists_ne (0 : E), have := le_of_op_norm_le _ (h 1) y, simp_rw [lsmul_apply, one_smul, norm_one, mul_one] at this, refine le_of_mul_le_mul_right _ (norm_pos_iff.mpr hy), simp_rw [one_mul, this] end end continuous_linear_map namespace submodule variables [nontrivially_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] [nontrivially_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] {σ₁₂ : 𝕜 →+* 𝕜₂} lemma norm_subtypeL (K : submodule 𝕜 E) [nontrivial K] : ‖K.subtypeL‖ = 1 := K.subtypeₗᵢ.norm_to_continuous_linear_map end submodule namespace continuous_linear_equiv variables [nontrivially_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] [nontrivially_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] section variables [ring_hom_isometric σ₂₁] protected lemma antilipschitz (e : E ≃SL[σ₁₂] F) : antilipschitz_with ‖(e.symm : F →SL[σ₂₁] E)‖₊ e := e.symm.lipschitz.to_right_inverse e.left_inv lemma one_le_norm_mul_norm_symm [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 1 ≤ ‖(e : E →SL[σ₁₂] F)‖ * ‖(e.symm : F →SL[σ₂₁] E)‖ := begin rw [mul_comm], convert (e.symm : F →SL[σ₂₁] E).op_norm_comp_le (e : E →SL[σ₁₂] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end include σ₂₁ lemma norm_pos [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 0 < ‖(e : E →SL[σ₁₂] F)‖ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) omit σ₂₁ lemma norm_symm_pos [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 0 < ‖(e.symm : F →SL[σ₂₁] E)‖ := pos_of_mul_pos_right (zero_lt_one.trans_le e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma nnnorm_symm_pos [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 0 < ‖(e.symm : F →SL[σ₂₁] E)‖₊ := e.norm_symm_pos lemma subsingleton_or_norm_symm_pos [ring_hom_isometric σ₁₂] (e : E ≃SL[σ₁₂] F) : subsingleton E ∨ 0 < ‖(e.symm : F →SL[σ₂₁] E)‖ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos [ring_hom_isometric σ₁₂] (e : E ≃SL[σ₁₂] F) : subsingleton E ∨ 0 < ‖(e.symm : F →SL[σ₂₁] E)‖₊ := subsingleton_or_norm_symm_pos e variable (𝕜) @[simp] lemma coord_norm (x : E) (h : x ≠ 0) : ‖coord 𝕜 x h‖ = ‖x‖⁻¹ := begin have hx : 0 < ‖x‖ := (norm_pos_iff.mpr h), haveI : nontrivial (𝕜 ∙ x) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end variables {𝕜} {𝕜₄ : Type*} [nontrivially_normed_field 𝕜₄] variables {H : Type*} [normed_add_comm_group H] [normed_space 𝕜₄ H] [normed_space 𝕜₃ G] variables {σ₂₃ : 𝕜₂ →+* 𝕜₃} {σ₁₃ : 𝕜 →+* 𝕜₃} variables {σ₃₄ : 𝕜₃ →+* 𝕜₄} {σ₄₃ : 𝕜₄ →+* 𝕜₃} variables {σ₂₄ : 𝕜₂ →+* 𝕜₄} {σ₁₄ : 𝕜 →+* 𝕜₄} variables [ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄] variables [ring_hom_comp_triple σ₂₁ σ₁₄ σ₂₄] [ring_hom_comp_triple σ₂₄ σ₄₃ σ₂₃] variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] variables [ring_hom_isometric σ₁₄] [ring_hom_isometric σ₂₃] variables [ring_hom_isometric σ₄₃] [ring_hom_isometric σ₂₄] variables [ring_hom_isometric σ₁₃] [ring_hom_isometric σ₁₂] variables [ring_hom_isometric σ₃₄] include σ₂₁ σ₃₄ σ₁₃ σ₂₄ /-- A pair of continuous (semi)linear equivalences generates an continuous (semi)linear equivalence between the spaces of continuous (semi)linear maps. -/ @[simps apply symm_apply] def arrow_congrSL (e₁₂ : E ≃SL[σ₁₂] F) (e₄₃ : H ≃SL[σ₄₃] G) : (E →SL[σ₁₄] H) ≃SL[σ₄₃] (F →SL[σ₂₃] G) := { -- given explicitly to help `simps` to_fun := λ L, (e₄₃ : H →SL[σ₄₃] G).comp (L.comp (e₁₂.symm : F →SL[σ₂₁] E)), -- given explicitly to help `simps` inv_fun := λ L, (e₄₃.symm : G →SL[σ₃₄] H).comp (L.comp (e₁₂ : E →SL[σ₁₂] F)), map_add' := λ f g, by rw [add_comp, comp_add], map_smul' := λ t f, by rw [smul_comp, comp_smulₛₗ], continuous_to_fun := (continuous_id.clm_comp_const _).const_clm_comp _, continuous_inv_fun := (continuous_id.clm_comp_const _).const_clm_comp _, .. e₁₂.arrow_congr_equiv e₄₃, } omit σ₂₁ σ₃₄ σ₁₃ σ₂₄ /-- A pair of continuous linear equivalences generates an continuous linear equivalence between the spaces of continuous linear maps. -/ def arrow_congr {F H : Type*} [normed_add_comm_group F] [normed_add_comm_group H] [normed_space 𝕜 F] [normed_space 𝕜 G] [normed_space 𝕜 H] (e₁ : E ≃L[𝕜] F) (e₂ : H ≃L[𝕜] G) : (E →L[𝕜] H) ≃L[𝕜] (F →L[𝕜] G) := arrow_congrSL e₁ e₂ end end continuous_linear_equiv end normed /-- A bounded bilinear form `B` in a real normed space is *coercive* if there is some positive constant C such that `C * ‖u‖ * ‖u‖ ≤ B u u`. -/ def is_coercive [normed_add_comm_group E] [normed_space ℝ E] (B : E →L[ℝ] E →L[ℝ] ℝ) : Prop := ∃ C, (0 < C) ∧ ∀ u, C * ‖u‖ * ‖u‖ ≤ B u u
423bd98eeea211cedb6e0940847075addb0e21b0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/equiv/encodable/basic.lean
f50a87ff525151119b199db160c88e74cad6b921
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
18,475
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import data.equiv.nat import order.rel_iso import order.directed /-! # Encodable types This file defines encodable (constructively countable) types as a typeclass. This is used to provide explicit encode/decode functions from and to `ℕ`, with the information that those functions are inverses of each other. The difference with `denumerable` is that finite types are encodable. For infinite types, `encodable` and `denumerable` agree. ## Main declarations * `encodable α`: States that there exists an explicit encoding function `encode : α → ℕ` with a partial inverse `decode : ℕ → option α`. * `decode₂`: Version of `decode` that is equal to `none` outside of the range of `encode`. Useful as we do not require this in the definition of `decode`. * `ulower α`: Any encodable type has an equivalent type living in the lowest universe, namely a subtype of `ℕ`. `ulower α` finds it. ## Implementation notes The point of asking for an explicit partial inverse `decode : ℕ → option α` to `encode : α → ℕ` is to make the range of `encode` decidable even when the finiteness of `α` is not. -/ open option list nat function /-- Constructively countable type. Made from an explicit injection `encode : α → ℕ` and a partial inverse `decode : ℕ → option α`. Note that finite types *are* countable. See `denumerable` if you wish to enforce infiniteness. -/ class encodable (α : Type*) := (encode : α → ℕ) (decode [] : ℕ → option α) (encodek : ∀ a, decode (encode a) = some a) attribute [simp] encodable.encodek namespace encodable variables {α : Type*} {β : Type*} universe u theorem encode_injective [encodable α] : function.injective (@encode α _) | x y e := option.some.inj $ by rw [← encodek, e, encodek] @[simp] lemma encode_inj [encodable α] {a b : α} : encode a = encode b ↔ a = b := encode_injective.eq_iff lemma surjective_decode_iget (α : Type*) [encodable α] [inhabited α] : surjective (λ n, (encodable.decode α n).iget) := λ x, ⟨encodable.encode x, by simp_rw [encodable.encodek]⟩ /-- An encodable type has decidable equality. Not set as an instance because this is usually not the best way to infer decidability. -/ def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α | a b := decidable_of_iff _ encode_inj /-- If `α` is encodable and there is an injection `f : β → α`, then `β` is encodable as well. -/ def of_left_injection [encodable α] (f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β := ⟨λ b, encode (f b), λ n, (decode α n).bind finv, λ b, by simp [encodable.encodek, linv]⟩ /-- If `α` is encodable and `f : β → α` is invertible, then `β` is encodable as well. -/ def of_left_inverse [encodable α] (f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β := of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b)) /-- Encodability is preserved by equivalence. -/ def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β := of_left_inverse e e.symm e.left_inv @[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) : @encode _ (of_equiv _ e) b = encode (e b) := rfl @[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) : @decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl instance nat : encodable ℕ := ⟨id, some, λ a, rfl⟩ @[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl @[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl instance empty : encodable empty := ⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩ instance unit : encodable punit := ⟨λ_, 0, λ n, nat.cases_on n (some punit.star) (λ _, none), λ _, by simp⟩ @[simp] theorem encode_star : encode punit.star = 0 := rfl @[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl @[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl /-- If `α` is encodable, then so is `option α`. -/ instance option {α : Type*} [h : encodable α] : encodable (option α) := ⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)), λ n, nat.cases_on n (some none) (λ m, (decode α m).map some), λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩ @[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl @[simp] theorem encode_some [encodable α] (a : α) : encode (some a) = succ (encode a) := rfl @[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl @[simp] theorem decode_option_succ [encodable α] (n) : decode (option α) (succ n) = (decode α n).map some := rfl /-- Failsafe variant of `decode`. `decode₂ α n` returns the preimage of `n` under `encode` if it exists, and returns `none` if it doesn't. This requirement could be imposed directly on `decode` but is not to help make the definition easier to use. -/ def decode₂ (α) [encodable α] (n : ℕ) : option α := (decode α n).bind (option.guard (λ a, encode a = n)) theorem mem_decode₂' [encodable α] {n : ℕ} {a : α} : a ∈ decode₂ α n ↔ a ∈ decode α n ∧ encode a = n := by simp [decode₂]; exact ⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩ theorem mem_decode₂ [encodable α] {n : ℕ} {a : α} : a ∈ decode₂ α n ↔ encode a = n := mem_decode₂'.trans (and_iff_right_of_imp $ λ e, e ▸ encodek _) theorem decode₂_eq_some [encodable α] {n : ℕ} {a : α} : decode₂ α n = some a ↔ encode a = n := mem_decode₂ @[simp] lemma decode₂_encode [encodable α] (a : α) : decode₂ α (encode a) = some a := by { ext, simp [mem_decode₂, eq_comm] } theorem decode₂_ne_none_iff [encodable α] {n : ℕ} : decode₂ α n ≠ none ↔ n ∈ set.range (encode : α → ℕ) := by simp_rw [set.range, set.mem_set_of_eq, ne.def, option.eq_none_iff_forall_not_mem, encodable.mem_decode₂, not_forall, not_not] theorem decode₂_is_partial_inv [encodable α] : is_partial_inv encode (decode₂ α) := λ a n, mem_decode₂ theorem decode₂_inj [encodable α] {n : ℕ} {a₁ a₂ : α} (h₁ : a₁ ∈ decode₂ α n) (h₂ : a₂ ∈ decode₂ α n) : a₁ = a₂ := encode_injective $ (mem_decode₂.1 h₁).trans (mem_decode₂.1 h₂).symm theorem encodek₂ [encodable α] (a : α) : decode₂ α (encode a) = some a := mem_decode₂.2 rfl /-- The encoding function has decidable range. -/ def decidable_range_encode (α : Type*) [encodable α] : decidable_pred (∈ set.range (@encode α _)) := λ x, decidable_of_iff (option.is_some (decode₂ α x)) ⟨λ h, ⟨option.get h, by rw [← decode₂_is_partial_inv (option.get h), option.some_get]⟩, λ ⟨n, hn⟩, by rw [← hn, encodek₂]; exact rfl⟩ /-- An encodable type is equivalent to the range of its encoding function. -/ def equiv_range_encode (α : Type*) [encodable α] : α ≃ set.range (@encode α _) := { to_fun := λ a : α, ⟨encode a, set.mem_range_self _⟩, inv_fun := λ n, option.get (show is_some (decode₂ α n.1), by cases n.2 with x hx; rw [← hx, encodek₂]; exact rfl), left_inv := λ a, by dsimp; rw [← option.some_inj, option.some_get, encodek₂], right_inv := λ ⟨n, x, hx⟩, begin apply subtype.eq, dsimp, conv {to_rhs, rw ← hx}, rw [encode_injective.eq_iff, ← option.some_inj, option.some_get, ← hx, encodek₂], end } /-- A type with unique element is encodable. This is not an instance to avoid diamonds. -/ def _root_.unique.encodable [unique α] : encodable α := ⟨λ _, 0, λ _, some default, unique.forall_iff.2 rfl⟩ section sum variables [encodable α] [encodable β] /-- Explicit encoding function for the sum of two encodable types. -/ def encode_sum : α ⊕ β → ℕ | (sum.inl a) := bit0 $ encode a | (sum.inr b) := bit1 $ encode b /-- Explicit decoding function for the sum of two encodable types. -/ def decode_sum (n : ℕ) : option (α ⊕ β) := match bodd_div2 n with | (ff, m) := (decode α m).map sum.inl | (tt, m) := (decode β m).map sum.inr end /-- If `α` and `β` are encodable, then so is their sum. -/ instance sum : encodable (α ⊕ β) := ⟨encode_sum, decode_sum, λ s, by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩ @[simp] theorem encode_inl (a : α) : @encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl @[simp] theorem encode_inr (b : β) : @encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl @[simp] theorem decode_sum_val (n : ℕ) : decode (α ⊕ β) n = decode_sum n := rfl end sum instance bool : encodable bool := of_equiv (unit ⊕ unit) equiv.bool_equiv_punit_sum_punit @[simp] theorem encode_tt : encode tt = 1 := rfl @[simp] theorem encode_ff : encode ff = 0 := rfl @[simp] theorem decode_zero : decode bool 0 = some ff := rfl @[simp] theorem decode_one : decode bool 1 = some tt := rfl theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none := begin suffices : decode_sum n = none, { change (decode_sum n).map _ = none, rw this, refl }, have : 1 ≤ div2 n, { rw [div2_val, nat.le_div_iff_mul_le], exacts [h, dec_trivial] }, cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e, simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl end noncomputable instance «Prop» : encodable Prop := of_equiv bool equiv.Prop_equiv_bool section sigma variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)] /-- Explicit encoding function for `sigma γ` -/ def encode_sigma : sigma γ → ℕ | ⟨a, b⟩ := mkpair (encode a) (encode b) /-- Explicit decoding function for `sigma γ` -/ def decode_sigma (n : ℕ) : option (sigma γ) := let (n₁, n₂) := unpair n in (decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a instance sigma : encodable (sigma γ) := ⟨encode_sigma, decode_sigma, λ ⟨a, b⟩, by simp [encode_sigma, decode_sigma, unpair_mkpair, encodek]⟩ @[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n = (decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) := show decode_sigma._match_1 _ = _, by cases n.unpair; refl @[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ = mkpair (encode a) (encode b) := rfl end sigma section prod variables [encodable α] [encodable β] /-- If `α` and `β` are encodable, then so is their product. -/ instance prod : encodable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n = (decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) := show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; refl @[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) = mkpair (encode a) (encode b) := rfl end prod section subtype open subtype decidable variables {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] include encA /-- Explicit encoding function for a decidable subtype of an encodable type -/ def encode_subtype : {a : α // P a} → ℕ | ⟨v, h⟩ := encode v include decP /-- Explicit decoding function for a decidable subtype of an encodable type -/ def decode_subtype (v : ℕ) : option {a : α // P a} := (decode α v).bind $ λ a, if h : P a then some ⟨a, h⟩ else none /-- A decidable subtype of an encodable type is encodable. -/ instance subtype : encodable {a : α // P a} := ⟨encode_subtype, decode_subtype, λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩ lemma subtype.encode_eq (a : subtype P) : encode a = encode a.val := by cases a; refl end subtype instance fin (n) : encodable (fin n) := of_equiv _ (equiv.fin_equiv_subtype _) instance int : encodable ℤ := of_equiv _ equiv.int_equiv_nat instance pnat : encodable ℕ+ := of_equiv _ equiv.pnat_equiv_nat /-- The lift of an encodable type is encodable. -/ instance ulift [encodable α] : encodable (ulift α) := of_equiv _ equiv.ulift /-- The lift of an encodable type is encodable. -/ instance plift [encodable α] : encodable (plift α) := of_equiv _ equiv.plift /-- If `β` is encodable and there is an injection `f : α → β`, then `α` is encodable as well. -/ noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α := of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl) end encodable section ulower local attribute [instance, priority 100] encodable.decidable_range_encode /-- `ulower α : Type` is an equivalent type in the lowest universe, given `encodable α`. -/ @[derive decidable_eq, derive encodable] def ulower (α : Type*) [encodable α] : Type := set.range (encodable.encode : α → ℕ) end ulower namespace ulower variables (α : Type*) [encodable α] /-- The equivalence between the encodable type `α` and `ulower α : Type`. -/ def equiv : α ≃ ulower α := encodable.equiv_range_encode α variables {α} /-- Lowers an `a : α` into `ulower α`. -/ def down (a : α) : ulower α := equiv α a instance [inhabited α] : inhabited (ulower α) := ⟨down default⟩ /-- Lifts an `a : ulower α` into `α`. -/ def up (a : ulower α) : α := (equiv α).symm a @[simp] lemma down_up {a : ulower α} : down a.up = a := equiv.right_inv _ _ @[simp] lemma up_down {a : α} : (down a).up = a := equiv.left_inv _ _ @[simp] lemma up_eq_up {a b : ulower α} : a.up = b.up ↔ a = b := equiv.apply_eq_iff_eq _ @[simp] lemma down_eq_down {a b : α} : down a = down b ↔ a = b := equiv.apply_eq_iff_eq _ @[ext] protected lemma ext {a b : ulower α} : a.up = b.up → a = b := up_eq_up.1 end ulower /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace encodable section find_a variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p] private def good : option α → Prop | (some a) := p a | none := false private def decidable_good : decidable_pred (good p) | n := by cases n; unfold good; apply_instance local attribute [instance] decidable_good open encodable variable {p} /-- Constructive choice function for a decidable subtype of an encodable type. -/ def choose_x (h : ∃ x, p x) : {a : α // p a} := have ∃ n, good p (decode α n), from let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩, match _, nat.find_spec this : ∀ o, good p o → {a // p a} with | some a, h := ⟨a, h⟩ end /-- Constructive choice function for a decidable predicate over an encodable type. -/ def choose (h : ∃ x, p x) : α := (choose_x h).1 lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2 end find_a theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop} [Π a, encodable (β a)] [∀ x y, decidable (R x y)] (H : ∀ x, ∃ y, R x y) : ∃ f : Π a, β a, ∀ x, R x (f x) := ⟨λ x, choose (H x), λ x, choose_spec (H x)⟩ theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop} [c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] : (∀ x, ∃ y, P x y) ↔ ∃ f : Π a, β a, (∀ x, P x (f x)) := ⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩ /- There is a total ordering on the elements of an encodable type, induced by the map to ℕ. -/ /-- The `encode` function, viewed as an embedding. -/ def encode' (α) [encodable α] : α ↪ ℕ := ⟨encodable.encode, encodable.encode_injective⟩ instance {α} [encodable α] : is_trans _ (encode' α ⁻¹'o (≤)) := (rel_embedding.preimage _ _).is_trans instance {α} [encodable α] : is_antisymm _ (encodable.encode' α ⁻¹'o (≤)) := (rel_embedding.preimage _ _).is_antisymm instance {α} [encodable α] : is_total _ (encodable.encode' α ⁻¹'o (≤)) := (rel_embedding.preimage _ _).is_total end encodable namespace directed open encodable variables {α : Type*} {β : Type*} [encodable α] [inhabited α] /-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type, construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))` and `r (f a) (f (x (encode a + 1))`. -/ protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α | 0 := default | (n + 1) := let p := sequence n in match decode α n with | none := classical.some (hf p p) | (some a) := classical.some (hf p a) end lemma sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) : r (f (hf.sequence f n)) (f (hf.sequence f (n+1))) := begin dsimp [directed.sequence], generalize eq : hf.sequence f n = p, cases h : decode α n with a, { exact (classical.some_spec (hf p p)).1 }, { exact (classical.some_spec (hf p a)).1 } end lemma rel_sequence {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) : r (f a) (f (hf.sequence f (encode a + 1))) := begin simp only [directed.sequence, encodek], exact (classical.some_spec (hf _ a)).2 end variables [preorder β] {f : α → β} (hf : directed (≤) f) lemma sequence_mono : monotone (f ∘ (hf.sequence f)) := monotone_nat_of_le_succ $ hf.sequence_mono_nat lemma le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) := hf.rel_sequence a end directed section quotient open encodable quotient variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α] /-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid on an encodable type. -/ def quotient.rep (q : quotient s) : α := choose (exists_rep q) theorem quotient.rep_spec (q : quotient s) : ⟦q.rep⟧ = q := choose_spec (exists_rep q) /-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/ def encodable_quotient : encodable (quotient s) := ⟨λ q, encode q.rep, λ n, quotient.mk <$> decode α n, by rintros ⟨l⟩; rw encodek; exact congr_arg some ⟦l⟧.rep_spec⟩ end quotient
a5911cd07445d03f376de65810ec8e4c8d279bdb
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/init/ua.lean
46b8d56ea394e709f32810f80f6816074eb6eed6
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
3,439
lean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ import .equiv universes u v w l hott_theory namespace hott open eq equiv hott.is_equiv axiom univalence (A B : Type u) : is_equiv (@equiv_of_eq A B) attribute [instance] univalence -- This is the version of univalence axiom we will probably use most often @[hott] def ua {A B : Type u} : A ≃ B → A = B := equiv_of_eq⁻¹ᶠ @[hott] def eq_equiv_equiv (A B : Type u) : (A = B) ≃ (A ≃ B) := equiv.mk equiv_of_eq (by apply_instance) @[hott, elab_simple] def equiv_of_eq_ua {A B : Type u} (f : A ≃ B) : equiv_of_eq (ua f) = f := right_inv equiv_of_eq f @[hott] def cast_ua_fn {A B : Type u} (f : A ≃ B) : cast (ua f) = f := ap to_fun (equiv_of_eq_ua f) @[hott] def cast_ua {A B : Type u} (f : A ≃ B) (a : A) : cast (ua f) a = f a := ap10 (cast_ua_fn f) a @[hott] def cast_ua_inv_fn {A B : Type u} (f : A ≃ B) : cast (ua f)⁻¹ = f⁻¹ᶠ := ap to_inv (equiv_of_eq_ua f) @[hott] def cast_ua_inv {A B : Type u} (f : A ≃ B) (b : B) : cast (ua f)⁻¹ b = f⁻¹ᶠ b := ap10 (cast_ua_inv_fn f) b @[hott] def ua_equiv_of_eq {A B : Type u} (p : A = B) : ua (equiv_of_eq p) = p := left_inv equiv_of_eq p @[hott] def eq_of_equiv_lift {A : Type (max v u)} {B : Type v} (f : A ≃ B) : A = ulift B := ua (f ⬝e equiv_lift _) namespace equiv -- One consequence of UA is that we can transport along equivalencies of types -- We can use this for calculation evironments @[subst, hott] protected def transport_of_equiv (P : Type _ → Type _) {A B : Type _} (H : A ≃ B) : P A → P B := eq.transport P (ua H) -- we can "recurse" on equivalences, by replacing them by (equiv_of_eq _) @[hott] def rec_on_ua {A B : Type _} {P : A ≃ B → Type _} (f : A ≃ B) (H : Π(q : A = B), P (equiv_of_eq q)) : P f := right_inv equiv_of_eq f ▸ H (ua f) -- a variant where we immediately recurse on the equality in the new goal @[hott] def rec_on_ua_idp {A : Type _} {P : Π{B}, A ≃ B → Type _} {B : Type _} (f : A ≃ B) (H : P equiv.rfl) : P f := rec_on_ua f (λq, by induction q; apply H) -- a variant where (equiv_of_eq (ua f)) will be replaced by f in the new goal @[hott] def rec_on_ua' {A B : Type _} {P : A ≃ B → A = B → Type _} (f : A ≃ B) (H : Π(q : A = B), P (equiv_of_eq q) q) : P f (ua f) := transport (λ x, P x (ua f)) (right_inv equiv_of_eq f) (H (ua f)) -- a variant where we do both @[hott] def rec_on_ua_idp' {A : Type _} {P : Π{B}, A ≃ B → A = B → Type _} {B : Type _} (f : A ≃ B) (H : P equiv.rfl idp) : P f (ua f) := rec_on_ua' f (λq, by induction q; exact H) @[hott] def ua_refl (A : Type _) : ua equiv.rfl = idpath A := eq_of_fn_eq_fn (eq_equiv_equiv _ _) (right_inv (eq_equiv_equiv _ _).to_fun equiv.rfl) @[hott] def ua_symm {A B : Type _} (f : A ≃ B) : ua f⁻¹ᵉ = (ua f)⁻¹ := begin apply rec_on_ua_idp f, transitivity, tactic.swap, {apply inverse2, symmetry, apply ua_refl}, {apply ua_refl}, end @[hott] def ua_trans {A B C : Type _} (f : A ≃ B) (g : B ≃ C) : ua (f ⬝e g) = ua f ⬝ ua g := begin apply rec_on_ua_idp g, apply rec_on_ua_idp f, transitivity, tactic.swap, {apply concat2; {symmetry, apply ua_refl}}, {apply ua_refl}, end end equiv end hott
05b464fdaff0a318a965cdd3c246e1e0307d7f97
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/rev_tac1.lean
0327ca37c3f775134ceab59ae0d6542d06adbae5
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
185
lean
open tactic example (a b : nat) (H : a > 0) (H : a > b) (H : b > 0) : a = b → true := by do a ← get_local `a, n ← revert a, trace n, trace_state, intros, constructor
1a748fd1b8e8833370e5c33e1006fb02e231b3a5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/locally_finite.lean
8f4ee3a9b7c2909157288df9c8ded3b6bbead8a3
[ "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
42,009
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.preimage /-! # Locally finite orders This file defines locally finite orders. A locally finite order is an order for which all bounded intervals are finite. This allows to make sense of `Icc`/`Ico`/`Ioc`/`Ioo` as lists, multisets, or finsets. Further, if the order is bounded above (resp. below), then we can also make sense of the "unbounded" intervals `Ici`/`Ioi` (resp. `Iic`/`Iio`). Many theorems about these intervals can be found in `data.finset.locally_finite`. ## Examples Naturally occurring locally finite orders are `ℕ`, `ℤ`, `ℕ+`, `fin n`, `α × β` the product of two locally finite orders, `α →₀ β` the finitely supported functions to a locally finite order `β`... ## Main declarations In a `locally_finite_order`, * `finset.Icc`: Closed-closed interval as a finset. * `finset.Ico`: Closed-open interval as a finset. * `finset.Ioc`: Open-closed interval as a finset. * `finset.Ioo`: Open-open interval as a finset. * `multiset.Icc`: Closed-closed interval as a multiset. * `multiset.Ico`: Closed-open interval as a multiset. * `multiset.Ioc`: Open-closed interval as a multiset. * `multiset.Ioo`: Open-open interval as a multiset. In a `locally_finite_order_top`, * `finset.Ici`: Closed-infinite interval as a finset. * `finset.Ioi`: Open-infinite interval as a finset. * `multiset.Ici`: Closed-infinite interval as a multiset. * `multiset.Ioi`: Open-infinite interval as a multiset. In a `locally_finite_order_bot`, * `finset.Iic`: Infinite-open interval as a finset. * `finset.Iio`: Infinite-closed interval as a finset. * `multiset.Iic`: Infinite-open interval as a multiset. * `multiset.Iio`: Infinite-closed interval as a multiset. ## Instances A `locally_finite_order` instance can be built * for a subtype of a locally finite order. See `subtype.locally_finite_order`. * for the product of two locally finite orders. See `prod.locally_finite_order`. * for any fintype (but not as an instance). See `fintype.to_locally_finite_order`. * from a definition of `finset.Icc` alone. See `locally_finite_order.of_Icc`. * by pulling back `locally_finite_order β` through an order embedding `f : α →o β`. See `order_embedding.locally_finite_order`. Instances for concrete types are proved in their respective files: * `ℕ` is in `data.nat.interval` * `ℤ` is in `data.int.interval` * `ℕ+` is in `data.pnat.interval` * `fin n` is in `data.fin.interval` * `finset α` is in `data.finset.interval` * `Σ i, α i` is in `data.sigma.interval` Along, you will find lemmas about the cardinality of those finite intervals. ## TODO Provide the `locally_finite_order` instance for `α ×ₗ β` where `locally_finite_order α` and `fintype β`. Provide the `locally_finite_order` instance for `α →₀ β` where `β` is locally finite. Provide the `locally_finite_order` instance for `Π₀ i, β i` where all the `β i` are locally finite. From `linear_order α`, `no_max_order α`, `locally_finite_order α`, we can also define an order isomorphism `α ≃ ℕ` or `α ≃ ℤ`, depending on whether we have `order_bot α` or `no_min_order α` and `nonempty α`. When `order_bot α`, we can match `a : α` to `(Iio a).card`. We can provide `succ_order α` from `linear_order α` and `locally_finite_order α` using ```lean lemma exists_min_greater [linear_order α] [locally_finite_order α] {x ub : α} (hx : x < ub) : ∃ lub, x < lub ∧ ∀ y, x < y → lub ≤ y := begin -- very non golfed have h : (finset.Ioc x ub).nonempty := ⟨ub, finset.mem_Ioc_iff.2 ⟨hx, le_rfl⟩⟩, use finset.min' (finset.Ioc x ub) h, split, { have := finset.min'_mem _ h, simp * at * }, rintro y hxy, obtain hy | hy := le_total y ub, apply finset.min'_le, simp * at *, exact (finset.min'_le _ _ (finset.mem_Ioc_iff.2 ⟨hx, le_rfl⟩)).trans hy, end ``` Note that the converse is not true. Consider `{-2^z | z : ℤ} ∪ {2^z | z : ℤ}`. Any element has a successor (and actually a predecessor as well), so it is a `succ_order`, but it's not locally finite as `Icc (-1) 1` is infinite. -/ open finset function /-- A locally finite order is an order where bounded intervals are finite. When you don't care too much about definitional equality, you can use `locally_finite_order.of_Icc` or `locally_finite_order.of_finite_Icc` to build a locally finite order from just `finset.Icc`. -/ class locally_finite_order (α : Type*) [preorder α] := (finset_Icc : α → α → finset α) (finset_Ico : α → α → finset α) (finset_Ioc : α → α → finset α) (finset_Ioo : α → α → finset α) (finset_mem_Icc : ∀ a b x : α, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) (finset_mem_Ico : ∀ a b x : α, x ∈ finset_Ico a b ↔ a ≤ x ∧ x < b) (finset_mem_Ioc : ∀ a b x : α, x ∈ finset_Ioc a b ↔ a < x ∧ x ≤ b) (finset_mem_Ioo : ∀ a b x : α, x ∈ finset_Ioo a b ↔ a < x ∧ x < b) /-- A locally finite order top is an order where all intervals bounded above are finite. This is slightly weaker than `locally_finite_order` + `order_top` as it allows empty types. -/ class locally_finite_order_top (α : Type*) [preorder α] := (finset_Ioi : α → finset α) (finset_Ici : α → finset α) (finset_mem_Ici : ∀ a x : α, x ∈ finset_Ici a ↔ a ≤ x) (finset_mem_Ioi : ∀ a x : α, x ∈ finset_Ioi a ↔ a < x) /-- A locally finite order bot is an order where all intervals bounded below are finite. This is slightly weaker than `locally_finite_order` + `order_bot` as it allows empty types. -/ class locally_finite_order_bot (α : Type*) [preorder α] := (finset_Iio : α → finset α) (finset_Iic : α → finset α) (finset_mem_Iic : ∀ a x : α, x ∈ finset_Iic a ↔ x ≤ a) (finset_mem_Iio : ∀ a x : α, x ∈ finset_Iio a ↔ x < a) /-- A constructor from a definition of `finset.Icc` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `decidable_rel (≤)` but only `preorder`. -/ def locally_finite_order.of_Icc' (α : Type*) [preorder α] [decidable_rel ((≤) : α → α → Prop)] (finset_Icc : α → α → finset α) (mem_Icc : ∀ a b x, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) : locally_finite_order α := { finset_Icc := finset_Icc, finset_Ico := λ a b, (finset_Icc a b).filter (λ x, ¬b ≤ x), finset_Ioc := λ a b, (finset_Icc a b).filter (λ x, ¬x ≤ a), finset_Ioo := λ a b, (finset_Icc a b).filter (λ x, ¬x ≤ a ∧ ¬b ≤ x), finset_mem_Icc := mem_Icc, finset_mem_Ico := λ a b x, by rw [finset.mem_filter, mem_Icc, and_assoc, lt_iff_le_not_le], finset_mem_Ioc := λ a b x, by rw [finset.mem_filter, mem_Icc, and.right_comm, lt_iff_le_not_le], finset_mem_Ioo := λ a b x, by rw [finset.mem_filter, mem_Icc, and_and_and_comm, lt_iff_le_not_le, lt_iff_le_not_le] } /-- A constructor from a definition of `finset.Icc` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `partial_order` but only `decidable_eq`. -/ def locally_finite_order.of_Icc (α : Type*) [partial_order α] [decidable_eq α] (finset_Icc : α → α → finset α) (mem_Icc : ∀ a b x, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) : locally_finite_order α := { finset_Icc := finset_Icc, finset_Ico := λ a b, (finset_Icc a b).filter (λ x, x ≠ b), finset_Ioc := λ a b, (finset_Icc a b).filter (λ x, a ≠ x), finset_Ioo := λ a b, (finset_Icc a b).filter (λ x, a ≠ x ∧ x ≠ b), finset_mem_Icc := mem_Icc, finset_mem_Ico := λ a b x, by rw [finset.mem_filter, mem_Icc, and_assoc, lt_iff_le_and_ne], finset_mem_Ioc := λ a b x, by rw [finset.mem_filter, mem_Icc, and.right_comm, lt_iff_le_and_ne], finset_mem_Ioo := λ a b x, by rw [finset.mem_filter, mem_Icc, and_and_and_comm, lt_iff_le_and_ne, lt_iff_le_and_ne] } /-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order_top.of_Ici`, this one requires `decidable_rel (≤)` but only `preorder`. -/ def locally_finite_order_top.of_Ici' (α : Type*) [preorder α] [decidable_rel ((≤) : α → α → Prop)] (finset_Ici : α → finset α) (mem_Ici : ∀ a x, x ∈ finset_Ici a ↔ a ≤ x) : locally_finite_order_top α := { finset_Ici := finset_Ici, finset_Ioi := λ a, (finset_Ici a).filter (λ x, ¬x ≤ a), finset_mem_Ici := mem_Ici, finset_mem_Ioi := λ a x, by rw [mem_filter, mem_Ici, lt_iff_le_not_le] } /-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order_top.of_Ici'`, this one requires `partial_order` but only `decidable_eq`. -/ def locally_finite_order_top.of_Ici (α : Type*) [partial_order α] [decidable_eq α] (finset_Ici : α → finset α) (mem_Ici : ∀ a x, x ∈ finset_Ici a ↔ a ≤ x) : locally_finite_order_top α := { finset_Ici := finset_Ici, finset_Ioi := λ a, (finset_Ici a).filter (λ x, a ≠ x), finset_mem_Ici := mem_Ici, finset_mem_Ioi := λ a x, by rw [mem_filter, mem_Ici, lt_iff_le_and_ne] } /-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `decidable_rel (≤)` but only `preorder`. -/ def locally_finite_order_bot.of_Iic' (α : Type*) [preorder α] [decidable_rel ((≤) : α → α → Prop)] (finset_Iic : α → finset α) (mem_Iic : ∀ a x, x ∈ finset_Iic a ↔ x ≤ a) : locally_finite_order_bot α := { finset_Iic := finset_Iic, finset_Iio := λ a, (finset_Iic a).filter (λ x, ¬a ≤ x), finset_mem_Iic := mem_Iic, finset_mem_Iio := λ a x, by rw [mem_filter, mem_Iic, lt_iff_le_not_le] } /-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order_top.of_Ici'`, this one requires `partial_order` but only `decidable_eq`. -/ def locally_finite_order_top.of_Iic (α : Type*) [partial_order α] [decidable_eq α] (finset_Iic : α → finset α) (mem_Iic : ∀ a x, x ∈ finset_Iic a ↔ x ≤ a) : locally_finite_order_bot α := { finset_Iic := finset_Iic, finset_Iio := λ a, (finset_Iic a).filter (λ x, x ≠ a), finset_mem_Iic := mem_Iic, finset_mem_Iio := λ a x, by rw [mem_filter, mem_Iic, lt_iff_le_and_ne] } variables {α β : Type*} /-- An empty type is locally finite. This is not an instance as it would not be defeq to more specific instances. -/ @[reducible] -- See note [reducible non-instances] protected def _root_.is_empty.to_locally_finite_order [preorder α] [is_empty α] : locally_finite_order α := { finset_Icc := is_empty_elim, finset_Ico := is_empty_elim, finset_Ioc := is_empty_elim, finset_Ioo := is_empty_elim, finset_mem_Icc := is_empty_elim, finset_mem_Ico := is_empty_elim, finset_mem_Ioc := is_empty_elim, finset_mem_Ioo := is_empty_elim } /-- An empty type is locally finite. This is not an instance as it would not be defeq to more specific instances. -/ @[reducible] -- See note [reducible non-instances] protected def _root_.is_empty.to_locally_finite_order_top [preorder α] [is_empty α] : locally_finite_order_top α := { finset_Ici := is_empty_elim, finset_Ioi := is_empty_elim, finset_mem_Ici := is_empty_elim, finset_mem_Ioi := is_empty_elim } /-- An empty type is locally finite. This is not an instance as it would not be defeq to more specific instances. -/ @[reducible] -- See note [reducible non-instances] protected def _root_.is_empty.to_locally_finite_order_bot [preorder α] [is_empty α] : locally_finite_order_bot α := { finset_Iic := is_empty_elim, finset_Iio := is_empty_elim, finset_mem_Iic := is_empty_elim, finset_mem_Iio := is_empty_elim } /-! ### Intervals as finsets -/ namespace finset variables [preorder α] section locally_finite_order variables [locally_finite_order α] {a b x : α} /-- The finset of elements `x` such that `a ≤ x` and `x ≤ b`. Basically `set.Icc a b` as a finset. -/ def Icc (a b : α) : finset α := locally_finite_order.finset_Icc a b /-- The finset of elements `x` such that `a ≤ x` and `x < b`. Basically `set.Ico a b` as a finset. -/ def Ico (a b : α) : finset α := locally_finite_order.finset_Ico a b /-- The finset of elements `x` such that `a < x` and `x ≤ b`. Basically `set.Ioc a b` as a finset. -/ def Ioc (a b : α) : finset α := locally_finite_order.finset_Ioc a b /-- The finset of elements `x` such that `a < x` and `x < b`. Basically `set.Ioo a b` as a finset. -/ def Ioo (a b : α) : finset α := locally_finite_order.finset_Ioo a b @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := locally_finite_order.finset_mem_Icc a b x @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := locally_finite_order.finset_mem_Ico a b x @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := locally_finite_order.finset_mem_Ioc a b x @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := locally_finite_order.finset_mem_Ioo a b x @[simp, norm_cast] lemma coe_Icc (a b : α) : (Icc a b : set α) = set.Icc a b := set.ext $ λ _, mem_Icc @[simp, norm_cast] lemma coe_Ico (a b : α) : (Ico a b : set α) = set.Ico a b := set.ext $ λ _, mem_Ico @[simp, norm_cast] lemma coe_Ioc (a b : α) : (Ioc a b : set α) = set.Ioc a b := set.ext $ λ _, mem_Ioc @[simp, norm_cast] lemma coe_Ioo (a b : α) : (Ioo a b : set α) = set.Ioo a b := set.ext $ λ _, mem_Ioo end locally_finite_order section locally_finite_order_top variables [locally_finite_order_top α] {a x : α} /-- The finset of elements `x` such that `a ≤ x`. Basically `set.Ici a` as a finset. -/ def Ici (a : α) : finset α := locally_finite_order_top.finset_Ici a /-- The finset of elements `x` such that `a < x`. Basically `set.Ioi a` as a finset. -/ def Ioi (a : α) : finset α := locally_finite_order_top.finset_Ioi a @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := locally_finite_order_top.finset_mem_Ici _ _ @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := locally_finite_order_top.finset_mem_Ioi _ _ @[simp, norm_cast] lemma coe_Ici (a : α) : (Ici a : set α) = set.Ici a := set.ext $ λ _, mem_Ici @[simp, norm_cast] lemma coe_Ioi (a : α) : (Ioi a : set α) = set.Ioi a := set.ext $ λ _, mem_Ioi end locally_finite_order_top section locally_finite_order_bot variables [locally_finite_order_bot α] {a x : α} /-- The finset of elements `x` such that `a ≤ x`. Basically `set.Iic a` as a finset. -/ def Iic (a : α) : finset α := locally_finite_order_bot.finset_Iic a /-- The finset of elements `x` such that `a < x`. Basically `set.Iio a` as a finset. -/ def Iio (a : α) : finset α := locally_finite_order_bot.finset_Iio a @[simp] lemma mem_Iic : x ∈ Iic a ↔ x ≤ a := locally_finite_order_bot.finset_mem_Iic _ _ @[simp] lemma mem_Iio : x ∈ Iio a ↔ x < a := locally_finite_order_bot.finset_mem_Iio _ _ @[simp, norm_cast] lemma coe_Iic (a : α) : (Iic a : set α) = set.Iic a := set.ext $ λ _, mem_Iic @[simp, norm_cast] lemma coe_Iio (a : α) : (Iio a : set α) = set.Iio a := set.ext $ λ _, mem_Iio end locally_finite_order_bot section order_top variables [locally_finite_order α] [order_top α] {a x : α} @[priority 100] -- See note [lower priority instance] instance _root_.locally_finite_order.to_locally_finite_order_top : locally_finite_order_top α := { finset_Ici := λ b, Icc b ⊤, finset_Ioi := λ b, Ioc b ⊤, finset_mem_Ici := λ a x, by rw [mem_Icc, and_iff_left le_top], finset_mem_Ioi := λ a x, by rw [mem_Ioc, and_iff_left le_top] } lemma Ici_eq_Icc (a : α) : Ici a = Icc a ⊤ := rfl lemma Ioi_eq_Ioc (a : α) : Ioi a = Ioc a ⊤ := rfl end order_top section order_bot variables [order_bot α] [locally_finite_order α] {b x : α} @[priority 100] -- See note [lower priority instance] instance locally_finite_order.to_locally_finite_order_bot : locally_finite_order_bot α := { finset_Iic := Icc ⊥, finset_Iio := Ico ⊥, finset_mem_Iic := λ a x, by rw [mem_Icc, and_iff_right bot_le], finset_mem_Iio := λ a x, by rw [mem_Ico, and_iff_right bot_le] } lemma Iic_eq_Icc : Iic = Icc (⊥ : α) := rfl lemma Iio_eq_Ico : Iio = Ico (⊥ : α) := rfl end order_bot end finset /-! ### Intervals as multisets -/ namespace multiset variables [preorder α] section locally_finite_order variables [locally_finite_order α] /-- The multiset of elements `x` such that `a ≤ x` and `x ≤ b`. Basically `set.Icc a b` as a multiset. -/ def Icc (a b : α) : multiset α := (finset.Icc a b).val /-- The multiset of elements `x` such that `a ≤ x` and `x < b`. Basically `set.Ico a b` as a multiset. -/ def Ico (a b : α) : multiset α := (finset.Ico a b).val /-- The multiset of elements `x` such that `a < x` and `x ≤ b`. Basically `set.Ioc a b` as a multiset. -/ def Ioc (a b : α) : multiset α := (finset.Ioc a b).val /-- The multiset of elements `x` such that `a < x` and `x < b`. Basically `set.Ioo a b` as a multiset. -/ def Ioo (a b : α) : multiset α := (finset.Ioo a b).val @[simp] lemma mem_Icc {a b x : α} : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := by rw [Icc, ←finset.mem_def, finset.mem_Icc] @[simp] lemma mem_Ico {a b x : α} : x ∈ Ico a b ↔ a ≤ x ∧ x < b := by rw [Ico, ←finset.mem_def, finset.mem_Ico] @[simp] lemma mem_Ioc {a b x : α} : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := by rw [Ioc, ←finset.mem_def, finset.mem_Ioc] @[simp] lemma mem_Ioo {a b x : α} : x ∈ Ioo a b ↔ a < x ∧ x < b := by rw [Ioo, ←finset.mem_def, finset.mem_Ioo] end locally_finite_order section locally_finite_order_top variables [locally_finite_order_top α] /-- The multiset of elements `x` such that `a ≤ x`. Basically `set.Ici a` as a multiset. -/ def Ici (a : α) : multiset α := (finset.Ici a).val /-- The multiset of elements `x` such that `a < x`. Basically `set.Ioi a` as a multiset. -/ def Ioi (a : α) : multiset α := (finset.Ioi a).val @[simp] lemma mem_Ici {a x : α} : x ∈ Ici a ↔ a ≤ x := by rw [Ici, ←finset.mem_def, finset.mem_Ici] @[simp] lemma mem_Ioi {a x : α} : x ∈ Ioi a ↔ a < x := by rw [Ioi, ←finset.mem_def, finset.mem_Ioi] end locally_finite_order_top section locally_finite_order_bot variables [locally_finite_order_bot α] /-- The multiset of elements `x` such that `x ≤ b`. Basically `set.Iic b` as a multiset. -/ def Iic (b : α) : multiset α := (finset.Iic b).val /-- The multiset of elements `x` such that `x < b`. Basically `set.Iio b` as a multiset. -/ def Iio (b : α) : multiset α := (finset.Iio b).val @[simp] lemma mem_Iic {b x : α} : x ∈ Iic b ↔ x ≤ b := by rw [Iic, ←finset.mem_def, finset.mem_Iic] @[simp] lemma mem_Iio {b x : α} : x ∈ Iio b ↔ x < b := by rw [Iio, ←finset.mem_def, finset.mem_Iio] end locally_finite_order_bot end multiset /-! ### Finiteness of `set` intervals -/ namespace set section preorder variables [preorder α] [locally_finite_order α] (a b : α) instance fintype_Icc : fintype (Icc a b) := fintype.of_finset (finset.Icc a b) (λ x, by rw [finset.mem_Icc, mem_Icc]) instance fintype_Ico : fintype (Ico a b) := fintype.of_finset (finset.Ico a b) (λ x, by rw [finset.mem_Ico, mem_Ico]) instance fintype_Ioc : fintype (Ioc a b) := fintype.of_finset (finset.Ioc a b) (λ x, by rw [finset.mem_Ioc, mem_Ioc]) instance fintype_Ioo : fintype (Ioo a b) := fintype.of_finset (finset.Ioo a b) (λ x, by rw [finset.mem_Ioo, mem_Ioo]) lemma finite_Icc : (Icc a b).finite := (Icc a b).to_finite lemma finite_Ico : (Ico a b).finite := (Ico a b).to_finite lemma finite_Ioc : (Ioc a b).finite := (Ioc a b).to_finite lemma finite_Ioo : (Ioo a b).finite := (Ioo a b).to_finite end preorder section order_top variables [preorder α] [locally_finite_order_top α] (a : α) instance fintype_Ici : fintype (Ici a) := fintype.of_finset (finset.Ici a) (λ x, by rw [finset.mem_Ici, mem_Ici]) instance fintype_Ioi : fintype (Ioi a) := fintype.of_finset (finset.Ioi a) (λ x, by rw [finset.mem_Ioi, mem_Ioi]) lemma finite_Ici : (Ici a).finite := (Ici a).to_finite lemma finite_Ioi : (Ioi a).finite := (Ioi a).to_finite end order_top section order_bot variables [preorder α] [locally_finite_order_bot α] (b : α) instance fintype_Iic : fintype (Iic b) := fintype.of_finset (finset.Iic b) (λ x, by rw [finset.mem_Iic, mem_Iic]) instance fintype_Iio : fintype (Iio b) := fintype.of_finset (finset.Iio b) (λ x, by rw [finset.mem_Iio, mem_Iio]) lemma finite_Iic : (Iic b).finite := (Iic b).to_finite lemma finite_Iio : (Iio b).finite := (Iio b).to_finite end order_bot end set /-! ### Instances -/ open finset section preorder variables [preorder α] [preorder β] /-- A noncomputable constructor from the finiteness of all closed intervals. -/ noncomputable def locally_finite_order.of_finite_Icc (h : ∀ a b : α, (set.Icc a b).finite) : locally_finite_order α := @locally_finite_order.of_Icc' α _ (classical.dec_rel _) (λ a b, (h a b).to_finset) (λ a b x, by rw [set.finite.mem_to_finset, set.mem_Icc]) /-- A fintype is a locally finite order. This is not an instance as it would not be defeq to better instances such as `fin.locally_finite_order`. -/ @[reducible] def fintype.to_locally_finite_order [fintype α] [@decidable_rel α (<)] [@decidable_rel α (≤)] : locally_finite_order α := { finset_Icc := λ a b, (set.Icc a b).to_finset, finset_Ico := λ a b, (set.Ico a b).to_finset, finset_Ioc := λ a b, (set.Ioc a b).to_finset, finset_Ioo := λ a b, (set.Ioo a b).to_finset, finset_mem_Icc := λ a b x, by simp only [set.mem_to_finset, set.mem_Icc], finset_mem_Ico := λ a b x, by simp only [set.mem_to_finset, set.mem_Ico], finset_mem_Ioc := λ a b x, by simp only [set.mem_to_finset, set.mem_Ioc], finset_mem_Ioo := λ a b x, by simp only [set.mem_to_finset, set.mem_Ioo] } instance : subsingleton (locally_finite_order α) := subsingleton.intro (λ h₀ h₁, begin cases h₀, cases h₁, have hIcc : h₀_finset_Icc = h₁_finset_Icc, { ext a b x, rw [h₀_finset_mem_Icc, h₁_finset_mem_Icc] }, have hIco : h₀_finset_Ico = h₁_finset_Ico, { ext a b x, rw [h₀_finset_mem_Ico, h₁_finset_mem_Ico] }, have hIoc : h₀_finset_Ioc = h₁_finset_Ioc, { ext a b x, rw [h₀_finset_mem_Ioc, h₁_finset_mem_Ioc] }, have hIoo : h₀_finset_Ioo = h₁_finset_Ioo, { ext a b x, rw [h₀_finset_mem_Ioo, h₁_finset_mem_Ioo] }, simp_rw [hIcc, hIco, hIoc, hIoo], end) instance : subsingleton (locally_finite_order_top α) := subsingleton.intro $ λ h₀ h₁, begin cases h₀, cases h₁, have hIci : h₀_finset_Ici = h₁_finset_Ici, { ext a b x, rw [h₀_finset_mem_Ici, h₁_finset_mem_Ici] }, have hIoi : h₀_finset_Ioi = h₁_finset_Ioi, { ext a b x, rw [h₀_finset_mem_Ioi, h₁_finset_mem_Ioi] }, simp_rw [hIci, hIoi], end instance : subsingleton (locally_finite_order_bot α) := subsingleton.intro $ λ h₀ h₁, begin cases h₀, cases h₁, have hIic : h₀_finset_Iic = h₁_finset_Iic, { ext a b x, rw [h₀_finset_mem_Iic, h₁_finset_mem_Iic] }, have hIio : h₀_finset_Iio = h₁_finset_Iio, { ext a b x, rw [h₀_finset_mem_Iio, h₁_finset_mem_Iio] }, simp_rw [hIic, hIio], end -- Should this be called `locally_finite_order.lift`? /-- Given an order embedding `α ↪o β`, pulls back the `locally_finite_order` on `β` to `α`. -/ protected noncomputable def order_embedding.locally_finite_order [locally_finite_order β] (f : α ↪o β) : locally_finite_order α := { finset_Icc := λ a b, (Icc (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_Ico := λ a b, (Ico (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_Ioc := λ a b, (Ioc (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_Ioo := λ a b, (Ioo (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_mem_Icc := λ a b x, by rw [mem_preimage, mem_Icc, f.le_iff_le, f.le_iff_le], finset_mem_Ico := λ a b x, by rw [mem_preimage, mem_Ico, f.le_iff_le, f.lt_iff_lt], finset_mem_Ioc := λ a b x, by rw [mem_preimage, mem_Ioc, f.lt_iff_lt, f.le_iff_le], finset_mem_Ioo := λ a b x, by rw [mem_preimage, mem_Ioo, f.lt_iff_lt, f.lt_iff_lt] } open order_dual section locally_finite_order variables [locally_finite_order α] (a b : α) /-- Note we define `Icc (to_dual a) (to_dual b)` as `Icc α _ _ b a` (which has type `finset α` not `finset αᵒᵈ`!) instead of `(Icc b a).map to_dual.to_embedding` as this means the following is defeq: ``` lemma this : (Icc (to_dual (to_dual a)) (to_dual (to_dual b)) : _) = (Icc a b : _) := rfl ``` -/ instance : locally_finite_order αᵒᵈ := { finset_Icc := λ a b, @Icc α _ _ (of_dual b) (of_dual a), finset_Ico := λ a b, @Ioc α _ _ (of_dual b) (of_dual a), finset_Ioc := λ a b, @Ico α _ _ (of_dual b) (of_dual a), finset_Ioo := λ a b, @Ioo α _ _ (of_dual b) (of_dual a), finset_mem_Icc := λ a b x, mem_Icc.trans (and_comm _ _), finset_mem_Ico := λ a b x, mem_Ioc.trans (and_comm _ _), finset_mem_Ioc := λ a b x, mem_Ico.trans (and_comm _ _), finset_mem_Ioo := λ a b x, mem_Ioo.trans (and_comm _ _) } lemma Icc_to_dual : Icc (to_dual a) (to_dual b) = (Icc b a).map to_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Icc, mem_Icc], exact and_comm _ _ } lemma Ico_to_dual : Ico (to_dual a) (to_dual b) = (Ioc b a).map to_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ico, mem_Ioc], exact and_comm _ _ } lemma Ioc_to_dual : Ioc (to_dual a) (to_dual b) = (Ico b a).map to_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioc, mem_Ico], exact and_comm _ _ } lemma Ioo_to_dual : Ioo (to_dual a) (to_dual b) = (Ioo b a).map to_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioo, mem_Ioo], exact and_comm _ _ } lemma Icc_of_dual (a b : αᵒᵈ) : Icc (of_dual a) (of_dual b) = (Icc b a).map of_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Icc, mem_Icc], exact and_comm _ _ } lemma Ico_of_dual (a b : αᵒᵈ) : Ico (of_dual a) (of_dual b) = (Ioc b a).map of_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ico, mem_Ioc], exact and_comm _ _ } lemma Ioc_of_dual (a b : αᵒᵈ) : Ioc (of_dual a) (of_dual b) = (Ico b a).map of_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioc, mem_Ico], exact and_comm _ _ } lemma Ioo_of_dual (a b : αᵒᵈ) : Ioo (of_dual a) (of_dual b) = (Ioo b a).map of_dual.to_embedding := by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioo, mem_Ioo], exact and_comm _ _ } end locally_finite_order section locally_finite_order_top variables [locally_finite_order_top α] /-- Note we define `Iic (to_dual a)` as `Ici a` (which has type `finset α` not `finset αᵒᵈ`!) instead of `(Ici a).map to_dual.to_embedding` as this means the following is defeq: ``` lemma this : (Iic (to_dual (to_dual a)) : _) = (Iic a : _) := rfl ``` -/ instance : locally_finite_order_bot αᵒᵈ := { finset_Iic := λ a, @Ici α _ _ (of_dual a), finset_Iio := λ a, @Ioi α _ _ (of_dual a), finset_mem_Iic := λ a x, mem_Ici, finset_mem_Iio := λ a x, mem_Ioi } lemma Iic_to_dual (a : α) : Iic (to_dual a) = (Ici a).map to_dual.to_embedding := map_refl.symm lemma Iio_to_dual (a : α) : Iio (to_dual a) = (Ioi a).map to_dual.to_embedding := map_refl.symm lemma Ici_of_dual (a : αᵒᵈ) : Ici (of_dual a) = (Iic a).map of_dual.to_embedding := map_refl.symm lemma Ioi_of_dual (a : αᵒᵈ) : Ioi (of_dual a) = (Iio a).map of_dual.to_embedding := map_refl.symm end locally_finite_order_top section locally_finite_order_top variables [locally_finite_order_bot α] /-- Note we define `Ici (to_dual a)` as `Iic a` (which has type `finset α` not `finset αᵒᵈ`!) instead of `(Iic a).map to_dual.to_embedding` as this means the following is defeq: ``` lemma this : (Ici (to_dual (to_dual a)) : _) = (Ici a : _) := rfl ``` -/ instance : locally_finite_order_top αᵒᵈ := { finset_Ici := λ a, @Iic α _ _ (of_dual a), finset_Ioi := λ a, @Iio α _ _ (of_dual a), finset_mem_Ici := λ a x, mem_Iic, finset_mem_Ioi := λ a x, mem_Iio } lemma Ici_to_dual (a : α) : Ici (to_dual a) = (Iic a).map to_dual.to_embedding := map_refl.symm lemma Ioi_to_dual (a : α) : Ioi (to_dual a) = (Iio a).map to_dual.to_embedding := map_refl.symm lemma Iic_of_dual (a : αᵒᵈ) : Iic (of_dual a) = (Ici a).map of_dual.to_embedding := map_refl.symm lemma Iio_of_dual (a : αᵒᵈ) : Iio (of_dual a) = (Ioi a).map of_dual.to_embedding := map_refl.symm end locally_finite_order_top namespace prod instance [locally_finite_order α] [locally_finite_order β] [decidable_rel ((≤) : α × β → α × β → Prop)] : locally_finite_order (α × β) := locally_finite_order.of_Icc' (α × β) (λ a b, Icc a.fst b.fst ×ˢ Icc a.snd b.snd) (λ a b x, by { rw [mem_product, mem_Icc, mem_Icc, and_and_and_comm], refl }) instance [locally_finite_order_top α] [locally_finite_order_top β] [decidable_rel ((≤) : α × β → α × β → Prop)] : locally_finite_order_top (α × β) := locally_finite_order_top.of_Ici' (α × β) (λ a, Ici a.fst ×ˢ Ici a.snd) (λ a x, by { rw [mem_product, mem_Ici, mem_Ici], refl }) instance [locally_finite_order_bot α] [locally_finite_order_bot β] [decidable_rel ((≤) : α × β → α × β → Prop)] : locally_finite_order_bot (α × β) := locally_finite_order_bot.of_Iic' (α × β) (λ a, Iic a.fst ×ˢ Iic a.snd) (λ a x, by { rw [mem_product, mem_Iic, mem_Iic], refl }) lemma Icc_eq [locally_finite_order α] [locally_finite_order β] [decidable_rel ((≤) : α × β → α × β → Prop)] (p q : α × β) : finset.Icc p q = finset.Icc p.1 q.1 ×ˢ finset.Icc p.2 q.2 := rfl @[simp] lemma Icc_mk_mk [locally_finite_order α] [locally_finite_order β] [decidable_rel ((≤) : α × β → α × β → Prop)] (a₁ a₂ : α) (b₁ b₂ : β) : finset.Icc (a₁, b₁) (a₂, b₂) = finset.Icc a₁ a₂ ×ˢ finset.Icc b₁ b₂ := rfl lemma card_Icc [locally_finite_order α] [locally_finite_order β] [decidable_rel ((≤) : α × β → α × β → Prop)] (p q : α × β) : (finset.Icc p q).card = (finset.Icc p.1 q.1).card * (finset.Icc p.2 q.2).card := finset.card_product _ _ end prod end preorder /-! #### `with_top`, `with_bot` Adding a `⊤` to a locally finite `order_top` keeps it locally finite. Adding a `⊥` to a locally finite `order_bot` keeps it locally finite. -/ namespace with_top variables (α) [partial_order α] [order_top α] [locally_finite_order α] local attribute [pattern] coe local attribute [simp] option.mem_iff instance : locally_finite_order (with_top α) := { finset_Icc := λ a b, match a, b with | ⊤, ⊤ := {⊤} | ⊤, (b : α) := ∅ | (a : α), ⊤ := insert_none (Ici a) | (a : α), (b : α) := (Icc a b).map embedding.coe_option end, finset_Ico := λ a b, match a, b with | ⊤, _ := ∅ | (a : α), ⊤ := (Ici a).map embedding.coe_option | (a : α), (b : α) := (Ico a b).map embedding.coe_option end, finset_Ioc := λ a b, match a, b with | ⊤, _ := ∅ | (a : α), ⊤ := insert_none (Ioi a) | (a : α), (b : α) := (Ioc a b).map embedding.coe_option end, finset_Ioo := λ a b, match a, b with | ⊤, _ := ∅ | (a : α), ⊤ := (Ioi a).map embedding.coe_option | (a : α), (b : α) := (Ioo a b).map embedding.coe_option end, finset_mem_Icc := λ a b x, match a, b, x with | ⊤, ⊤, x := mem_singleton.trans (le_antisymm_iff.trans $ and_comm _ _) | ⊤, (b : α), x := iff_of_false (not_mem_empty _) (λ h, (h.1.trans h.2).not_lt $ coe_lt_top _) | (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_1] | (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_1, coe_eq_coe] | (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_1] | (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_1, coe_eq_coe] end, finset_mem_Ico := λ a b x, match a, b, x with | ⊤, b, x := iff_of_false (not_mem_empty _) (λ h, not_top_lt $ h.1.trans_lt h.2) | (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_2] | (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_2, coe_eq_coe, coe_lt_top] | (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_2] | (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_2, coe_eq_coe, coe_lt_coe] end, finset_mem_Ioc := λ a b x, match a, b, x with | ⊤, b, x := iff_of_false (not_mem_empty _) (λ h, not_top_lt $ h.1.trans_le h.2) | (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_3, coe_lt_top] | (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_3, coe_eq_coe, coe_lt_coe] | (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_3] | (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_3, coe_eq_coe, coe_lt_coe] end, finset_mem_Ioo := λ a b x, match a, b, x with | ⊤, b, x := iff_of_false (not_mem_empty _) (λ h, not_top_lt $ h.1.trans h.2) | (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_4, coe_lt_top] | (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_4, coe_eq_coe, coe_lt_coe, coe_lt_top] | (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_4] | (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_4, coe_eq_coe, coe_lt_coe] end } variables (a b : α) lemma Icc_coe_top : Icc (a : with_top α) ⊤ = insert_none (Ici a) := rfl lemma Icc_coe_coe : Icc (a : with_top α) b = (Icc a b).map embedding.coe_option := rfl lemma Ico_coe_top : Ico (a : with_top α) ⊤ = (Ici a).map embedding.coe_option := rfl lemma Ico_coe_coe : Ico (a : with_top α) b = (Ico a b).map embedding.coe_option := rfl lemma Ioc_coe_top : Ioc (a : with_top α) ⊤ = insert_none (Ioi a) := rfl lemma Ioc_coe_coe : Ioc (a : with_top α) b = (Ioc a b).map embedding.coe_option := rfl lemma Ioo_coe_top : Ioo (a : with_top α) ⊤ = (Ioi a).map embedding.coe_option := rfl lemma Ioo_coe_coe : Ioo (a : with_top α) b = (Ioo a b).map embedding.coe_option := rfl end with_top namespace with_bot variables (α) [partial_order α] [order_bot α] [locally_finite_order α] instance : locally_finite_order (with_bot α) := @order_dual.locally_finite_order (with_top αᵒᵈ) _ _ variables (a b : α) lemma Icc_bot_coe : Icc (⊥ : with_bot α) b = insert_none (Iic b) := rfl lemma Icc_coe_coe : Icc (a : with_bot α) b = (Icc a b).map embedding.coe_option := rfl lemma Ico_bot_coe : Ico (⊥ : with_bot α) b = insert_none (Iio b) := rfl lemma Ico_coe_coe : Ico (a : with_bot α) b = (Ico a b).map embedding.coe_option := rfl lemma Ioc_bot_coe : Ioc (⊥ : with_bot α) b = (Iic b).map embedding.coe_option := rfl lemma Ioc_coe_coe : Ioc (a : with_bot α) b = (Ioc a b).map embedding.coe_option := rfl lemma Ioo_bot_coe : Ioo (⊥ : with_bot α) b = (Iio b).map embedding.coe_option := rfl lemma Ioo_coe_coe : Ioo (a : with_bot α) b = (Ioo a b).map embedding.coe_option := rfl end with_bot namespace order_iso variables [preorder α] [preorder β] /-! #### Transfer locally finite orders across order isomorphisms -/ /-- Transfer `locally_finite_order` across an `order_iso`. -/ @[reducible] -- See note [reducible non-instances] def locally_finite_order [locally_finite_order β] (f : α ≃o β) : locally_finite_order α := { finset_Icc := λ a b, (Icc (f a) (f b)).map f.symm.to_equiv.to_embedding, finset_Ico := λ a b, (Ico (f a) (f b)).map f.symm.to_equiv.to_embedding, finset_Ioc := λ a b, (Ioc (f a) (f b)).map f.symm.to_equiv.to_embedding, finset_Ioo := λ a b, (Ioo (f a) (f b)).map f.symm.to_equiv.to_embedding, finset_mem_Icc := by simp, finset_mem_Ico := by simp, finset_mem_Ioc := by simp, finset_mem_Ioo := by simp } /-- Transfer `locally_finite_order_top` across an `order_iso`. -/ @[reducible] -- See note [reducible non-instances] def locally_finite_order_top [locally_finite_order_top β] (f : α ≃o β) : locally_finite_order_top α := { finset_Ici := λ a, (Ici (f a)).map f.symm.to_equiv.to_embedding, finset_Ioi := λ a, (Ioi (f a)).map f.symm.to_equiv.to_embedding, finset_mem_Ici := by simp, finset_mem_Ioi := by simp } /-- Transfer `locally_finite_order_bot` across an `order_iso`. -/ @[reducible] -- See note [reducible non-instances] def locally_finite_order_bot [locally_finite_order_bot β] (f : α ≃o β) : locally_finite_order_bot α := { finset_Iic := λ a, (Iic (f a)).map f.symm.to_equiv.to_embedding, finset_Iio := λ a, (Iio (f a)).map f.symm.to_equiv.to_embedding, finset_mem_Iic := by simp, finset_mem_Iio := by simp } end order_iso /-! #### Subtype of a locally finite order -/ variables [preorder α] (p : α → Prop) [decidable_pred p] instance [locally_finite_order α] : locally_finite_order (subtype p) := { finset_Icc := λ a b, (Icc (a : α) b).subtype p, finset_Ico := λ a b, (Ico (a : α) b).subtype p, finset_Ioc := λ a b, (Ioc (a : α) b).subtype p, finset_Ioo := λ a b, (Ioo (a : α) b).subtype p, finset_mem_Icc := λ a b x, by simp_rw [finset.mem_subtype, mem_Icc, subtype.coe_le_coe], finset_mem_Ico := λ a b x, by simp_rw [finset.mem_subtype, mem_Ico, subtype.coe_le_coe, subtype.coe_lt_coe], finset_mem_Ioc := λ a b x, by simp_rw [finset.mem_subtype, mem_Ioc, subtype.coe_le_coe, subtype.coe_lt_coe], finset_mem_Ioo := λ a b x, by simp_rw [finset.mem_subtype, mem_Ioo, subtype.coe_lt_coe] } instance [locally_finite_order_top α] : locally_finite_order_top (subtype p) := { finset_Ici := λ a, (Ici (a : α)).subtype p, finset_Ioi := λ a, (Ioi (a : α)).subtype p, finset_mem_Ici := λ a x, by simp_rw [finset.mem_subtype, mem_Ici, subtype.coe_le_coe], finset_mem_Ioi := λ a x, by simp_rw [finset.mem_subtype, mem_Ioi, subtype.coe_lt_coe] } instance [locally_finite_order_bot α] : locally_finite_order_bot (subtype p) := { finset_Iic := λ a, (Iic (a : α)).subtype p, finset_Iio := λ a, (Iio (a : α)).subtype p, finset_mem_Iic := λ a x, by simp_rw [finset.mem_subtype, mem_Iic, subtype.coe_le_coe], finset_mem_Iio := λ a x, by simp_rw [finset.mem_subtype, mem_Iio, subtype.coe_lt_coe] } namespace finset section locally_finite_order variables [locally_finite_order α] (a b : subtype p) lemma subtype_Icc_eq : Icc a b = (Icc (a : α) b).subtype p := rfl lemma subtype_Ico_eq : Ico a b = (Ico (a : α) b).subtype p := rfl lemma subtype_Ioc_eq : Ioc a b = (Ioc (a : α) b).subtype p := rfl lemma subtype_Ioo_eq : Ioo a b = (Ioo (a : α) b).subtype p := rfl variables (hp : ∀ ⦃a b x⦄, a ≤ x → x ≤ b → p a → p b → p x) include hp lemma map_subtype_embedding_Icc : (Icc a b).map (embedding.subtype p) = Icc a b := begin rw subtype_Icc_eq, refine finset.subtype_map_of_mem (λ x hx, _), rw mem_Icc at hx, exact hp hx.1 hx.2 a.prop b.prop, end lemma map_subtype_embedding_Ico : (Ico a b).map (embedding.subtype p) = Ico a b := begin rw subtype_Ico_eq, refine finset.subtype_map_of_mem (λ x hx, _), rw mem_Ico at hx, exact hp hx.1 hx.2.le a.prop b.prop, end lemma map_subtype_embedding_Ioc : (Ioc a b).map (embedding.subtype p) = Ioc a b := begin rw subtype_Ioc_eq, refine finset.subtype_map_of_mem (λ x hx, _), rw mem_Ioc at hx, exact hp hx.1.le hx.2 a.prop b.prop, end lemma map_subtype_embedding_Ioo : (Ioo a b).map (embedding.subtype p) = Ioo a b := begin rw subtype_Ioo_eq, refine finset.subtype_map_of_mem (λ x hx, _), rw mem_Ioo at hx, exact hp hx.1.le hx.2.le a.prop b.prop, end end locally_finite_order section locally_finite_order_top variables [locally_finite_order_top α] (a : subtype p) lemma subtype_Ici_eq : Ici a = (Ici (a : α)).subtype p := rfl lemma subtype_Ioi_eq : Ioi a = (Ioi (a : α)).subtype p := rfl variables (hp : ∀ ⦃a x⦄, a ≤ x → p a → p x) include hp lemma map_subtype_embedding_Ici : (Ici a).map (embedding.subtype p) = Ici a := by { rw subtype_Ici_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Ici.1 hx) a.prop) } lemma map_subtype_embedding_Ioi : (Ioi a).map (embedding.subtype p) = Ioi a := by { rw subtype_Ioi_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Ioi.1 hx).le a.prop) } end locally_finite_order_top section locally_finite_order_bot variables [locally_finite_order_bot α] (a : subtype p) lemma subtype_Iic_eq : Iic a = (Iic (a : α)).subtype p := rfl lemma subtype_Iio_eq : Iio a = (Iio (a : α)).subtype p := rfl variables (hp : ∀ ⦃a x⦄, x ≤ a → p a → p x) include hp lemma map_subtype_embedding_Iic : (Iic a).map (embedding.subtype p) = Iic a := by { rw subtype_Iic_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Iic.1 hx) a.prop) } lemma map_subtype_embedding_Iio : (Iio a).map (embedding.subtype p) = Iio a := by { rw subtype_Iio_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Iio.1 hx).le a.prop) } end locally_finite_order_bot end finset
50309f97f135951912076be655db9c96b7338285
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/set_theory/game/short.lean
314d2c934e62a9f67c441548442b0504c742d4f8
[ "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,925
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import set_theory.game import data.fintype.basic /-! # Short games A combinatorial game is `short` [Conway, ch.9][conway2001] if it has only finitely many positions. In particular, this means there is a finite set of moves at every point. We prove that the order relations `≤` and `<`, and the equivalence relation `≈`, are decidable on short games, although unfortunately in practice `dec_trivial` doesn't seem to be able to prove anything using these instances. -/ universes u namespace pgame /-- A short game is a game with a finite set of moves at every turn. -/ inductive short : pgame.{u} → Type (u+1) | mk : Π {α β : Type u} {L : α → pgame.{u}} {R : β → pgame.{u}} (sL : ∀ i : α, short (L i)) (sR : ∀ j : β, short (R j)) [fintype α] [fintype β], short ⟨α, β, L, R⟩ instance subsingleton_short : Π (x : pgame), subsingleton (short x) | (mk xl xr xL xR) := ⟨λ a b, begin cases a, cases b, congr, { funext, apply @subsingleton.elim _ (subsingleton_short (xL x)) }, { funext, apply @subsingleton.elim _ (subsingleton_short (xR x)) }, end⟩ using_well_founded { dec_tac := pgame_wf_tac } /-- A synonym for `short.mk` that specifies the pgame in an implicit argument. -/ def short.mk' {x : pgame} [fintype x.left_moves] [fintype x.right_moves] (sL : ∀ i : x.left_moves, short (x.move_left i)) (sR : ∀ j : x.right_moves, short (x.move_right j)) : short x := by unfreezingI { cases x, dsimp at * }; exact short.mk sL sR attribute [class] short /-- Extracting the `fintype` instance for the indexing type for Left's moves in a short game. This is an unindexed typeclass, so it can't be made a global instance. -/ def fintype_left {α β : Type u} {L : α → pgame.{u}} {R : β → pgame.{u}} [S : short ⟨α, β, L, R⟩] : fintype α := by { casesI S with _ _ _ _ _ _ F _, exact F } local attribute [instance] fintype_left instance fintype_left_moves (x : pgame) [S : short x] : fintype (x.left_moves) := by { casesI x, dsimp, apply_instance } /-- Extracting the `fintype` instance for the indexing type for Right's moves in a short game. This is an unindexed typeclass, so it can't be made a global instance. -/ def fintype_right {α β : Type u} {L : α → pgame.{u}} {R : β → pgame.{u}} [S : short ⟨α, β, L, R⟩] : fintype β := by { casesI S with _ _ _ _ _ _ _ F, exact F } local attribute [instance] fintype_right instance fintype_right_moves (x : pgame) [S : short x] : fintype (x.right_moves) := by { casesI x, dsimp, apply_instance } instance move_left_short (x : pgame) [S : short x] (i : x.left_moves) : short (x.move_left i) := by { casesI S with _ _ _ _ L _ _ _, apply L } /-- Extracting the `short` instance for a move by Left. This would be a dangerous instance potentially introducing new metavariables in typeclass search, so we only make it an instance locally. -/ def move_left_short' {xl xr} (xL xR) [S : short (mk xl xr xL xR)] (i : xl) : short (xL i) := by { casesI S with _ _ _ _ L _ _ _, apply L } local attribute [instance] move_left_short' instance move_right_short (x : pgame) [S : short x] (j : x.right_moves) : short (x.move_right j) := by { casesI S with _ _ _ _ _ R _ _, apply R } /-- Extracting the `short` instance for a move by Right. This would be a dangerous instance potentially introducing new metavariables in typeclass search, so we only make it an instance locally. -/ def move_right_short' {xl xr} (xL xR) [S : short (mk xl xr xL xR)] (j : xr) : short (xR j) := by { casesI S with _ _ _ _ _ R _ _, apply R } local attribute [instance] move_right_short' instance short.of_pempty {xL} {xR} : short (mk pempty pempty xL xR) := short.mk (λ i, pempty.elim i) (λ j, pempty.elim j) instance short_0 : short 0 := short.mk (λ i, by cases i) (λ j, by cases j) instance short_1 : short 1 := short.mk (λ i, begin cases i, apply_instance, end) (λ j, by cases j) /-- Evidence that every `pgame` in a list is `short`. -/ inductive list_short : list pgame.{u} → Type (u+1) | nil : list_short [] | cons : Π (hd : pgame.{u}) [short hd] (tl : list pgame.{u}) [list_short tl], list_short (hd :: tl) attribute [class] list_short attribute [instance] list_short.nil list_short.cons instance list_short_nth_le : Π (L : list pgame.{u}) [list_short L] (i : fin (list.length L)), short (list.nth_le L i i.is_lt) | [] _ n := begin exfalso, rcases n with ⟨_, ⟨⟩⟩, end | (hd :: tl) (@list_short.cons _ S _ _) ⟨0, _⟩ := S | (hd :: tl) (@list_short.cons _ _ _ S) ⟨n+1, h⟩ := @list_short_nth_le tl S ⟨n, (add_lt_add_iff_right 1).mp h⟩ instance short_of_lists : Π (L R : list pgame) [list_short L] [list_short R], short (pgame.of_lists L R) | L R _ _ := by { resetI, apply short.mk, { intros, apply_instance }, { intros, apply pgame.list_short_nth_le /- where does the subtype.val come from? -/ } } /-- If `x` is a short game, and `y` is a relabelling of `x`, then `y` is also short. -/ def short_of_relabelling : Π {x y : pgame.{u}} (R : relabelling x y) (S : short x), short y | x y ⟨L, R, rL, rR⟩ S := begin resetI, haveI := (fintype.of_equiv _ L), haveI := (fintype.of_equiv _ R), exact short.mk' (λ i, by { rw ←(L.right_inv i), apply short_of_relabelling (rL (L.symm i)) infer_instance, }) (λ j, short_of_relabelling (rR j) infer_instance) end /-- If `x` has no left move or right moves, it is (very!) short. -/ def short_of_equiv_empty {x : pgame.{u}} (el : x.left_moves ≃ pempty) (er : x.right_moves ≃ pempty) : short x := short_of_relabelling (relabel_relabelling el er).symm short.of_pempty instance short_neg : Π (x : pgame.{u}) [short x], short (-x) | (mk xl xr xL xR) _ := begin resetI, apply short.mk, { rintro i, apply short_neg _, apply_instance, }, { rintro j, apply short_neg _, apply_instance, } end using_well_founded { dec_tac := pgame_wf_tac } instance short_add : Π (x y : pgame.{u}) [short x] [short y], short (x + y) | (mk xl xr xL xR) (mk yl yr yL yR) _ _ := begin resetI, apply short.mk, { rintro ⟨i⟩, { apply short_add, }, { change short (mk xl xr xL xR + yL i), apply short_add, } }, { rintro ⟨j⟩, { apply short_add, }, { change short (mk xl xr xL xR + yR j), apply short_add, } }, end using_well_founded { dec_tac := pgame_wf_tac } instance short_nat : Π n : ℕ, short n | 0 := pgame.short_0 | (n+1) := @pgame.short_add _ _ (short_nat n) pgame.short_1 instance short_bit0 (x : pgame.{u}) [short x] : short (bit0 x) := by { dsimp [bit0], apply_instance } instance short_bit1 (x : pgame.{u}) [short x] : short (bit1 x) := by { dsimp [bit1], apply_instance } /-- Auxiliary construction of decidability instances. We build `decidable (x ≤ y)` and `decidable (x < y)` in a simultaneous induction. Instances for the two projections separately are provided below. -/ def le_lt_decidable : Π (x y : pgame.{u}) [short x] [short y], decidable (x ≤ y) × decidable (x < y) | (mk xl xr xL xR) (mk yl yr yL yR) shortx shorty := begin resetI, split, { refine @decidable_of_iff' _ _ mk_le_mk (id _), apply @and.decidable _ _ _ _, { apply @fintype.decidable_forall_fintype xl _ _ (by apply_instance), intro i, apply (@le_lt_decidable _ _ _ _).2; apply_instance, }, { apply @fintype.decidable_forall_fintype yr _ _ (by apply_instance), intro i, apply (@le_lt_decidable _ _ _ _).2; apply_instance, }, }, { refine @decidable_of_iff' _ _ mk_lt_mk (id _), apply @or.decidable _ _ _ _, { apply @fintype.decidable_exists_fintype yl _ _ (by apply_instance), intro i, apply (@le_lt_decidable _ _ _ _).1; apply_instance, }, { apply @fintype.decidable_exists_fintype xr _ _ (by apply_instance), intro i, apply (@le_lt_decidable _ _ _ _).1; apply_instance, }, }, end using_well_founded { dec_tac := pgame_wf_tac } instance le_decidable (x y : pgame.{u}) [short x] [short y] : decidable (x ≤ y) := (le_lt_decidable x y).1 instance lt_decidable (x y : pgame.{u}) [short x] [short y] : decidable (x < y) := (le_lt_decidable x y).2 instance equiv_decidable (x y : pgame.{u}) [short x] [short y] : decidable (x ≈ y) := and.decidable example : short 0 := by apply_instance example : short 1 := by apply_instance example : short 2 := by apply_instance example : short (-2) := by apply_instance example : short (of_lists [0] [1]) := by apply_instance example : short (of_lists [-2, -1] [1]) := by apply_instance example : short (0 + 0) := by apply_instance example : decidable ((1 : pgame) ≤ 1) := by apply_instance -- No longer works since definitional reduction of well-founded definitions has been restricted. -- example : (0 : pgame) ≤ 0 := dec_trivial -- example : (1 : pgame) ≤ 1 := dec_trivial end pgame
fbc1eb64ccaa3b642ae7b69655ed7692c065a34d
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/stream/basic.lean
8fa1d5037a4be4ab3bc0d2ea4ca5c107d2146577
[ "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
383
lean
/- Copyright (c) 2020 Gabriel Ebner, Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Simon Hudon -/ import tactic.ext data.stream /-! # Additional instances and attributes for streams -/ attribute [ext] stream.ext instance {α} [inhabited α] : inhabited (stream α) := ⟨stream.const (default _)⟩
7791ec97654587a4b7c031325d1cebbde3f4f456
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1817.lean
e77ba29c23e38e58d0673812698bef69b7c6f12b
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
219
lean
def f : int → int := λ _, 0 #check int.add (-1) 1 #check (-1 : int) #check 2 + (-1 : int) #check (2 + -1 : int) #check f (-1) #check 2 * (-1 : int) #check (2 * -1 : int) #check f 1 < -2 #check (- - 2 : int)
df0887aa0e7a493ce04adb15d9caec17037cbf40
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/affine_space/ordered.lean
fc815aef1fcc4588b706144703600261fc7b57ec
[]
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
18,741
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.affine_space.midpoint import Mathlib.algebra.module.ordered import Mathlib.tactic.field_simp import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Ordered modules as affine spaces In this file we define the slope of a function `f : k → PE` taking values in an affine space over `k` and prove some theorems about `slope` and `line_map` in the case when `PE` is an ordered semimodule over `k`. The `slope` function naturally appears in the Mean Value Theorem, and in the proof of the fact that a function with nonnegative second derivative on an interval is convex on this interval. In the third part of this file we prove inequalities that will be used in `analysis.convex.basic` to link convexity of a function on an interval to monotonicity of the slope, see section docstring below for details. ## Implementation notes We do not introduce the notion of ordered affine spaces (yet?). Instead, we prove various theorems for an ordered semimodule interpreted as an affine space. ## Tags affine space, ordered semimodule, slope -/ /-! ### Definition of `slope` and basic properties In this section we define `slope f a b` and prove some properties that do not require order on the codomain. -/ /-- `slope f a b = (b - a)⁻¹ • (f b -ᵥ f a)` is the slope of a function `f` on the interval `[a, b]`. Note that `slope f a a = 0`, not the derivative of `f` at `a`. -/ def slope {k : Type u_1} {E : Type u_2} {PE : Type u_3} [field k] [add_comm_group E] [semimodule k E] [add_torsor E PE] (f : k → PE) (a : k) (b : k) : E := b - a⁻¹ • (f b -ᵥ f a) theorem slope_def_field {k : Type u_1} [field k] (f : k → k) (a : k) (b : k) : slope f a b = (f b - f a) / (b - a) := Eq.symm div_eq_inv_mul @[simp] theorem slope_same {k : Type u_1} {E : Type u_2} {PE : Type u_3} [field k] [add_comm_group E] [semimodule k E] [add_torsor E PE] (f : k → PE) (a : k) : slope f a a = 0 := sorry theorem eq_of_slope_eq_zero {k : Type u_1} {E : Type u_2} {PE : Type u_3} [field k] [add_comm_group E] [semimodule k E] [add_torsor E PE] {f : k → PE} {a : k} {b : k} (h : slope f a b = 0) : f a = f b := sorry theorem slope_comm {k : Type u_1} {E : Type u_2} {PE : Type u_3} [field k] [add_comm_group E] [semimodule k E] [add_torsor E PE] (f : k → PE) (a : k) (b : k) : slope f a b = slope f b a := sorry /-- `slope f a c` is a linear combination of `slope f a b` and `slope f b c`. This version explicitly provides coefficients. If `a ≠ c`, then the sum of the coefficients is `1`, so it is actually an affine combination, see `line_map_slope_slope_sub_div_sub`. -/ theorem sub_div_sub_smul_slope_add_sub_div_sub_smul_slope {k : Type u_1} {E : Type u_2} {PE : Type u_3} [field k] [add_comm_group E] [semimodule k E] [add_torsor E PE] (f : k → PE) (a : k) (b : k) (c : k) : ((b - a) / (c - a)) • slope f a b + ((c - b) / (c - a)) • slope f b c = slope f a c := sorry /-- `slope f a c` is an affine combination of `slope f a b` and `slope f b c`. This version uses `line_map` to express this property. -/ theorem line_map_slope_slope_sub_div_sub {k : Type u_1} {E : Type u_2} {PE : Type u_3} [field k] [add_comm_group E] [semimodule k E] [add_torsor E PE] (f : k → PE) (a : k) (b : k) (c : k) (h : a ≠ c) : coe_fn (affine_map.line_map (slope f a b) (slope f b c)) ((c - b) / (c - a)) = slope f a c := sorry /-- `slope f a b` is an affine combination of `slope f a (line_map a b r)` and `slope f (line_map a b r) b`. We use `line_map` to express this property. -/ theorem line_map_slope_line_map_slope_line_map {k : Type u_1} {E : Type u_2} {PE : Type u_3} [field k] [add_comm_group E] [semimodule k E] [add_torsor E PE] (f : k → PE) (a : k) (b : k) (r : k) : coe_fn (affine_map.line_map (slope f (coe_fn (affine_map.line_map a b) r) b) (slope f a (coe_fn (affine_map.line_map a b) r))) r = slope f a b := sorry /-! ### Monotonicity of `line_map` In this section we prove that `line_map a b r` is monotone (strictly or not) in its arguments if other arguments belong to specific domains. -/ theorem line_map_mono_left {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {a' : E} {b : E} {r : k} (ha : a ≤ a') (hr : r ≤ 1) : coe_fn (affine_map.line_map a b) r ≤ coe_fn (affine_map.line_map a' b) r := sorry theorem line_map_strict_mono_left {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {a' : E} {b : E} {r : k} (ha : a < a') (hr : r < 1) : coe_fn (affine_map.line_map a b) r < coe_fn (affine_map.line_map a' b) r := sorry theorem line_map_mono_right {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {b' : E} {r : k} (hb : b ≤ b') (hr : 0 ≤ r) : coe_fn (affine_map.line_map a b) r ≤ coe_fn (affine_map.line_map a b') r := sorry theorem line_map_strict_mono_right {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {b' : E} {r : k} (hb : b < b') (hr : 0 < r) : coe_fn (affine_map.line_map a b) r < coe_fn (affine_map.line_map a b') r := sorry theorem line_map_mono_endpoints {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {a' : E} {b : E} {b' : E} {r : k} (ha : a ≤ a') (hb : b ≤ b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) : coe_fn (affine_map.line_map a b) r ≤ coe_fn (affine_map.line_map a' b') r := has_le.le.trans (line_map_mono_left ha h₁) (line_map_mono_right hb h₀) theorem line_map_strict_mono_endpoints {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {a' : E} {b : E} {b' : E} {r : k} (ha : a < a') (hb : b < b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) : coe_fn (affine_map.line_map a b) r < coe_fn (affine_map.line_map a' b') r := sorry theorem line_map_lt_line_map_iff_of_lt {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} {r' : k} (h : r < r') : coe_fn (affine_map.line_map a b) r < coe_fn (affine_map.line_map a b) r' ↔ a < b := sorry theorem left_lt_line_map_iff_lt {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : 0 < r) : a < coe_fn (affine_map.line_map a b) r ↔ a < b := sorry theorem line_map_lt_left_iff_lt {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : 0 < r) : coe_fn (affine_map.line_map a b) r < a ↔ b < a := left_lt_line_map_iff_lt h theorem line_map_lt_right_iff_lt {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : r < 1) : coe_fn (affine_map.line_map a b) r < b ↔ a < b := sorry theorem right_lt_line_map_iff_lt {k : Type u_1} {E : Type u_2} [ordered_ring k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : r < 1) : b < coe_fn (affine_map.line_map a b) r ↔ b < a := line_map_lt_right_iff_lt h theorem line_map_le_line_map_iff_of_lt {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} {r' : k} (h : r < r') : coe_fn (affine_map.line_map a b) r ≤ coe_fn (affine_map.line_map a b) r' ↔ a ≤ b := sorry theorem left_le_line_map_iff_le {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : 0 < r) : a ≤ coe_fn (affine_map.line_map a b) r ↔ a ≤ b := sorry @[simp] theorem left_le_midpoint {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} : a ≤ midpoint k a b ↔ a ≤ b := left_le_line_map_iff_le (iff.mpr inv_pos zero_lt_two) theorem line_map_le_left_iff_le {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : 0 < r) : coe_fn (affine_map.line_map a b) r ≤ a ↔ b ≤ a := left_le_line_map_iff_le h @[simp] theorem midpoint_le_left {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} : midpoint k a b ≤ a ↔ b ≤ a := line_map_le_left_iff_le (iff.mpr inv_pos zero_lt_two) theorem line_map_le_right_iff_le {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : r < 1) : coe_fn (affine_map.line_map a b) r ≤ b ↔ a ≤ b := sorry @[simp] theorem midpoint_le_right {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} : midpoint k a b ≤ b ↔ a ≤ b := line_map_le_right_iff_le (inv_lt_one one_lt_two) theorem right_le_line_map_iff_le {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} {r : k} (h : r < 1) : b ≤ coe_fn (affine_map.line_map a b) r ↔ b ≤ a := line_map_le_right_iff_le h @[simp] theorem right_le_midpoint {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {a : E} {b : E} : b ≤ midpoint k a b ↔ b ≤ a := right_le_line_map_iff_le (inv_lt_one one_lt_two) /-! ### Convexity and slope Given an interval `[a, b]` and a point `c ∈ (a, b)`, `c = line_map a b r`, there are a few ways to say that the point `(c, f c)` is above/below the segment `[(a, f a), (b, f b)]`: * compare `f c` to `line_map (f a) (f b) r`; * compare `slope f a c` to `slope `f a b`; * compare `slope f c b` to `slope f a b`; * compare `slope f a c` to `slope f c b`. In this section we prove equivalence of these four approaches. In order to make the statements more readable, we introduce local notation `c = line_map a b r`. Then we prove lemmas like ``` lemma map_le_line_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) : f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f a b := ``` For each inequality between `f c` and `line_map (f a) (f b) r` we provide 3 lemmas: * `*_left` relates it to an inequality on `slope f a c` and `slope f a b`; * `*_right` relates it to an inequality on `slope f a b` and `slope f c b`; * no-suffix version relates it to an inequality on `slope f a c` and `slope f c b`. Later these inequalities will be used in to restate `convex_on` in terms of monotonicity of the slope. -/ /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f a b`. -/ theorem map_le_line_map_iff_slope_le_slope_left {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < r * (b - a)) : f (coe_fn (affine_map.line_map a b) r) ≤ coe_fn (affine_map.line_map (f a) (f b)) r ↔ slope f a (coe_fn (affine_map.line_map a b) r) ≤ slope f a b := sorry /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f a c`. -/ theorem line_map_le_map_iff_slope_le_slope_left {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < r * (b - a)) : coe_fn (affine_map.line_map (f a) (f b)) r ≤ f (coe_fn (affine_map.line_map a b) r) ↔ slope f a b ≤ slope f a (coe_fn (affine_map.line_map a b) r) := map_le_line_map_iff_slope_le_slope_left h /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f a b`. -/ theorem map_lt_line_map_iff_slope_lt_slope_left {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < r * (b - a)) : f (coe_fn (affine_map.line_map a b) r) < coe_fn (affine_map.line_map (f a) (f b)) r ↔ slope f a (coe_fn (affine_map.line_map a b) r) < slope f a b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_left h) (map_le_line_map_iff_slope_le_slope_left h) /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f a c`. -/ theorem line_map_lt_map_iff_slope_lt_slope_left {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < r * (b - a)) : coe_fn (affine_map.line_map (f a) (f b)) r < f (coe_fn (affine_map.line_map a b) r) ↔ slope f a b < slope f a (coe_fn (affine_map.line_map a b) r) := map_lt_line_map_iff_slope_lt_slope_left h /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f c b`. -/ theorem map_le_line_map_iff_slope_le_slope_right {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < (1 - r) * (b - a)) : f (coe_fn (affine_map.line_map a b) r) ≤ coe_fn (affine_map.line_map (f a) (f b)) r ↔ slope f a b ≤ slope f (coe_fn (affine_map.line_map a b) r) b := sorry /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a b`. -/ theorem line_map_le_map_iff_slope_le_slope_right {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < (1 - r) * (b - a)) : coe_fn (affine_map.line_map (f a) (f b)) r ≤ f (coe_fn (affine_map.line_map a b) r) ↔ slope f (coe_fn (affine_map.line_map a b) r) b ≤ slope f a b := map_le_line_map_iff_slope_le_slope_right h /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f c b`. -/ theorem map_lt_line_map_iff_slope_lt_slope_right {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < (1 - r) * (b - a)) : f (coe_fn (affine_map.line_map a b) r) < coe_fn (affine_map.line_map (f a) (f b)) r ↔ slope f a b < slope f (coe_fn (affine_map.line_map a b) r) b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_right h) (map_le_line_map_iff_slope_le_slope_right h) /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a b`. -/ theorem line_map_lt_map_iff_slope_lt_slope_right {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (h : 0 < (1 - r) * (b - a)) : coe_fn (affine_map.line_map (f a) (f b)) r < f (coe_fn (affine_map.line_map a b) r) ↔ slope f (coe_fn (affine_map.line_map a b) r) b < slope f a b := map_lt_line_map_iff_slope_lt_slope_right h /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f c b`. -/ theorem map_le_line_map_iff_slope_le_slope {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : f (coe_fn (affine_map.line_map a b) r) ≤ coe_fn (affine_map.line_map (f a) (f b)) r ↔ slope f a (coe_fn (affine_map.line_map a b) r) ≤ slope f (coe_fn (affine_map.line_map a b) r) b := sorry /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a c`. -/ theorem line_map_le_map_iff_slope_le_slope {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : coe_fn (affine_map.line_map (f a) (f b)) r ≤ f (coe_fn (affine_map.line_map a b) r) ↔ slope f (coe_fn (affine_map.line_map a b) r) b ≤ slope f a (coe_fn (affine_map.line_map a b) r) := map_le_line_map_iff_slope_le_slope hab h₀ h₁ /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f c b`. -/ theorem map_lt_line_map_iff_slope_lt_slope {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : f (coe_fn (affine_map.line_map a b) r) < coe_fn (affine_map.line_map (f a) (f b)) r ↔ slope f a (coe_fn (affine_map.line_map a b) r) < slope f (coe_fn (affine_map.line_map a b) r) b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope hab h₀ h₁) (map_le_line_map_iff_slope_le_slope hab h₀ h₁) /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a c`. -/ theorem line_map_lt_map_iff_slope_lt_slope {k : Type u_1} {E : Type u_2} [linear_ordered_field k] [ordered_add_comm_group E] [semimodule k E] [ordered_semimodule k E] {f : k → E} {a : k} {b : k} {r : k} (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : coe_fn (affine_map.line_map (f a) (f b)) r < f (coe_fn (affine_map.line_map a b) r) ↔ slope f (coe_fn (affine_map.line_map a b) r) b < slope f a (coe_fn (affine_map.line_map a b) r) := map_lt_line_map_iff_slope_lt_slope hab h₀ h₁
5ffbfb61eae64514a4aec15524e970c083a07da3
bf532e3e865883a676110e756f800e0ddeb465be
/data/analysis/filter.lean
87354b400d8817ea56505dc9ead4e46b8da275c0
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,843
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Computational realization of filters (experimental). -/ import order.filter open set filter /-- A `cfilter α σ` is a realization of a filter (base) on `α`, represented by a type `σ` together with operations for the top element and the binary inf operation. -/ structure cfilter (α σ : Type*) [partial_order α] := (f : σ → α) (pt : σ) (inf : σ → σ → σ) (inf_le_left : ∀ a b : σ, f (inf a b) ≤ f a) (inf_le_right : ∀ a b : σ, f (inf a b) ≤ f b) variables {α : Type*} {β : Type*} {σ : Type*} {τ : Type*} namespace cfilter section variables [partial_order α] (F : cfilter α σ) instance : has_coe_to_fun (cfilter α σ) := ⟨_, cfilter.f⟩ @[simp] theorem coe_mk (f pt inf h₁ h₂ a) : (@cfilter.mk α σ _ f pt inf h₁ h₂) a = f a := rfl /-- Map a cfilter to an equivalent representation type. -/ def of_equiv (E : σ ≃ τ) : cfilter α σ → cfilter α τ | ⟨f, p, g, h₁, h₂⟩ := { f := λ a, f (E.symm a), pt := E p, inf := λ a b, E (g (E.symm a) (E.symm b)), inf_le_left := λ a b, by simpa using h₁ (E.symm a) (E.symm b), inf_le_right := λ a b, by simpa using h₂ (E.symm a) (E.symm b) } @[simp] theorem of_equiv_val (E : σ ≃ τ) (F : cfilter α σ) (a : τ) : F.of_equiv E a = F (E.symm a) := by cases F; refl end /-- The filter represented by a `cfilter` is the collection of supersets of elements of the filter base. -/ def to_filter (F : cfilter (set α) σ) : filter α := { sets := {a | ∃ b, F b ⊆ a}, exists_mem_sets := ⟨_, F.pt, subset.refl _⟩, upwards_sets := λ x y ⟨b, h⟩ s, ⟨b, subset.trans h s⟩, directed_sets := λ x ⟨a, h₁⟩ y ⟨b, h₂⟩, ⟨_, ⟨F.inf a b, subset.refl _⟩, subset.trans (F.inf_le_left _ _) h₁, subset.trans (F.inf_le_right _ _) h₂⟩ } @[simp] theorem mem_to_filter_sets (F : cfilter (set α) σ) {a : set α} : a ∈ F.to_filter.sets ↔ ∃ b, F b ⊆ a := iff.rfl end cfilter /-- A realizer for filter `f` is a cfilter which generates `f`. -/ structure filter.realizer (f : filter α) := (σ : Type*) (F : cfilter (set α) σ) (eq : F.to_filter = f) protected def cfilter.to_realizer (F : cfilter (set α) σ) : F.to_filter.realizer := ⟨σ, F, rfl⟩ namespace filter.realizer theorem mem_sets {f : filter α} (F : f.realizer) {a : set α} : a ∈ f.sets ↔ ∃ b, F.F b ⊆ a := by cases F; subst f; simp -- Used because it has better definitional equalities than the eq.rec proof def of_eq {f g : filter α} (e : f = g) (F : f.realizer) : g.realizer := ⟨F.σ, F.F, F.eq.trans e⟩ /-- A filter realizes itself. -/ def of_filter (f : filter α) : f.realizer := ⟨f.sets, { f := subtype.val, pt := ⟨univ, univ_mem_sets⟩, inf := λ ⟨x, h₁⟩ ⟨y, h₂⟩, ⟨_, inter_mem_sets h₁ h₂⟩, inf_le_left := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_left x y, inf_le_right := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_right x y }, filter_eq $ set.ext $ λ x, set_coe.exists.trans exists_sets_subset_iff⟩ /-- Transfer a filter realizer to another realizer on a different base type. -/ def of_equiv {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) : f.realizer := ⟨τ, F.F.of_equiv E, by refine eq.trans _ F.eq; exact filter_eq (set.ext $ λ x, ⟨λ ⟨s, h⟩, ⟨E.symm s, by simpa using h⟩, λ ⟨t, h⟩, ⟨E t, by simp [h]⟩⟩)⟩ @[simp] theorem of_equiv_σ {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) : (F.of_equiv E).σ = τ := rfl @[simp] theorem of_equiv_F {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) (s : τ) : (F.of_equiv E).F s = F.F (E.symm s) := by delta of_equiv; simp /-- `unit` is a realizer for the principal filter -/ protected def principal (s : set α) : (principal s).realizer := ⟨unit, { f := λ _, s, pt := (), inf := λ _ _, (), inf_le_left := λ _ _, le_refl _, inf_le_right := λ _ _, le_refl _ }, filter_eq $ set.ext $ λ x, ⟨λ ⟨_, s⟩, s, λ h, ⟨(), h⟩⟩⟩ @[simp] theorem principal_σ (s : set α) : (realizer.principal s).σ = unit := rfl @[simp] theorem principal_F (s : set α) (u : unit) : (realizer.principal s).F u = s := rfl /-- `unit` is a realizer for the top filter -/ protected def top : (⊤ : filter α).realizer := (realizer.principal _).of_eq principal_univ @[simp] theorem top_σ : (@realizer.top α).σ = unit := rfl @[simp] theorem top_F (u : unit) : (@realizer.top α).F u = univ := rfl /-- `unit` is a realizer for the bottom filter -/ protected def bot : (⊥ : filter α).realizer := (realizer.principal _).of_eq principal_empty @[simp] theorem bot_σ : (@realizer.bot α).σ = unit := rfl @[simp] theorem bot_F (u : unit) : (@realizer.bot α).F u = ∅ := rfl /-- Construct a realizer for `map m f` given a realizer for `f` -/ protected def map (m : α → β) {f : filter α} (F : f.realizer) : (map m f).realizer := ⟨F.σ, { f := λ s, image m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := λ a b, image_subset _ (F.F.inf_le_left _ _), inf_le_right := λ a b, image_subset _ (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by simp [cfilter.to_filter]; rw F.mem_sets; exact exists_congr (λ s, image_subset_iff)⟩ @[simp] theorem map_σ (m : α → β) {f : filter α} (F : f.realizer) : (F.map m).σ = F.σ := rfl @[simp] theorem map_F (m : α → β) {f : filter α} (F : f.realizer) (s) : (F.map m).F s = image m (F.F s) := rfl /-- Construct a realizer for `vmap m f` given a realizer for `f` -/ protected def vmap (m : α → β) {f : filter β} (F : f.realizer) : (vmap m f).realizer := ⟨F.σ, { f := λ s, preimage m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := λ a b, preimage_mono (F.F.inf_le_left _ _), inf_le_right := λ a b, preimage_mono (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; subst f; simp [cfilter.to_filter, mem_vmap_sets]; exact ⟨λ ⟨s, h⟩, ⟨_, ⟨s, subset.refl _⟩, h⟩, λ ⟨y, ⟨s, h⟩, h₂⟩, ⟨s, subset.trans (preimage_mono h) h₂⟩⟩⟩ /-- Construct a realizer for the sup of two filters -/ protected def sup {f g : filter α} (F : f.realizer) (G : g.realizer) : (f ⊔ g).realizer := ⟨F.σ × G.σ, { f := λ ⟨s, t⟩, F.F s ∪ G.F t, pt := (F.F.pt, G.F.pt), inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact ⟨λ ⟨s, t, h⟩, ⟨⟨s, subset.trans (subset_union_left _ _) h⟩, ⟨t, subset.trans (subset_union_right _ _) h⟩⟩, λ ⟨⟨s, h₁⟩, ⟨t, h₂⟩⟩, ⟨s, t, union_subset h₁ h₂⟩⟩⟩ /-- Construct a realizer for the inf of two filters -/ protected def inf {f g : filter α} (F : f.realizer) (G : g.realizer) : (f ⊓ g).realizer := ⟨F.σ × G.σ, { f := λ ⟨s, t⟩, F.F s ∩ G.F t, pt := (F.F.pt, G.F.pt), inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact ⟨λ ⟨s, t, h⟩, ⟨_, ⟨s, subset.refl _⟩, _, ⟨t, subset.refl _⟩, h⟩, λ ⟨y, ⟨s, h₁⟩, z, ⟨t, h₂⟩, h⟩, ⟨s, t, subset.trans (inter_subset_inter h₁ h₂) h⟩⟩⟩ /-- Construct a realizer for the cofinite filter -/ protected def cofinite [decidable_eq α] : (@cofinite α).realizer := ⟨finset α, { f := λ s, {a | a ∉ s}, pt := ∅, inf := (∪), inf_le_left := λ s t a, mt (finset.mem_union_left _), inf_le_right := λ s t a, mt (finset.mem_union_right _) }, filter_eq $ set.ext $ λ x, by simp [cfilter.to_filter]; exactI ⟨λ ⟨s, h⟩, finite_subset (finite_mem_finset s) (compl_subset_of_compl_subset h), λ ⟨fs⟩, ⟨(-x).to_finset, λ a (h : a ∉ (-x).to_finset), classical.by_contradiction $ λ h', h (mem_to_finset.2 h')⟩⟩⟩ /-- Construct a realizer for filter bind -/ protected def bind {f : filter α} {m : α → filter β} (F : f.realizer) (G : ∀ i, (m i).realizer) : (f.bind m).realizer := ⟨Σ s : F.σ, Π i ∈ F.F s, (G i).σ, { f := λ ⟨s, f⟩, ⋃ i ∈ F.F s, (G i).F (f i H), pt := ⟨F.F.pt, λ i H, (G i).F.pt⟩, inf := λ ⟨a, f⟩ ⟨b, f'⟩, ⟨F.F.inf a b, λ i h, (G i).F.inf (f i (F.F.inf_le_left _ _ h)) (f' i (F.F.inf_le_right _ _ h))⟩, inf_le_left := λ ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) → x ∈ ⋃ i (H : i ∈ F.F a), ((G i).F) (f i H), by simp; exact λ i h₁ h₂, ⟨i, F.F.inf_le_left _ _ h₁, (G i).F.inf_le_left _ _ h₂⟩, inf_le_right := λ ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) → x ∈ ⋃ i (H : i ∈ F.F b), ((G i).F) (f' i H), by simp; exact λ i h₁ h₂, ⟨i, F.F.inf_le_right _ _ h₁, (G i).F.inf_le_right _ _ h₂⟩ }, filter_eq $ set.ext $ λ x, by cases F with _ F _; subst f; simp [cfilter.to_filter, mem_bind_sets]; exact ⟨λ ⟨s, f, h⟩, ⟨F s, ⟨s, subset.refl _⟩, λ i H, (G i).mem_sets.2 ⟨f i H, λ a h', h ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, h'⟩⟩⟩, λ ⟨y, ⟨s, h⟩, f⟩, let ⟨f', h'⟩ := classical.axiom_of_choice (λ i:F s, (G i).mem_sets.1 (f i (h i.2))) in ⟨s, λ i h, f' ⟨i, h⟩, λ a ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, m⟩, h' ⟨_, H⟩ m⟩⟩⟩ /-- Construct a realizer for indexed supremum -/ protected def Sup {f : α → filter β} (F : ∀ i, (f i).realizer) : (⨆ i, f i).realizer := let F' : (⨆ i, f i).realizer := ((realizer.bind realizer.top F).of_eq $ filter_eq $ set.ext $ by simp [filter.bind, eq_univ_iff_forall, supr_sets_eq]) in F'.of_equiv $ show (Σ u:unit, Π (i : α), true → (F i).σ) ≃ Π i, (F i).σ, from ⟨λ⟨_,f⟩ i, f i ⟨⟩, λ f, ⟨(), λ i _, f i⟩, λ ⟨⟨⟩, f⟩, by dsimp; congr; simp, λ f, rfl⟩ /-- Construct a realizer for the product of filters -/ protected def prod {f g : filter α} (F : f.realizer) (G : g.realizer) : (f.prod g).realizer := (F.vmap _).inf (G.vmap _) theorem le_iff {f g : filter α} (F : f.realizer) (G : g.realizer) : f ≤ g ↔ ∀ b : G.σ, ∃ a : F.σ, F.F a ≤ G.F b := ⟨λ H t, F.mem_sets.1 (H (G.mem_sets.2 ⟨t, subset.refl _⟩)), λ H x h, F.mem_sets.2 $ let ⟨s, h₁⟩ := G.mem_sets.1 h, ⟨t, h₂⟩ := H s in ⟨t, subset.trans h₂ h₁⟩⟩ theorem tendsto_iff (f : α → β) {l₁ : filter α} {l₂ : filter β} (L₁ : l₁.realizer) (L₂ : l₂.realizer) : tendsto f l₁ l₂ ↔ ∀ b, ∃ a, ∀ x ∈ L₁.F a, f x ∈ L₂.F b := (le_iff (L₁.map f) L₂).trans $ forall_congr $ λ b, exists_congr $ λ a, image_subset_iff theorem ne_bot_iff {f : filter α} (F : f.realizer) : f ≠ ⊥ ↔ ∀ a : F.σ, F.F a ≠ ∅ := by haveI := classical.prop_decidable; rw [not_iff_comm, ← lattice.le_bot_iff, F.le_iff realizer.bot]; simp [not_forall]; exact ⟨λ ⟨x, e⟩ _, ⟨x, le_of_eq e⟩, λ h, let ⟨x, h⟩ := h () in ⟨x, lattice.le_bot_iff.1 h⟩⟩ end filter.realizer
9106233debc548a7a83badc1a1c3eea5d6580098
618003631150032a5676f229d13a079ac875ff77
/src/data/nat/fib.lean
aff5e7306020726ede341c336f1e80e94527f271
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,254
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.stream.basic import tactic.norm_num import tactic.monotonicity /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. ## Main Definitions - `fib` returns the stream of Fibonacci numbers. ## Main Statements - `fib_succ_succ` shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`. ## Implementation Notes For efficiency purposes, the sequence is defined using `stream.iterate`. ## Tags fib, fibonacci -/ namespace nat /-- Auxiliary function used in the definition of `fib_aux_stream`. -/ private def fib_aux_step : (ℕ × ℕ) → (ℕ × ℕ) := λ p, ⟨p.snd, p.fst + p.snd⟩ /-- Auxiliary stream creating Fibonacci pairs `⟨Fₙ, Fₙ₊₁⟩`. -/ private def fib_aux_stream : stream (ℕ × ℕ) := stream.iterate fib_aux_step ⟨0, 1⟩ /-- Implementation of the fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ def fib (n : ℕ) : ℕ := (fib_aux_stream n).fst @[simp] lemma fib_zero : fib 0 = 0 := rfl @[simp] lemma fib_one : fib 1 = 1 := rfl private lemma fib_aux_stream_succ {n : ℕ} : fib_aux_stream (n + 1) = fib_aux_step (fib_aux_stream n) := begin change (stream.nth (n + 1) $ stream.iterate fib_aux_step ⟨0, 1⟩) = fib_aux_step (stream.nth n $ stream.iterate fib_aux_step ⟨0, 1⟩), rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map] end /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/ lemma fib_succ_succ {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by simp only [fib, fib_aux_stream_succ, fib_aux_step] lemma fib_pos {n : ℕ} (n_pos : 0 < n) : 0 < fib n := begin induction n with n IH, case nat.zero { norm_num at n_pos }, case nat.succ { cases n, case nat.zero { simp [fib_succ_succ, zero_lt_one] }, case nat.succ { have : 0 ≤ fib n, by simp, exact (lt_add_of_nonneg_of_lt this $ IH n.succ_pos) }} end lemma fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by { cases n; simp [fib_succ_succ] } lemma fib_mono {n m : ℕ} (n_le_m : n ≤ m) : fib n ≤ fib m := by { induction n_le_m with m n_le_m IH, { refl }, { exact (le_trans IH fib_le_fib_succ) }} lemma le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := begin induction five_le_n with n five_le_n IH, { have : 5 = fib 5, by refl, -- 5 ≤ fib 5 exact le_of_eq this }, { -- n + 1 ≤ fib (n + 1) for 5 ≤ n cases n with n', -- rewrite n = succ n' to use fib.succ_succ { have : 5 = 0, from nat.le_zero_iff.elim_left five_le_n, contradiction }, rw fib_succ_succ, suffices : 1 + (n' + 1) ≤ fib n' + fib (n' + 1), by rwa [nat.succ_eq_add_one, add_comm], have : n' ≠ 0, by { intro h, have : 5 ≤ 1, by rwa h at five_le_n, norm_num at this }, have : 1 ≤ fib n', from nat.succ_le_of_lt (fib_pos $ zero_lt_iff_ne_zero.mpr this), mono } end end nat
9651b4945597511fcd8cbdd8891df21d7f24e8c9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/euclidean_domain.lean
9be725299613f02026d0258cc5c20bab187fbe58
[ "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,169
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 -/ import algebra.gcd_monoid.basic import algebra.euclidean_domain.basic import ring_theory.ideal.basic import ring_theory.principal_ideal_domain /-! # Lemmas about Euclidean domains Various about Euclidean domains are proved; all of them seem to be true more generally for principal ideal domains, so these lemmas should probably be reproved in more generality and this file perhaps removed? ## Tags euclidean domain -/ noncomputable theory open_locale classical open euclidean_domain set ideal section gcd_monoid variables {R : Type*} [euclidean_domain R] [gcd_monoid R] lemma gcd_ne_zero_of_left (p q : R) (hp : p ≠ 0) : gcd_monoid.gcd p q ≠ 0 := λ h, hp $ eq_zero_of_zero_dvd (h ▸ gcd_dvd_left p q) lemma gcd_ne_zero_of_right (p q : R) (hp : q ≠ 0) : gcd_monoid.gcd p q ≠ 0 := λ h, hp $ eq_zero_of_zero_dvd (h ▸ gcd_dvd_right p q) lemma left_div_gcd_ne_zero {p q : R} (hp : p ≠ 0) : p / gcd_monoid.gcd p q ≠ 0 := begin obtain ⟨r, hr⟩ := gcd_monoid.gcd_dvd_left p q, obtain ⟨pq0, r0⟩ : gcd_monoid.gcd p q ≠ 0 ∧ r ≠ 0 := mul_ne_zero_iff.mp (hr ▸ hp), rw [hr, mul_comm, mul_div_cancel _ pq0] { occs := occurrences.pos [1] }, exact r0, end lemma right_div_gcd_ne_zero {p q : R} (hq : q ≠ 0) : q / gcd_monoid.gcd p q ≠ 0 := begin obtain ⟨r, hr⟩ := gcd_monoid.gcd_dvd_right p q, obtain ⟨pq0, r0⟩ : gcd_monoid.gcd p q ≠ 0 ∧ r ≠ 0 := mul_ne_zero_iff.mp (hr ▸ hq), rw [hr, mul_comm, mul_div_cancel _ pq0] { occs := occurrences.pos [1] }, exact r0, end end gcd_monoid namespace euclidean_domain /-- Create a `gcd_monoid` whose `gcd_monoid.gcd` matches `euclidean_domain.gcd`. -/ def gcd_monoid (R) [euclidean_domain R] : gcd_monoid R := { gcd := gcd, lcm := lcm, gcd_dvd_left := gcd_dvd_left, gcd_dvd_right := gcd_dvd_right, dvd_gcd := λ a b c, dvd_gcd, gcd_mul_lcm := λ a b, by rw euclidean_domain.gcd_mul_lcm, lcm_zero_left := lcm_zero_left, lcm_zero_right := lcm_zero_right } variables {α : Type*} [euclidean_domain α] [decidable_eq α] theorem span_gcd {α} [euclidean_domain α] (x y : α) : span ({gcd x y} : set α) = span ({x, y} : set α) := begin letI := euclidean_domain.gcd_monoid α, exact span_gcd x y, end theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} : is_unit (gcd x y) ↔ is_coprime x y := begin letI := euclidean_domain.gcd_monoid α, exact gcd_is_unit_iff x y, end -- this should be proved for UFDs surely? theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α} (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin letI := euclidean_domain.gcd_monoid α, exact is_coprime_of_dvd x y nonzero H, end -- this should be proved for UFDs surely? theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin letI := euclidean_domain.gcd_monoid α, exact dvd_or_coprime x y h, end end euclidean_domain
231db01d6e7e3cd5d68a105fd08261f199c6f336
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/computability/primrec.lean
5374fa3ae0d5b9b956f20d3542da4deefc76f5db
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,900
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.equiv.list import logic.function.iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open denumerable encodable function namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ'] end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim [] : nat.primrec (λ n, encodable.encode (decode n))) namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := by letI : primcodable β := primcodable.of_equiv α e; exact encode_iff.1 primrec.encode theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, function.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ default α) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem option_get_or_else : primrec₂ (@option.get_or_else α) := primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $ λ ⟨o, a⟩, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [swap], cases e : p.1 - p.2 with n, { simp [tsub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite (nat_le.comp primrec.snd primrec.fst) fst snd theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode₂ : primrec (decode₂ α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := fintype.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, { simp }, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_right_le n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := option_iget.comp₂ list_nth theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_succ]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, simp [*, list.find_index]] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_succ] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) (equiv.fin_equiv_subtype _) instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) section ulower local attribute [instance, priority 100] encodable.decidable_range_encode encodable.decidable_eq_of_encodable instance ulower : primcodable (ulower α) := have primrec_pred (λ n, encodable.decode₂ α n ≠ none), from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode (primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst) (primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)), primcodable.subtype $ primrec_pred.of_eq this (λ n, decode₂_ne_none_iff) end ulower end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) : by haveI := primcodable.subtype hp; exact primrec (λ a, @subtype.mk β p (f a) (h a)) := subtype_val_iff.1 hf theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} : primrec f → primrec (λ a, option.get (h a)) := begin intro hf, refine (nat.primrec.pred.comp hf).of_eq (λ n, _), generalize hx : decode α n = x, cases x; simp end theorem ulower_down : primrec (ulower.down : α → ulower α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact subtype_mk primrec.encode theorem ulower_up : primrec (ulower.up : ulower α → α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact option_get (primrec.decode₂.comp subtype_val) theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (coe : fin n → ℕ) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, (f v ::ᵥ g v)) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y ::ᵥ IH ::ᵥ v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (tsub_eq_zero_iff_le.mp e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {simp}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
656e1766ba6842e10aeb0b1ba7260102cae22e61
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/primorial.lean
5eea76e716d1ebecfd8c18537f8fb06781abb0fe
[ "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,261
lean
/- Copyright (c) 2020 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens, Yury Kudryashov -/ import algebra.big_operators.associated import data.nat.choose.sum import data.nat.choose.dvd import data.nat.parity import data.nat.prime /-! # Primorial > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the primorial function (the product of primes less than or equal to some bound), and proves that `primorial n ≤ 4 ^ n`. ## Notations We use the local notation `n#` for the primorial of `n`: that is, the product of the primes less than or equal to `n`. -/ open finset open nat open_locale big_operators nat /-- The primorial `n#` of `n` is the product of the primes less than or equal to `n`. -/ def primorial (n : ℕ) : ℕ := ∏ p in (filter nat.prime (range (n + 1))), p local notation x`#` := primorial x lemma primorial_pos (n : ℕ) : 0 < n# := prod_pos $ λ p hp, (mem_filter.1 hp).2.pos lemma primorial_succ {n : ℕ} (hn1 : n ≠ 1) (hn : odd n) : (n + 1)# = n# := begin refine prod_congr _ (λ _ _, rfl), rw [range_succ, filter_insert, if_neg (λ h, odd_iff_not_even.mp hn _)], exact (h.even_sub_one $ mt succ.inj hn1) end lemma primorial_add (m n : ℕ) : (m + n)# = m# * ∏ p in filter nat.prime (Ico (m + 1) (m + n + 1)), p := begin rw [primorial, primorial, ← Ico_zero_eq_range, ← prod_union, ← filter_union, Ico_union_Ico_eq_Ico], exacts [zero_le _, add_le_add_right (nat.le_add_right _ _) _, disjoint_filter_filter $ Ico_disjoint_Ico_consecutive _ _ _] end lemma primorial_add_dvd {m n : ℕ} (h : n ≤ m) : (m + n)# ∣ m# * choose (m + n) m := calc (m + n)# = m# * ∏ p in filter nat.prime (Ico (m + 1) (m + n + 1)), p : primorial_add _ _ ... ∣ m# * choose (m + n) m : mul_dvd_mul_left _ $ prod_primes_dvd _ (λ k hk, (mem_filter.1 hk).2.prime) $ λ p hp, begin rw [mem_filter, mem_Ico] at hp, exact hp.2.dvd_choose_add hp.1.1 (h.trans_lt (m.lt_succ_self.trans_le hp.1.1)) (nat.lt_succ_iff.1 hp.1.2) end lemma primorial_add_le {m n : ℕ} (h : n ≤ m) : (m + n)# ≤ m# * choose (m + n) m := le_of_dvd (mul_pos (primorial_pos _) (choose_pos $ nat.le_add_right _ _)) (primorial_add_dvd h) lemma primorial_le_4_pow (n : ℕ) : n# ≤ 4 ^ n := begin induction n using nat.strong_induction_on with n ihn, cases n, { refl }, rcases n.even_or_odd with (⟨m, rfl⟩ | ho), { rcases m.eq_zero_or_pos with rfl | hm, { dec_trivial }, calc (m + m + 1)# = (m + 1 + m)# : by rw [add_right_comm] ... ≤ (m + 1)# * choose (m + 1 + m) (m + 1) : primorial_add_le m.le_succ ... = (m + 1)# * choose (2 * m + 1) m : by rw [choose_symm_add, two_mul, add_right_comm] ... ≤ 4 ^ (m + 1) * 4 ^ m : mul_le_mul' (ihn _ $ succ_lt_succ $ (lt_add_iff_pos_left _).2 hm) (choose_middle_le_pow _) ... ≤ 4 ^ (m + m + 1) : by rw [← pow_add, add_right_comm] }, { rcases decidable.eq_or_ne n 1 with rfl | hn, { dec_trivial }, { calc (n + 1)# = n# : primorial_succ hn ho ... ≤ 4 ^ n : ihn n n.lt_succ_self ... ≤ 4 ^ (n + 1) : pow_le_pow_of_le_right four_pos n.le_succ } } end
21d54055dc6babed0b532d15f9fd85134e7b884f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/prod.lean
b12f134275ae5669607c54cd0158c5f2a985b0af
[ "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
24,060
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, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.basic import order.partial_sups /-! ### Products of modules This file defines constructors for linear maps whose domains or codomains are products. It contains theorems relating these to each other, as well as to `submodule.prod`, `submodule.map`, `submodule.comap`, `linear_map.range`, and `linear_map.ker`. ## Main definitions - products in the domain: - `linear_map.fst` - `linear_map.snd` - `linear_map.coprod` - `linear_map.prod_ext` - products in the codomain: - `linear_map.inl` - `linear_map.inr` - `linear_map.prod` - products in both domain and codomain: - `linear_map.prod_map` - `linear_equiv.prod_map` - `linear_equiv.skew_prod` -/ universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} section prod namespace linear_map variables (S : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f : M →ₗ[R] M₂) section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := { to_fun := prod.fst, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := { to_fun := prod.snd, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ @[simps] def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (M →ₗ[R] M₂ × M₃) := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def prod_equiv [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] : ((M →ₗ[R] M₂) × (M →ₗ[R] M₃)) ≃ₗ[S] (M →ₗ[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, map_add' := λ a b, rfl, map_smul' := λ r a, rfl } section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := prod linear_map.id 0 /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := prod 0 linear_map.id end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f.1 x.1 + f.2 x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := f.comp (fst _ _ _) + g.comp (snd _ _ _) @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M × M₂) : coprod f g x = f x.1 + g x.2 := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem comp_coprod (f : M₃ →ₗ[R] M₄) (g₁ : M →ₗ[R] M₃) (g₂ : M₂ →ₗ[R] M₃) : f.comp (g₁.coprod g₂) = (f.comp g₁).coprod (f.comp g₂) := ext $ λ x, f.map_add (g₁ x.1) (g₂ x.2) theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext; simp @[simp] theorem coprod_comp_prod (f : M₂ →ₗ[R] M₄) (g : M₃ →ₗ[R] M₄) (f' : M →ₗ[R] M₂) (g' : M →ₗ[R] M₃) : (f.coprod g).comp (f'.prod g') = f.comp f' + g.comp g' := rfl /-- Taking the product of two maps with the same codomain is equivalent to taking the product of their domains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def coprod_equiv [module S M₃] [smul_comm_class R S M₃] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₃)) ≃ₗ[S] (M × M₂ →ₗ[R] M₃) := { to_fun := λ f, f.1.coprod f.2, inv_fun := λ f, (f.comp (inl _ _ _), f.comp (inr _ _ _)), left_inv := λ f, by simp only [prod.mk.eta, coprod_inl, coprod_inr], right_inv := λ f, by simp only [←comp_coprod, comp_id, coprod_inl_inr], map_add' := λ a b, by { ext, simp only [prod.snd_add, add_apply, coprod_apply, prod.fst_add], ac_refl }, map_smul' := λ r a, by { ext, simp only [smul_add, smul_apply, prod.smul_snd, prod.smul_fst, coprod_apply] } } theorem prod_ext_iff {f g : M × M₂ →ₗ[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := (coprod_equiv ℕ).symm.injective.eq_iff.symm.trans prod.ext_iff /-- Split equality of linear maps from a product into linear maps over each component, to allow `ext` to apply lemmas specific to `M →ₗ M₃` and `M₂ →ₗ M₃`. See note [partially-applied ext lemmas]. -/ @[ext] theorem prod_ext {f g : M × M₂ →ₗ[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl lemma prod_map_comap_prod (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) (S : submodule R M₂) (S' : submodule R M₄) : (submodule.prod S S').comap (linear_map.prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ lemma ker_prod_map (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) : (linear_map.prod_map f g).ker = submodule.prod f.ker g.ker := begin dsimp only [ker], rw [←prod_map_comap_prod, submodule.prod_bot], end section map_mul variables {A : Type*} [non_unital_non_assoc_semiring A] [module R A] variables {B : Type*} [non_unital_non_assoc_semiring B] [module R B] lemma inl_map_mul (a₁ a₂ : A) : linear_map.inl R A B (a₁ * a₂) = linear_map.inl R A B a₁ * linear_map.inl R A B a₂ := prod.ext rfl (by simp) lemma inr_map_mul (b₁ b₂ : B) : linear_map.inr R A B (b₁ * b₂) = linear_map.inr R A B b₁ * linear_map.inr R A B b₂ := prod.ext (by simp) rfl end map_mul end linear_map end prod namespace linear_map open submodule variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rintros ⟨_, _⟩ ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl_range_inl_inr.sup_eq_top lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw set_like.le_def, rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image] @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end lemma ker_prod_ker_le_ker_coprod {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := by { rintros ⟨y, z⟩, simp {contextual := tt} } lemma ker_coprod_of_disjoint_range {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := begin apply le_antisymm _ (ker_prod_ker_le_ker_coprod f g), rintros ⟨y, z⟩ h, simp only [mem_ker, mem_prod, coprod_apply] at h ⊢, have : f y ∈ f.range ⊓ g.range, { simp only [true_and, mem_range, mem_inf, exists_apply_eq_apply], use -z, rwa [eq_comm, map_neg, ← sub_eq_zero, sub_neg_eq_add] }, rw [hd.eq_bot, mem_bot] at this, rw [this] at h, simpa [this] using h, end end linear_map namespace submodule open linear_map variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] lemma sup_eq_range (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, set_like.exists] variables (p : submodule R M) (q : submodule R M₂) @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_snd] variables (R M M₂) /-- `M` as a submodule of `M × N`. -/ def fst : submodule R (M × M₂) := (⊥ : submodule R M₂).comap (linear_map.snd R M M₂) /-- `M` as a submodule of `M × N` is isomorphic to `M`. -/ @[simps] def fst_equiv : submodule.fst R M M₂ ≃ₗ[R] M := { to_fun := λ x, x.1.1, inv_fun := λ m, ⟨⟨m, 0⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma fst_map_fst : (submodule.fst R M M₂).map (linear_map.fst R M M₂) = ⊤ := by tidy lemma fst_map_snd : (submodule.fst R M M₂).map (linear_map.snd R M M₂) = ⊥ := by { tidy, exact 0, } /-- `N` as a submodule of `M × N`. -/ def snd : submodule R (M × M₂) := (⊥ : submodule R M).comap (linear_map.fst R M M₂) /-- `N` as a submodule of `M × N` is isomorphic to `N`. -/ @[simps] def snd_equiv : submodule.snd R M M₂ ≃ₗ[R] M₂ := { to_fun := λ x, x.1.2, inv_fun := λ n, ⟨⟨0, n⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma snd_map_fst : (submodule.snd R M M₂).map (linear_map.fst R M M₂) = ⊥ := by { tidy, exact 0, } lemma snd_map_snd : (submodule.snd R M M₂).map (linear_map.snd R M M₂) = ⊤ := by tidy lemma fst_sup_snd : submodule.fst R M M₂ ⊔ submodule.snd R M M₂ = ⊤ := begin rw eq_top_iff, rintro ⟨m, n⟩ -, rw [show (m, n) = (m, 0) + (0, n), by simp], apply submodule.add_mem (submodule.fst R M M₂ ⊔ submodule.snd R M M₂), { exact submodule.mem_sup_left (submodule.mem_comap.mpr (by simp)), }, { exact submodule.mem_sup_right (submodule.mem_comap.mpr (by simp)), }, end lemma fst_inf_snd : submodule.fst R M M₂ ⊓ submodule.snd R M M₂ = ⊥ := by tidy end submodule namespace linear_equiv section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smul c _) (e₂.map_smul c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end end linear_equiv namespace linear_map open submodule variables [ring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end linear_map namespace linear_map /-! ## Tunnels and tailings Some preliminary work for establishing the strong rank condition for noetherian rings. Given a morphism `f : M × N →ₗ[R] M` which is `i : injective f`, we can find an infinite decreasing `tunnel f i n` of copies of `M` inside `M`, and sitting beside these, an infinite sequence of copies of `N`. We picturesquely name these as `tailing f i n` for each individual copy of `N`, and `tailings f i n` for the supremum of the first `n+1` copies: they are the pieces left behind, sitting inside the tunnel. By construction, each `tailing f i (n+1)` is disjoint from `tailings f i n`; later, when we assume `M` is noetherian, this implies that `N` must be trivial, and establishes the strong rank condition for any left-noetherian ring. -/ section tunnel -- (This doesn't work over a semiring: we need to use that `submodule R M` is a modular lattice, -- which requires cancellation.) variables [ring R] variables {N : Type*} [add_comm_group M] [module R M] [add_comm_group N] [module R N] open function /-- An auxiliary construction for `tunnel`. The composition of `f`, followed by the isomorphism back to `K`, followed by the inclusion of this submodule back into `M`. -/ def tunnel_aux (f : M × N →ₗ[R] M) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : M × N →ₗ[R] M := (Kφ.1.subtype.comp Kφ.2.symm.to_linear_map).comp f lemma tunnel_aux_injective (f : M × N →ₗ[R] M) (i : injective f) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : injective (tunnel_aux f Kφ) := (subtype.val_injective.comp Kφ.2.symm.injective).comp i noncomputable theory /-- Auxiliary definition for `tunnel`. -/ -- Even though we have `noncomputable theory`, -- we get an error without another `noncomputable` here. noncomputable def tunnel' (f : M × N →ₗ[R] M) (i : injective f) : ℕ → Σ (K : submodule R M), K ≃ₗ[R] M | 0 := ⟨⊤, linear_equiv.of_top ⊤ rfl⟩ | (n+1) := ⟨(submodule.fst R M N).map (tunnel_aux f (tunnel' n)), ((submodule.fst R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' n))).symm.trans (submodule.fst_equiv R M N)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a nested sequence of submodules all isomorphic to `M`. -/ def tunnel (f : M × N →ₗ[R] M) (i : injective f) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (tunnel' f i n).1, monotone_of_monotone_nat (λ n, begin dsimp [tunnel', tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a sequence of submodules all isomorphic to `N`. -/ def tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : submodule R M := (submodule.snd R M N).map (tunnel_aux f (tunnel' f i n)) /-- Each `tailing f i n` is a copy of `N`. -/ def tailing_linear_equiv (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≃ₗ[R] N := ((submodule.snd R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' f i n))).symm.trans (submodule.snd_equiv R M N) lemma tailing_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≤ tunnel f i n := begin dsimp [tailing, tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end lemma tailing_disjoint_tunnel_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailing f i n) (tunnel f i (n+1)) := begin rw disjoint_iff, dsimp [tailing, tunnel, tunnel'], rw [submodule.map_inf_eq_map_inf_comap, submodule.comap_map_eq_of_injective (tunnel_aux_injective _ i _), inf_comm, submodule.fst_inf_snd, submodule.map_bot], end lemma tailing_sup_tunnel_succ_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ⊔ tunnel f i (n+1) ≤ tunnel f i n := begin dsimp [tailing, tunnel, tunnel', tunnel_aux], rw [←submodule.map_sup, sup_comm, submodule.fst_sup_snd, submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end /-- The supremum of all the copies of `N` found inside the tunnel. -/ def tailings (f : M × N →ₗ[R] M) (i : injective f) : ℕ → submodule R M := partial_sups (tailing f i) @[simp] lemma tailings_zero (f : M × N →ₗ[R] M) (i : injective f) : tailings f i 0 = tailing f i 0 := by simp [tailings] @[simp] lemma tailings_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailings f i (n+1) = tailings f i n ⊔ tailing f i (n+1) := by simp [tailings] lemma tailings_disjoint_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tunnel f i (n+1)) := begin induction n with n ih, { simp only [tailings_zero], apply tailing_disjoint_tunnel_succ, }, { simp only [tailings_succ], refine disjoint.disjoint_sup_left_of_disjoint_sup_right _ _, apply tailing_disjoint_tunnel_succ, apply disjoint.mono_right _ ih, apply tailing_sup_tunnel_succ_le_tunnel, }, end lemma tailings_disjoint_tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tailing f i (n+1)) := disjoint.mono_right (tailing_le_tunnel f i _) (tailings_disjoint_tunnel f i _) end tunnel end linear_map
649decfecbbdbfbdea32533c63d5aafbd3787d4a
041929c569a4eeeafb4efdddab8a644f6df383c5
/src/mazes/gcd_maze/level813.lean
10cd094ff45c5c3ffcc2fe9d7aa3c0e456b708c3
[]
no_license
kbuzzard/xena-maze-game
30ffbe956762dd6603e74efd823d375649e037c3
098454dd6acc4c06beccf52b6547bf4cd99cc581
refs/heads/master
1,670,840,300,174
1,598,554,198,000
1,598,554,198,000
290,856,036
4
0
null
null
null
null
UTF-8
Lean
false
false
660
lean
-- import the definition of the gcd maze import mazes.gcd_maze.definition import data.int.gcd open maze direction /- # Bezout's Theorem Example maze. You are in a maze of integers, all distinct. You can go north, south east or west. North adds 8 to your integer, South subtracts 8. East adds 13 to your integer, West subtracts 13 The exit is at 1, the gcd of 8 and 5. When you're at the exit, type `out`. Solver remark : there are infinitely many rooms. -/ /- Lemma : no-side-bar Can you prove this case of Bezout's Theorem? -/ example : can_escape 8 13 0 := begin iterate 5 {n}, iterate 3 {w}, out end -- #eval nat.xgcd 8 13 -- (2, -3) -- hide
1bb9594125d4e00f829c3475e6ad1cfa2b29877f
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/measure/lebesgue.lean
c347ccce0c02b716c0f1989faaa0241f9abc1870
[ "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
31,905
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, Sébastien Gouëzel, Yury Kudryashov -/ import dynamics.ergodic.measure_preserving import linear_algebra.determinant import linear_algebra.matrix.diagonal import linear_algebra.matrix.transvection import measure_theory.constructions.pi import measure_theory.measure.stieltjes import measure_theory.measure.haar_of_basis /-! # Lebesgue measure on the real line and on `ℝⁿ` We show that the Lebesgue measure on the real line (constructed as a particular case of additive Haar measure on inner product spaces) coincides with the Stieltjes measure associated to the function `x ↦ x`. We deduce properties of this measure on `ℝ`, and then of the product Lebesgue measure on `ℝⁿ`. In particular, we prove that they are translation invariant. We show that, on `ℝⁿ`, a linear map acts on Lebesgue measure by rescaling it through the absolute value of its determinant, in `real.map_linear_map_volume_pi_eq_smul_volume_pi`. More properties of the Lebesgue measure are deduced from this in `haar_lebesgue.lean`, where they are proved more generally for any additive Haar measure on a finite-dimensional real vector space. -/ noncomputable theory open classical set filter measure_theory measure_theory.measure topological_space open ennreal (of_real) open_locale big_operators ennreal nnreal topology /-! ### Definition of the Lebesgue measure and lengths of intervals -/ namespace real variables {ι : Type*} [fintype ι] /-- The volume on the real line (as a particular case of the volume on a finite-dimensional inner product space) coincides with the Stieltjes measure coming from the identity function. -/ lemma volume_eq_stieltjes_id : (volume : measure ℝ) = stieltjes_function.id.measure := begin haveI : is_add_left_invariant stieltjes_function.id.measure := ⟨λ a, eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp only [measure.map_apply (measurable_const_add a) measurable_set_Ioo, sub_sub_sub_cancel_right, stieltjes_function.measure_Ioo, stieltjes_function.id_left_lim, stieltjes_function.id_apply, id.def, preimage_const_add_Ioo]⟩, have A : stieltjes_function.id.measure (std_orthonormal_basis ℝ ℝ).to_basis.parallelepiped = 1, { change stieltjes_function.id.measure (parallelepiped (std_orthonormal_basis ℝ ℝ)) = 1, rcases parallelepiped_orthonormal_basis_one_dim (std_orthonormal_basis ℝ ℝ) with H|H; simp only [H, stieltjes_function.measure_Icc, stieltjes_function.id_apply, id.def, tsub_zero, stieltjes_function.id_left_lim, sub_neg_eq_add, zero_add, ennreal.of_real_one] }, conv_rhs { rw [add_haar_measure_unique stieltjes_function.id.measure (std_orthonormal_basis ℝ ℝ).to_basis.parallelepiped, A] }, simp only [volume, basis.add_haar, one_smul], end theorem volume_val (s) : volume s = stieltjes_function.id.measure s := by simp [volume_eq_stieltjes_id] @[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp [volume_val] @[simp] lemma volume_univ : volume (univ : set ℝ) = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, calc (r : ℝ≥0∞) = volume (Icc (0 : ℝ) r) : by simp ... ≤ volume univ : measure_mono (subset_univ _) @[simp] lemma volume_ball (a r : ℝ) : volume (metric.ball a r) = of_real (2 * r) := by rw [ball_eq_Ioo, volume_Ioo, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_closed_ball (a r : ℝ) : volume (metric.closed_ball a r) = of_real (2 * r) := by rw [closed_ball_eq_Icc, volume_Icc, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_emetric_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [metric.emetric_ball_top, volume_univ, two_mul, _root_.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_ball_nnreal, volume_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end @[simp] lemma volume_emetric_closed_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.closed_ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [emetric.closed_ball_top, volume_univ, two_mul, _root_.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_closed_ball_nnreal, volume_closed_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) := ⟨λ x, volume_singleton⟩ @[simp] lemma volume_interval {a b : ℝ} : volume (uIcc a b) = of_real (|b - a|) := by rw [←Icc_min_max, volume_Icc, max_sub_min_eq_abs] @[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo a (a + n)) : by simp ... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self @[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ := by simp [← measure_congr Ioi_ae_eq_Ici] @[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo (a - n) a) : by simp ... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self @[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ := by simp [← measure_congr Iio_ae_eq_Iic] instance locally_finite_volume : is_locally_finite_measure (volume : measure ℝ) := ⟨λ x, ⟨Ioo (x - 1) (x + 1), is_open.mem_nhds is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩, by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩ instance is_finite_measure_restrict_Icc (x y : ℝ) : is_finite_measure (volume.restrict (Icc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ico (x y : ℝ) : is_finite_measure (volume.restrict (Ico x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioc (x y : ℝ) : is_finite_measure (volume.restrict (Ioc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioo (x y : ℝ) : is_finite_measure (volume.restrict (Ioo x y)) := ⟨by simp⟩ lemma volume_le_diam (s : set ℝ) : volume s ≤ emetric.diam s := begin by_cases hs : metric.bounded s, { rw [real.ediam_eq hs, ← volume_Icc], exact volume.mono (real.subset_Icc_Inf_Sup_of_bounded hs) }, { rw metric.ediam_of_unbounded hs, exact le_top } end lemma _root_.filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) : (0 : ℝ≥0∞) < volume {x | p x} := begin rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩, refine lt_of_lt_of_le _ (measure_mono hs), simpa [-mem_Ioo] using hx.1.trans hx.2 end /-! ### Volume of a box in `ℝⁿ` -/ lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) := begin rw [← pi_univ_Icc, volume_pi_pi], simp only [real.volume_Icc] end @[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (Icc a b)).to_real = ∏ i, (b i - a i) := by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioo {a b : ι → ℝ} : volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioc {a b : ι → ℝ} : volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ico {a b : ι → ℝ} : volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] @[simp] lemma volume_pi_ball (a : ι → ℝ) {r : ℝ} (hr : 0 < r) : volume (metric.ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_ball a hr, volume_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr.le) _).symm end @[simp] lemma volume_pi_closed_ball (a : ι → ℝ) {r : ℝ} (hr : 0 ≤ r) : volume (metric.closed_ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_closed_ball a hr, volume_closed_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr) _).symm end lemma volume_pi_le_prod_diam (s : set (ι → ℝ)) : volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) := calc volume s ≤ volume (pi univ (λ i, closure (function.eval i '' s))) : volume.mono $ subset.trans (subset_pi_eval_image univ s) $ pi_mono $ λ i hi, subset_closure ... = ∏ i, volume (closure $ function.eval i '' s) : volume_pi_pi _ ... ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : finset.prod_le_prod' $ λ i hi, (volume_le_diam _).trans_eq (emetric.diam_closure _) lemma volume_pi_le_diam_pow (s : set (ι → ℝ)) : volume s ≤ emetric.diam s ^ fintype.card ι := calc volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : volume_pi_le_prod_diam s ... ≤ ∏ i : ι, (1 : ℝ≥0) * emetric.diam s : finset.prod_le_prod' $ λ i hi, (lipschitz_with.eval i).ediam_image_le s ... = emetric.diam s ^ fintype.card ι : by simp only [ennreal.coe_one, one_mul, finset.prod_const, fintype.card] /-! ### Images of the Lebesgue measure under multiplication in ℝ -/ lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map ((*) a) volume = volume := begin refine (real.measure_ext_Ioo_rat $ λ p q, _).symm, cases lt_or_gt_of_ne h with h h, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, neg_sub_neg, neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub, smul_eq_mul, mul_div_cancel' _ (ne_of_lt h)] }, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, preimage_const_mul_Ioo _ _ h, abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h), smul_eq_mul] } end lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) : measure.map ((*) a) volume = ennreal.of_real (|a⁻¹|) • volume := by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one, one_smul] } @[simp] lemma volume_preimage_mul_left {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume (((*) a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume (((*) a) ⁻¹' s) = measure.map ((*) a) volume s : ((homeomorph.mul_left₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_left h, refl } lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map (* a) volume = volume := by simpa only [mul_comm] using real.smul_map_volume_mul_left h lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) : measure.map (* a) volume = ennreal.of_real (|a⁻¹|) • volume := by simpa only [mul_comm] using real.map_volume_mul_left h @[simp] lemma volume_preimage_mul_right {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume ((* a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume ((* a) ⁻¹' s) = measure.map (* a) volume s : ((homeomorph.mul_right₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_right h, refl } /-! ### Images of the Lebesgue measure under translation/linear maps in ℝⁿ -/ open matrix /-- A diagonal matrix rescales Lebesgue according to its determinant. This is a special case of `real.map_matrix_volume_pi_eq_smul_volume_pi`, that one should use instead (and whose proof uses this particular case). -/ lemma smul_map_diagonal_volume_pi [decidable_eq ι] {D : ι → ℝ} (h : det (diagonal D) ≠ 0) : ennreal.of_real (abs (det (diagonal D))) • measure.map ((diagonal D).to_lin') volume = volume := begin refine (measure.pi_eq (λ s hs, _)).symm, simp only [det_diagonal, measure.coe_smul, algebra.id.smul_eq_mul, pi.smul_apply], rw [measure.map_apply _ (measurable_set.univ_pi hs)], swap, { exact continuous.measurable (linear_map.continuous_on_pi _) }, have : (matrix.to_lin' (diagonal D)) ⁻¹' (set.pi set.univ (λ (i : ι), s i)) = set.pi set.univ (λ (i : ι), ((*) (D i)) ⁻¹' (s i)), { ext f, simp only [linear_map.coe_proj, algebra.id.smul_eq_mul, linear_map.smul_apply, mem_univ_pi, mem_preimage, linear_map.pi_apply, diagonal_to_lin'] }, have B : ∀ i, of_real (abs (D i)) * volume (has_mul.mul (D i) ⁻¹' s i) = volume (s i), { assume i, have A : D i ≠ 0, { simp only [det_diagonal, ne.def] at h, exact finset.prod_ne_zero_iff.1 h i (finset.mem_univ i) }, rw [volume_preimage_mul_left A, ← mul_assoc, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_inv_cancel A, abs_one, ennreal.of_real_one, one_mul] }, rw [this, volume_pi_pi, finset.abs_prod, ennreal.of_real_prod_of_nonneg (λ i hi, abs_nonneg (D i)), ← finset.prod_mul_distrib], simp only [B] end /-- A transvection preserves Lebesgue measure. -/ lemma volume_preserving_transvection_struct [decidable_eq ι] (t : transvection_struct ι ℝ) : measure_preserving (t.to_matrix.to_lin') := begin /- We separate the coordinate along which there is a shearing from the other ones, and apply Fubini. Along this coordinate (and when all the other coordinates are fixed), it acts like a translation, and therefore preserves Lebesgue. -/ let p : ι → Prop := λ i, i ≠ t.i, let α : Type* := {x // p x}, let β : Type* := {x // ¬ (p x)}, let g : (α → ℝ) → (β → ℝ) → (β → ℝ) := λ a b, (λ x, t.c * a ⟨t.j, t.hij.symm⟩) + b, let F : (α → ℝ) × (β → ℝ) → (α → ℝ) × (β → ℝ) := λ p, (id p.1, g p.1 p.2), let e : (ι → ℝ) ≃ᵐ (α → ℝ) × (β → ℝ) := measurable_equiv.pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p, have : (t.to_matrix.to_lin' : (ι → ℝ) → (ι → ℝ)) = e.symm ∘ F ∘ e, { cases t, ext f k, simp only [linear_equiv.map_smul, dite_eq_ite, linear_map.id_coe, p, ite_not, algebra.id.smul_eq_mul, one_mul, dot_product, std_basis_matrix, measurable_equiv.pi_equiv_pi_subtype_prod_symm_apply, id.def, transvection, pi.add_apply, zero_mul, linear_map.smul_apply, function.comp_app, measurable_equiv.pi_equiv_pi_subtype_prod_apply, matrix.transvection_struct.to_matrix_mk, matrix.mul_vec, linear_equiv.map_add, ite_mul, e, matrix.to_lin'_apply, pi.smul_apply, subtype.coe_mk, g, linear_map.add_apply, finset.sum_congr, matrix.to_lin'_one], by_cases h : t_i = k, { simp only [h, true_and, finset.mem_univ, if_true, eq_self_iff_true, finset.sum_ite_eq, one_apply, boole_mul, add_comm], }, { simp only [h, ne.symm h, add_zero, if_false, finset.sum_const_zero, false_and, mul_zero] } }, rw this, have A : measure_preserving e, { convert volume_preserving_pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p }, have B : measure_preserving F, { have g_meas : measurable (function.uncurry g), { have : measurable (λ (c : (α → ℝ)), c ⟨t.j, t.hij.symm⟩) := measurable_pi_apply ⟨t.j, t.hij.symm⟩, refine (measurable_pi_lambda _ (λ i, measurable.const_mul _ _)).add measurable_snd, exact this.comp measurable_fst }, exact (measure_preserving.id _).skew_product g_meas (eventually_of_forall (λ a, map_add_left_eq_self _ _)) }, exact ((A.symm e).comp B).comp A, end /-- Any invertible matrix rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_matrix_volume_pi_eq_smul_volume_pi [decidable_eq ι] {M : matrix ι ι ℝ} (hM : det M ≠ 0) : measure.map M.to_lin' volume = ennreal.of_real (abs (det M)⁻¹) • volume := begin -- This follows from the cases we have already proved, of diagonal matrices and transvections, -- as these matrices generate all invertible matrices. apply diagonal_transvection_induction_of_det_ne_zero _ M hM (λ D hD, _) (λ t, _) (λ A B hA hB IHA IHB, _), { conv_rhs { rw [← smul_map_diagonal_volume_pi hD] }, rw [smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel hD, abs_one, ennreal.of_real_one, one_smul] }, { simp only [matrix.transvection_struct.det, ennreal.of_real_one, (volume_preserving_transvection_struct _).map_eq, one_smul, _root_.inv_one, abs_one] }, { rw [to_lin'_mul, det_mul, linear_map.coe_comp, ← measure.map_map, IHB, measure.map_smul, IHA, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_comm, mul_inv], { apply continuous.measurable, apply linear_map.continuous_on_pi }, { apply continuous.measurable, apply linear_map.continuous_on_pi } } end /-- Any invertible linear map rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_linear_map_volume_pi_eq_smul_volume_pi {f : (ι → ℝ) →ₗ[ℝ] (ι → ℝ)} (hf : f.det ≠ 0) : measure.map f volume = ennreal.of_real (abs (f.det)⁻¹) • volume := begin -- this is deduced from the matrix case classical, let M := f.to_matrix', have A : f.det = det M, by simp only [linear_map.det_to_matrix'], have B : f = M.to_lin', by simp only [to_lin'_to_matrix'], rw [A, B], apply map_matrix_volume_pi_eq_smul_volume_pi, rwa A at hf end end real section region_between variable {α : Type*} /-- The region between two real-valued functions on an arbitrary set. -/ def region_between (f g : α → ℝ) (s : set α) : set (α × ℝ) := {p : α × ℝ | p.1 ∈ s ∧ p.2 ∈ Ioo (f p.1) (g p.1)} lemma region_between_subset (f g : α → ℝ) (s : set α) : region_between f g s ⊆ s ×ˢ univ := by simpa only [prod_univ, region_between, set.preimage, set_of_subset_set_of] using λ a, and.left variables [measurable_space α] {μ : measure α} {f g : α → ℝ} {s : set α} /-- The region between two measurable functions on a measurable set is measurable. -/ lemma measurable_set_region_between (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set (region_between f g s) := begin dsimp only [region_between, Ioo, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graph of the upper function. -/ lemma measurable_set_region_between_oc (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Ioc (f p.fst) (g p.fst)} := begin dsimp only [region_between, Ioc, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_le measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graph of the lower function. -/ lemma measurable_set_region_between_co (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Ico (f p.fst) (g p.fst)} := begin dsimp only [region_between, Ico, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_le (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graphs of both functions. -/ lemma measurable_set_region_between_cc (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Icc (f p.fst) (g p.fst)} := begin dsimp only [region_between, Icc, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_le (hf.comp measurable_fst) measurable_snd).inter (measurable_set_le measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The graph of a measurable function is a measurable set. -/ lemma measurable_set_graph (hf : measurable f) : measurable_set {p : α × ℝ | p.snd = f p.fst} := by simpa using measurable_set_region_between_cc hf hf measurable_set.univ theorem volume_region_between_eq_lintegral' (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin classical, rw measure.prod_apply, { have h : (λ x, volume {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)}) = s.indicator (λ x, ennreal.of_real (g x - f x)), { funext x, rw indicator_apply, split_ifs, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = Ioo (f x) (g x) := by simp [h, Ioo], simp only [hx, real.volume_Ioo, sub_zero] }, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = ∅ := by simp [h], simp only [hx, measure_empty] } }, dsimp only [region_between, preimage_set_of_eq], rw [h, lintegral_indicator]; simp only [hs, pi.sub_apply] }, { exact measurable_set_region_between hf hg hs }, end /-- The volume of the region between two almost everywhere measurable functions on a measurable set can be represented as a Lebesgue integral. -/ theorem volume_region_between_eq_lintegral [sigma_finite μ] (hf : ae_measurable f (μ.restrict s)) (hg : ae_measurable g (μ.restrict s)) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin have h₁ : (λ y, ennreal.of_real ((g - f) y)) =ᵐ[μ.restrict s] λ y, ennreal.of_real ((ae_measurable.mk g hg - ae_measurable.mk f hf) y) := (hg.ae_eq_mk.sub hf.ae_eq_mk).fun_comp _, have h₂ : (μ.restrict s).prod volume (region_between f g s) = (μ.restrict s).prod volume (region_between (ae_measurable.mk f hf) (ae_measurable.mk g hg) s), { apply measure_congr, apply eventually_eq.rfl.inter, exact ((quasi_measure_preserving_fst.ae_eq_comp hf.ae_eq_mk).comp₂ _ eventually_eq.rfl).inter (eventually_eq.rfl.comp₂ _ $ quasi_measure_preserving_fst.ae_eq_comp hg.ae_eq_mk) }, rw [lintegral_congr_ae h₁, ← volume_region_between_eq_lintegral' hf.measurable_mk hg.measurable_mk hs], convert h₂ using 1, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset f g s)).symm, }, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset (ae_measurable.mk f hf) (ae_measurable.mk g hg) s)).symm }, end theorem volume_region_between_eq_integral' [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : f ≤ᵐ[μ.restrict s] g ) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := begin have h : g - f =ᵐ[μ.restrict s] (λ x, real.to_nnreal (g x - f x)), from hfg.mono (λ x hx, (real.coe_to_nnreal _ $ sub_nonneg.2 hx).symm), rw [volume_region_between_eq_lintegral f_int.ae_measurable g_int.ae_measurable hs, integral_congr_ae h, lintegral_congr_ae, lintegral_coe_eq_integral _ ((integrable_congr h).mp (g_int.sub f_int))], simpa only, end /-- If two functions are integrable on a measurable set, and one function is less than or equal to the other on that set, then the volume of the region between the two functions can be represented as an integral. -/ theorem volume_region_between_eq_integral [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : ∀ x ∈ s, f x ≤ g x) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := volume_region_between_eq_integral' f_int g_int hs ((ae_restrict_iff' hs).mpr (eventually_of_forall hfg)) end region_between /-- Consider a real set `s`. If a property is true almost everywhere in `s ∩ (a, b)` for all `a, b ∈ s`, then it is true almost everywhere in `s`. Formulated with `μ.restrict`. See also `ae_of_mem_of_ae_of_mem_inter_Ioo`. -/ lemma ae_restrict_of_ae_restrict_inter_Ioo {μ : measure ℝ} [has_no_atoms μ] {s : set ℝ} {p : ℝ → Prop} (h : ∀ a b, a ∈ s → b ∈ s → a < b → ∀ᵐ x ∂(μ.restrict (s ∩ Ioo a b)), p x) : ∀ᵐ x ∂(μ.restrict s), p x := begin /- By second-countability, we cover `s` by countably many intervals `(a, b)` (except maybe for two endpoints, which don't matter since `μ` does not have any atom). -/ let T : s × s → set ℝ := λ p, Ioo p.1 p.2, let u := ⋃ (i : ↥s × ↥s), T i, have hfinite : (s \ u).finite := s.finite_diff_Union_Ioo', obtain ⟨A, A_count, hA⟩ : ∃ (A : set (↥s × ↥s)), A.countable ∧ (⋃ (i ∈ A), T i) = ⋃ (i : ↥s × ↥s), T i := is_open_Union_countable _ (λ p, is_open_Ioo), have : s ⊆ (s \ u) ∪ (⋃ p ∈ A, s ∩ T p), { assume x hx, by_cases h'x : x ∈ ⋃ (i : ↥s × ↥s), T i, { rw ← hA at h'x, obtain ⟨p, pA, xp⟩ : ∃ (p : ↥s × ↥s), p ∈ A ∧ x ∈ T p, by simpa only [mem_Union, exists_prop, set_coe.exists, exists_and_distrib_right] using h'x, right, exact mem_bUnion pA ⟨hx, xp⟩ }, { exact or.inl ⟨hx, h'x⟩ } }, apply ae_restrict_of_ae_restrict_of_subset this, rw [ae_restrict_union_iff, ae_restrict_bUnion_iff _ A_count], split, { have : μ.restrict (s \ u) = 0, by simp only [restrict_eq_zero, hfinite.measure_zero], simp only [this, ae_zero] }, { rintros ⟨⟨a, as⟩, ⟨b, bs⟩⟩ -, dsimp [T], rcases le_or_lt b a with hba|hab, { simp only [Ioo_eq_empty_of_le hba, inter_empty, restrict_empty, ae_zero] }, { exact h a b as bs hab } } end /-- Consider a real set `s`. If a property is true almost everywhere in `s ∩ (a, b)` for all `a, b ∈ s`, then it is true almost everywhere in `s`. Formulated with bare membership. See also `ae_restrict_of_ae_restrict_inter_Ioo`. -/ lemma ae_of_mem_of_ae_of_mem_inter_Ioo {μ : measure ℝ} [has_no_atoms μ] {s : set ℝ} {p : ℝ → Prop} (h : ∀ a b, a ∈ s → b ∈ s → a < b → ∀ᵐ x ∂μ, x ∈ s ∩ Ioo a b → p x) : ∀ᵐ x ∂μ, x ∈ s → p x := begin /- By second-countability, we cover `s` by countably many intervals `(a, b)` (except maybe for two endpoints, which don't matter since `μ` does not have any atom). -/ let T : s × s → set ℝ := λ p, Ioo p.1 p.2, let u := ⋃ (i : ↥s × ↥s), T i, have hfinite : (s \ u).finite := s.finite_diff_Union_Ioo', obtain ⟨A, A_count, hA⟩ : ∃ (A : set (↥s × ↥s)), A.countable ∧ (⋃ (i ∈ A), T i) = ⋃ (i : ↥s × ↥s), T i := is_open_Union_countable _ (λ p, is_open_Ioo), have M : ∀ᵐ x ∂μ, x ∉ s \ u, from hfinite.countable.ae_not_mem _, have M' : ∀ᵐ x ∂μ, ∀ (i : ↥s × ↥s) (H : i ∈ A), x ∈ s ∩ T i → p x, { rw ae_ball_iff A_count, rintros ⟨⟨a, as⟩, ⟨b, bs⟩⟩ -, change ∀ᵐ (x : ℝ) ∂μ, x ∈ s ∩ Ioo a b → p x, rcases le_or_lt b a with hba|hab, { simp only [Ioo_eq_empty_of_le hba, inter_empty, is_empty.forall_iff, eventually_true, mem_empty_iff_false], }, { exact h a b as bs hab } }, filter_upwards [M, M'] with x hx h'x, assume xs, by_cases Hx : x ∈ ⋃ (i : ↥s × ↥s), T i, { rw ← hA at Hx, obtain ⟨p, pA, xp⟩ : ∃ (p : ↥s × ↥s), p ∈ A ∧ x ∈ T p, by simpa only [mem_Union, exists_prop, set_coe.exists, exists_and_distrib_right] using Hx, apply h'x p pA ⟨xs, xp⟩ }, { exact false.elim (hx ⟨xs, Hx⟩) } end section summable_norm_Icc open continuous_map /- The following lemma is a minor variation on `integrable_of_summable_norm_restrict` in `measure_theory.integral.set_integral`, but it is placed here because it needs to know that `Icc a b` has volume `b - a`. -/ /-- If the sequence with `n`-th term the the sup norm of `λ x, f (x + n)` on the interval `Icc 0 1`, for `n ∈ ℤ`, is summable, then `f` is integrable on `ℝ`. -/ lemma real.integrable_of_summable_norm_Icc {E : Type*} [normed_add_comm_group E] {f : C(ℝ, E)} (hf : summable (λ n : ℤ, ‖(f.comp $ continuous_map.add_right n).restrict (Icc 0 1)‖)) : integrable f := begin refine integrable_of_summable_norm_restrict (summable_of_nonneg_of_le (λ n : ℤ, mul_nonneg (norm_nonneg (f.restrict (⟨Icc n (n + 1), is_compact_Icc⟩ : compacts ℝ))) ennreal.to_real_nonneg) (λ n, _) hf) (Union_Icc_int_cast ℝ), simp only [compacts.coe_mk, real.volume_Icc, add_sub_cancel', ennreal.to_real_of_real zero_le_one, mul_one, norm_le _ (norm_nonneg _)], intro x, have := ((f.comp $ continuous_map.add_right n).restrict (Icc 0 1)).norm_coe_le_norm ⟨x - n, ⟨sub_nonneg.mpr x.2.1, sub_le_iff_le_add'.mpr x.2.2⟩⟩, simpa only [continuous_map.restrict_apply, comp_apply, coe_add_right, subtype.coe_mk, sub_add_cancel] using this, end end summable_norm_Icc /-! ### Substituting `-x` for `x` These lemmas are stated in terms of either `Iic` or `Ioi` (neglecting `Iio` and `Ici`) to match mathlib's conventions for integrals over finite intervals (see `interval_integral`). For the case of finite integrals, see `interval_integral.integral_comp_neg`. -/ @[simp] lemma integral_comp_neg_Iic {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] (c : ℝ) (f : ℝ → E) : ∫ x in Iic c, f (-x) = ∫ x in Ioi (-c), f x := begin have A : measurable_embedding (λ x : ℝ, -x), from (homeomorph.neg ℝ).closed_embedding.measurable_embedding, have := A.set_integral_map f (Ici (-c)), rw measure.map_neg_eq_self (volume : measure ℝ) at this, simp_rw [←integral_Ici_eq_integral_Ioi, this, neg_preimage, preimage_neg_Ici, neg_neg], end @[simp] lemma integral_comp_neg_Ioi {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] (c : ℝ) (f : ℝ → E) : ∫ x in Ioi c, f (-x) = ∫ x in Iic (-c), f x := begin rw [←neg_neg c, ←integral_comp_neg_Iic], simp only [neg_neg], end
f0baa3e8ad2163f4689f8869ba4a107421c1a175
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/group_theory/perm/sign.lean
7aaba9fb87b3d46e8d1fa5db6584efe66054af30
[ "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
33,388
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.fintype.basic import algebra.big_operators universes u v open equiv function fintype finset variables {α : Type u} {β : Type v} namespace equiv.perm def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp, λ _, by simp⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext _ _ $ λ ⟨_, _⟩, rfl def of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : perm α := ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *⟩ instance of_subtype.is_group_hom {p : α → Prop} [decidable_pred p] : is_group_hom (@of_subtype α p _) := { map_mul := λ f g, equiv.ext _ _ $ λ x, begin rw [of_subtype, of_subtype, of_subtype], by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp [h, h₁, h₂] }, { simp [h] } end } @[simp] lemma of_subtype_one (p : α → Prop) [decidable_pred p] : @of_subtype α p _ 1 = 1 := is_group_hom.map_one of_subtype lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.injective, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp [disjoint, or.comm] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext _ _ $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := begin induction hp, { refl }, { rw [list.prod_cons, list.prod_cons, hp_ih (list.pairwise_cons.1 hl).2] }, { simp [list.prod_cons, disjoint_mul_comm, (mul_assoc _ _ _).symm, *, list.pairwise_cons] at * }, { rw [hp_ih_a hl, hp_ih_a_1 ((list.perm_pairwise (λ x y (h : disjoint x y), disjoint.symm h) hp_a).1 hl)] } end lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext _ _ $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp [hx] }, { haveI := classical.prop_decidable, simp [hx, not_not.1 (mt (h₂ x) hx)] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext _ _ $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp [support] def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext _ _ $ λ z, begin simp [mul_apply, swap_apply_def], split_ifs; simp [*, eq_inv_iff_eq] at * <|> cc end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] /-- Multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc (swap i j) (swap i j) σ, equiv.swap_mul_self, one_mul] lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp at hxy; tauto, equiv.ext _ _ $ λ z, begin rw [hxy.2, of_subtype], simp [swap_apply_def], split_ifs; cc <|> simp * at * end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp * at * }, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext.2 $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp * at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp * at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext _ _ $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [decidable_linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp [hl.1.symm] {contextual := tt} }, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext _ _ $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a.1).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp [fin_pairs_lt, fin.lt_def] def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := (fin_pairs_lt n).prod (λ x, if a x.1 ≤ a x.2 then -1 else 1) @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp [*, injective.eq_iff f.injective, sigma.mk.inj_eq] at * end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp [not_le_of_gt hab]; congr }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end instance sign_aux.is_group_hom {n : ℕ} : is_group_hom (@sign_aux n) := { map_mul := sign_aux_mul } private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = (finset.singleton (⟨one, zero⟩ : Σ a : fin n, fin n)).prod (λ x : Σ a : fin n, fin n, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1), begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp [*, lt_irrefl, -not_lt, not_le.symm, -not_le, le_refl, fin.lt_def, fin.le_def, nat.zero_le, zero, one, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact (monoid_hom.of sign_aux).map_is_conj (is_conj_swap hxy dec_trivial) def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext _ _ $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, from equiv.ext _ _ (λ z, by rw ← equiv.symm_trans_swap_trans; simp [mul_def]), have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp } end def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp [list.mem_of_perm h]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext _ _ (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] (f : perm α) := sign_aux3 f mem_univ instance sign.is_group_hom [fintype α] : is_group_hom (@sign α _ _) := { map_mul := λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1 } section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := is_mul_hom.map_mul sign _ _ @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := is_group_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := is_group_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [is_group_hom.map_inv sign, int.units_inv_eq_self]; apply_instance lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext _ _ (λ x, by simp))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = -1 ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, list.prod_hom _ (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_one_lt_card hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α → units ℤ} [is_group_hom s] (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact (monoid_hom.of s).map_is_conj (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [← l.prod_hom s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), funext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, ← l.prod_hom s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [l.1.prod_hom of_subtype, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext _ _ $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (show function.bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})), from ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩)) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp [inv_eq_iff_eq, eq_inv_iff_eq] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext _ _ $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext.2 $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x::y::0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext]; cc lemma sign_cycle [fintype α] : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1 ^ f.support.card) | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1 ^ f.support.card) : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, by conv in (f) {rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1 }; simp [mul_def, one_def], by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp [pow_add] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} end sign end equiv.perm lemma finset.prod_univ_perm [fintype α] [comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).prod f = univ.prod (λ z, f (σ z)) := eq.symm $ prod_bij (λ z _, σ z) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ H, σ.injective H) (λ b _, ⟨σ⁻¹ b, mem_univ _, by simp⟩) lemma finset.sum_univ_perm [fintype α] [add_comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).sum f = univ.sum (λ z, f (σ z)) := @finset.prod_univ_perm _ (multiplicative β) _ _ f σ attribute [to_additive] finset.prod_univ_perm
8ff9d650ae95a8ddfb76d2e3558500dbec869344
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/MeetSemilattice.lean
b232e8768c86efc5eee563b7e6161eccac5b5f67
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,383
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section MeetSemilattice structure MeetSemilattice (A : Type) : Type := (op : (A → (A → A))) (associative_op : (∀ {x y z : A} , (op (op x y) z) = (op x (op y z)))) (idempotent_op : (∀ {x : A} , (op x x) = x)) (commutative_op : (∀ {x y : A} , (op x y) = (op y x))) open MeetSemilattice structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (associative_opP : (∀ {xP yP zP : (Prod A A)} , (opP (opP xP yP) zP) = (opP xP (opP yP zP)))) (idempotent_opP : (∀ {xP : (Prod A A)} , (opP xP xP) = xP)) (commutative_opP : (∀ {xP yP : (Prod A A)} , (opP xP yP) = (opP yP xP))) structure Hom {A1 : Type} {A2 : Type} (Me1 : (MeetSemilattice A1)) (Me2 : (MeetSemilattice A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Me1) x1 x2)) = ((op Me2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Me1 : (MeetSemilattice A1)) (Me2 : (MeetSemilattice A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Me1) x1 x2) ((op Me2) y1 y2)))))) inductive MeetSemilatticeTerm : Type | opL : (MeetSemilatticeTerm → (MeetSemilatticeTerm → MeetSemilatticeTerm)) open MeetSemilatticeTerm inductive ClMeetSemilatticeTerm (A : Type) : Type | sing : (A → ClMeetSemilatticeTerm) | opCl : (ClMeetSemilatticeTerm → (ClMeetSemilatticeTerm → ClMeetSemilatticeTerm)) open ClMeetSemilatticeTerm inductive OpMeetSemilatticeTerm (n : ℕ) : Type | v : ((fin n) → OpMeetSemilatticeTerm) | opOL : (OpMeetSemilatticeTerm → (OpMeetSemilatticeTerm → OpMeetSemilatticeTerm)) open OpMeetSemilatticeTerm inductive OpMeetSemilatticeTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpMeetSemilatticeTerm2) | sing2 : (A → OpMeetSemilatticeTerm2) | opOL2 : (OpMeetSemilatticeTerm2 → (OpMeetSemilatticeTerm2 → OpMeetSemilatticeTerm2)) open OpMeetSemilatticeTerm2 def simplifyCl {A : Type} : ((ClMeetSemilatticeTerm A) → (ClMeetSemilatticeTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpMeetSemilatticeTerm n) → (OpMeetSemilatticeTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpMeetSemilatticeTerm2 n A) → (OpMeetSemilatticeTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((MeetSemilattice A) → (MeetSemilatticeTerm → A)) | Me (opL x1 x2) := ((op Me) (evalB Me x1) (evalB Me x2)) def evalCl {A : Type} : ((MeetSemilattice A) → ((ClMeetSemilatticeTerm A) → A)) | Me (sing x1) := x1 | Me (opCl x1 x2) := ((op Me) (evalCl Me x1) (evalCl Me x2)) def evalOpB {A : Type} {n : ℕ} : ((MeetSemilattice A) → ((vector A n) → ((OpMeetSemilatticeTerm n) → A))) | Me vars (v x1) := (nth vars x1) | Me vars (opOL x1 x2) := ((op Me) (evalOpB Me vars x1) (evalOpB Me vars x2)) def evalOp {A : Type} {n : ℕ} : ((MeetSemilattice A) → ((vector A n) → ((OpMeetSemilatticeTerm2 n A) → A))) | Me vars (v2 x1) := (nth vars x1) | Me vars (sing2 x1) := x1 | Me vars (opOL2 x1 x2) := ((op Me) (evalOp Me vars x1) (evalOp Me vars x2)) def inductionB {P : (MeetSemilatticeTerm → Type)} : ((∀ (x1 x2 : MeetSemilatticeTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : MeetSemilatticeTerm) , (P x))) | popl (opL x1 x2) := (popl _ _ (inductionB popl x1) (inductionB popl x2)) def inductionCl {A : Type} {P : ((ClMeetSemilatticeTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClMeetSemilatticeTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClMeetSemilatticeTerm A)) , (P x)))) | psing popcl (sing x1) := (psing x1) | psing popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl x1) (inductionCl psing popcl x2)) def inductionOpB {n : ℕ} {P : ((OpMeetSemilatticeTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpMeetSemilatticeTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpMeetSemilatticeTerm n)) , (P x)))) | pv popol (v x1) := (pv x1) | pv popol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol x1) (inductionOpB pv popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpMeetSemilatticeTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpMeetSemilatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpMeetSemilatticeTerm2 n A)) , (P x))))) | pv2 psing2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 x1) (inductionOp pv2 psing2 popol2 x2)) def stageB : (MeetSemilatticeTerm → (Staged MeetSemilatticeTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClMeetSemilatticeTerm A) → (Staged (ClMeetSemilatticeTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpMeetSemilatticeTerm n) → (Staged (OpMeetSemilatticeTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpMeetSemilatticeTerm2 n A) → (Staged (OpMeetSemilatticeTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) end MeetSemilattice
d8ae2a9fe615bd02fe97d8316cf38b5dd84c7401
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Data/Fin/Basic.lean
ee4516150dc4d39b756a8560afc9bc000b48d4ee
[ "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
3,078
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Nat.Div import Init.Data.Nat.Bitwise import Init.Coe open Nat namespace Fin instance coeToNat {n} : Coe (Fin n) Nat := ⟨fun v => v.val⟩ def elim0.{u} {α : Sort u} : Fin 0 → α | ⟨_, h⟩ => absurd h (not_lt_zero _) variable {n : Nat} protected def ofNat {n : Nat} (a : Nat) : Fin (succ n) := ⟨a % succ n, Nat.mod_lt _ (Nat.zero_lt_succ _)⟩ protected def ofNat' {n : Nat} (a : Nat) (h : n > 0) : Fin n := ⟨a % n, Nat.mod_lt _ h⟩ private theorem mlt {b : Nat} : {a : Nat} → a < n → b % n < n | 0, h => Nat.mod_lt _ h | a+1, h => have : n > 0 := Nat.lt_trans (Nat.zero_lt_succ _) h; Nat.mod_lt _ this protected def add : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a + b) % n, mlt h⟩ protected def mul : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a * b) % n, mlt h⟩ protected def sub : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a + (n - b)) % n, mlt h⟩ /- Remark: mod/div/modn/land/lor can be defined without using (% n), but we are trying to minimize the number of Nat theorems needed to boostrap Lean. -/ protected def mod : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a % b) % n, mlt h⟩ protected def div : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a / b) % n, mlt h⟩ protected def modn : Fin n → Nat → Fin n | ⟨a, h⟩, m => ⟨(a % m) % n, mlt h⟩ def land : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(Nat.land a b) % n, mlt h⟩ def lor : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(Nat.lor a b) % n, mlt h⟩ def xor : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(Nat.xor a b) % n, mlt h⟩ def shiftLeft : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a <<< b) % n, mlt h⟩ def shiftRight : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a >>> b) % n, mlt h⟩ instance : Add (Fin n) where add := Fin.add instance : Sub (Fin n) where sub := Fin.sub instance : Mul (Fin n) where mul := Fin.mul instance : Mod (Fin n) where mod := Fin.mod instance : Div (Fin n) where div := Fin.div instance : AndOp (Fin n) where and := Fin.land instance : OrOp (Fin n) where or := Fin.lor instance : Xor (Fin n) where xor := Fin.xor instance : ShiftLeft (Fin n) where shiftLeft := Fin.shiftLeft instance : ShiftRight (Fin n) where shiftRight := Fin.shiftRight instance : HMod (Fin n) Nat (Fin n) where hMod := Fin.modn instance : OfNat (Fin (no_index (n+1))) i where ofNat := Fin.ofNat i instance : Inhabited (Fin (no_index (n+1))) where default := 0 theorem val_ne_of_ne {i j : Fin n} (h : i ≠ j) : val i ≠ val j := fun h' => absurd (eq_of_val_eq h') h theorem modn_lt : ∀ {m : Nat} (i : Fin n), m > 0 → (i % m).val < m | m, ⟨a, h⟩, hp => Nat.lt_of_le_of_lt (mod_le _ _) (mod_lt _ hp) end Fin open Fin
efd8e27a5ef63415975afdb62d564f97b9e7ecf6
4aca55eba10c989f0d58647d3c2f371e7da44355
/src/inv_matrix.lean
690ffa06c5a7622cd868ebff8d3295b7efdb2be4
[]
no_license
eric-wieser/l534zhan-my_project
f9fc75fb5454405e1a2fa9b56cf96c355f6f2336
febc91e76b7b00fe2517f258ca04d27b7f35fcf3
refs/heads/master
1,689,218,910,420
1,630,439,440,000
1,630,439,440,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,479
lean
/- Copyright (c) 2021 Lu-Ming Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Lu-Ming Zhang. -/ /- import linear_algebra.matrix.nonsingular_inverse /-! This file supplements things about matrix inverse, that were missing in mathlib. -/ namespace matrix universes u v variables {n : Type u} [decidable_eq n] [fintype n] {α : Type v} [comm_ring α] open_locale matrix big_operators open equiv equiv.perm finset variables (A : matrix n n α) (B : matrix n n α) /- `is_unit_of_invertible A` converts the "stronger" condition `invertible A` to proposition `is_unit A`. -/ /-- `matrix.is_unit_det_of_invertible` converts `invertible A` to `is_unit A.det`. -/ lemma is_unit_det_of_invertible [invertible A] : is_unit A.det := @is_unit_of_invertible _ _ _(det_invertible_of_invertible A) @[simp] lemma inv_eq_nonsing_inv_of_invertible [invertible A] : ⅟ A = A⁻¹ := begin suffices : is_unit A, { rw [←this.mul_left_inj, inv_of_mul_self, matrix.mul_eq_mul, nonsing_inv_mul], rwa ←is_unit_iff_is_unit_det }, exact is_unit_of_invertible _ end variables {A} {B} /- `is_unit.invertible` lifts the proposition `is_unit A` to a constructive inverse of `A`. -/ /-- "Lift" the proposition `is_unit A.det` to a constructive inverse of `A`. -/ noncomputable def invertible_of_is_unit_det (h : is_unit A.det) : invertible A := ⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩ /-- If matrix A is left invertible, then its inverse equals its left inverse. -/ lemma inv_eq_left_inv (h : B ⬝ A = 1) : A⁻¹ = B := begin have h1 := (is_unit_det_of_left_inverse h), have h2 := matrix.invertible_of_is_unit_det h1, have := @inv_of_eq_left_inv (matrix n n α) (infer_instance) A B h2 h, simp* at *, end /-- If matrix A is right invertible, then its inverse equals its right inverse. -/ lemma inv_eq_right_inv (h : A ⬝ B = 1) : A⁻¹ = B := begin have h1 := (is_unit_det_of_right_inverse h), have h2 := matrix.invertible_of_is_unit_det h1, have := @inv_of_eq_right_inv (matrix n n α) (infer_instance) A B h2 h, simp* at *, end /-- We can construct an instance of invertible A if A has a left inverse. -/ def invertible_of_left_inverse (h: B ⬝ A = 1) : invertible A := ⟨B, h, nonsing_inv_right_left h⟩ /-- We can construct an instance of invertible A if A has a right inverse. -/ def invertible_of_right_inverse (h: A ⬝ B = 1) : invertible A := ⟨B, nonsing_inv_left_right h, h⟩ variables {C: matrix n n α} /-- The left inverse of matrix A is unique when existing. -/ lemma left_inv_eq_left_inv (h: B ⬝ A = 1) (g: C ⬝ A = 1) : B = C := by rw [←(inv_eq_left_inv h), ←(inv_eq_left_inv g)] /-- The right inverse of matrix A is unique when existing. -/ lemma right_inv_eq_right_inv (h: A ⬝ B = 1) (g: A ⬝ C = 1) : B = C := by rw [←(inv_eq_right_inv h), ←(inv_eq_right_inv g)] /-- The right inverse of matrix A equals the left inverse of A when they exist. -/ lemma right_inv_eq_left_inv (h: A ⬝ B = 1) (g: C ⬝ A = 1) : B = C := by rw [←(inv_eq_right_inv h), ←(inv_eq_left_inv g)] variable (A) @[simp] lemma mul_inv_of_invertible [invertible A] : A ⬝ A⁻¹ = 1 := mul_nonsing_inv A (is_unit_det_of_invertible A) @[simp] lemma inv_mul_of_invertible [invertible A] : A⁻¹ ⬝ A = 1 := nonsing_inv_mul A (is_unit_det_of_invertible A) end matrix -/
02f346e28bb044e423d2ac56fe77765cd1503dd5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/invariant_basis_number.lean
27204aca6438a223d2fac7e4b23a909d9a1eb144
[ "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
12,195
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import ring_theory.ideal.quotient import ring_theory.principal_ideal_domain /-! # Invariant basis number property We say that a ring `R` satisfies the invariant basis number property if there is a well-defined notion of the rank of a finitely generated free (left) `R`-module. Since a finitely generated free module with a basis consisting of `n` elements is linearly equivalent to `fin n → R`, it is sufficient that `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. It is also useful to consider two stronger conditions, namely the rank condition, that a surjective linear map `(fin n → R) →ₗ[R] (fin m → R)` implies `m ≤ n` and the strong rank condition, that an injective linear map `(fin n → R) →ₗ[R] (fin m → R)` implies `n ≤ m`. The strong rank condition implies the rank condition, and the rank condition implies the invariant basis number property. ## Main definitions `strong_rank_condition R` is a type class stating that `R` satisfies the strong rank condition. `rank_condition R` is a type class stating that `R` satisfies the rank condition. `invariant_basis_number R` is a type class stating that `R` has the invariant basis number property. ## Main results We show that every nontrivial left-noetherian ring satisfies the strong rank condition, (and so in particular every division ring or field), and then use this to show every nontrivial commutative ring has the invariant basis number property. More generally, every commutative ring satisfies the strong rank condition. This is proved in `linear_algebra/free_module/strong_rank_condition`. We keep `invariant_basis_number_of_nontrivial_of_comm_ring` here since it imports fewer files. ## Future work So far, there is no API at all for the `invariant_basis_number` class. There are several natural ways to formulate that a module `M` is finitely generated and free, for example `M ≃ₗ[R] (fin n → R)`, `M ≃ₗ[R] (ι → R)`, where `ι` is a fintype, or providing a basis indexed by a finite type. There should be lemmas applying the invariant basis number property to each situation. The finite version of the invariant basis number property implies the infinite analogue, i.e., that `(ι →₀ R) ≃ₗ[R] (ι' →₀ R)` implies that `cardinal.mk ι = cardinal.mk ι'`. This fact (and its variants) should be formalized. ## References * https://en.wikipedia.org/wiki/Invariant_basis_number * https://mathoverflow.net/a/2574/ ## Tags free module, rank, invariant basis number, IBN -/ noncomputable theory open_locale classical big_operators open function universes u v w section variables (R : Type u) [semiring R] /-- We say that `R` satisfies the strong rank condition if `(fin n → R) →ₗ[R] (fin m → R)` injective implies `n ≤ m`. -/ @[mk_iff] class strong_rank_condition : Prop := (le_of_fin_injective : ∀ {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)), injective f → n ≤ m) lemma le_of_fin_injective [strong_rank_condition R] {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)) : injective f → n ≤ m := strong_rank_condition.le_of_fin_injective f /-- A ring satisfies the strong rank condition if and only if, for all `n : ℕ`, any linear map `(fin (n + 1) → R) →ₗ[R] (fin n → R)` is not injective. -/ lemma strong_rank_condition_iff_succ : strong_rank_condition R ↔ ∀ (n : ℕ) (f : (fin (n + 1) → R) →ₗ[R] (fin n → R)), ¬function.injective f := begin refine ⟨λ h n, λ f hf, _, λ h, ⟨λ n m f hf, _⟩⟩, { letI : strong_rank_condition R := h, exact nat.not_succ_le_self n (le_of_fin_injective R f hf) }, { by_contra H, exact h m (f.comp (function.extend_by_zero.linear_map R (fin.cast_le (not_le.1 H)))) (hf.comp (function.extend_injective (rel_embedding.injective _) 0)) } end lemma card_le_of_injective [strong_rank_condition R] {α β : Type*} [fintype α] [fintype β] (f : (α → R) →ₗ[R] (β → R)) (i : injective f) : fintype.card α ≤ fintype.card β := begin let P := linear_equiv.fun_congr_left R R (fintype.equiv_fin α), let Q := linear_equiv.fun_congr_left R R (fintype.equiv_fin β), exact le_of_fin_injective R ((Q.symm.to_linear_map.comp f).comp P.to_linear_map) (((linear_equiv.symm Q).injective.comp i).comp (linear_equiv.injective P)), end lemma card_le_of_injective' [strong_rank_condition R] {α β : Type*} [fintype α] [fintype β] (f : (α →₀ R) →ₗ[R] (β →₀ R)) (i : injective f) : fintype.card α ≤ fintype.card β := begin let P := (finsupp.linear_equiv_fun_on_finite R R β), let Q := (finsupp.linear_equiv_fun_on_finite R R α).symm, exact card_le_of_injective R ((P.to_linear_map.comp f).comp Q.to_linear_map) ((P.injective.comp i).comp Q.injective) end /-- We say that `R` satisfies the rank condition if `(fin n → R) →ₗ[R] (fin m → R)` surjective implies `m ≤ n`. -/ class rank_condition : Prop := (le_of_fin_surjective : ∀ {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)), surjective f → m ≤ n) lemma le_of_fin_surjective [rank_condition R] {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)) : surjective f → m ≤ n := rank_condition.le_of_fin_surjective f lemma card_le_of_surjective [rank_condition R] {α β : Type*} [fintype α] [fintype β] (f : (α → R) →ₗ[R] (β → R)) (i : surjective f) : fintype.card β ≤ fintype.card α := begin let P := linear_equiv.fun_congr_left R R (fintype.equiv_fin α), let Q := linear_equiv.fun_congr_left R R (fintype.equiv_fin β), exact le_of_fin_surjective R ((Q.symm.to_linear_map.comp f).comp P.to_linear_map) (((linear_equiv.symm Q).surjective.comp i).comp (linear_equiv.surjective P)), end lemma card_le_of_surjective' [rank_condition R] {α β : Type*} [fintype α] [fintype β] (f : (α →₀ R) →ₗ[R] (β →₀ R)) (i : surjective f) : fintype.card β ≤ fintype.card α := begin let P := (finsupp.linear_equiv_fun_on_finite R R β), let Q := (finsupp.linear_equiv_fun_on_finite R R α).symm, exact card_le_of_surjective R ((P.to_linear_map.comp f).comp Q.to_linear_map) ((P.surjective.comp i).comp Q.surjective) end /-- By the universal property for free modules, any surjective map `(fin n → R) →ₗ[R] (fin m → R)` has an injective splitting `(fin m → R) →ₗ[R] (fin n → R)` from which the strong rank condition gives the necessary inequality for the rank condition. -/ @[priority 100] instance rank_condition_of_strong_rank_condition [strong_rank_condition R] : rank_condition R := { le_of_fin_surjective := λ n m f s, le_of_fin_injective R _ (f.splitting_of_fun_on_fintype_surjective_injective s), } /-- We say that `R` has the invariant basis number property if `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. This gives rise to a well-defined notion of rank of a finitely generated free module. -/ class invariant_basis_number : Prop := (eq_of_fin_equiv : ∀ {n m : ℕ}, ((fin n → R) ≃ₗ[R] (fin m → R)) → n = m) @[priority 100] instance invariant_basis_number_of_rank_condition [rank_condition R] : invariant_basis_number R := { eq_of_fin_equiv := λ n m e, le_antisymm (le_of_fin_surjective R e.symm.to_linear_map e.symm.surjective) (le_of_fin_surjective R e.to_linear_map e.surjective) } end section variables (R : Type u) [semiring R] [invariant_basis_number R] lemma eq_of_fin_equiv {n m : ℕ} : ((fin n → R) ≃ₗ[R] (fin m → R)) → n = m := invariant_basis_number.eq_of_fin_equiv lemma card_eq_of_lequiv {α β : Type*} [fintype α] [fintype β] (f : (α → R) ≃ₗ[R] (β → R)) : fintype.card α = fintype.card β := eq_of_fin_equiv R (((linear_equiv.fun_congr_left R R (fintype.equiv_fin α)).trans f) ≪≫ₗ ((linear_equiv.fun_congr_left R R (fintype.equiv_fin β)).symm)) lemma nontrivial_of_invariant_basis_number : nontrivial R := begin by_contra h, refine zero_ne_one (eq_of_fin_equiv R _), haveI := not_nontrivial_iff_subsingleton.1 h, haveI : subsingleton (fin 1 → R) := ⟨λ a b, funext $ λ x, subsingleton.elim _ _⟩, refine { .. }; { intros, exact 0 } <|> tidy end end section variables (R : Type u) [ring R] [nontrivial R] [is_noetherian_ring R] /-- Any nontrivial noetherian ring satisfies the strong rank condition. An injective map `((fin n ⊕ fin (1 + m)) → R) →ₗ[R] (fin n → R)` for some left-noetherian `R` would force `fin (1 + m) → R ≃ₗ punit` (via `is_noetherian.equiv_punit_of_prod_injective`), which is not the case! -/ -- Note this includes fields, -- and we use this below to show any commutative ring has invariant basis number. @[priority 100] instance noetherian_ring_strong_rank_condition : strong_rank_condition R := begin fsplit, intros m n f i, by_contradiction h, rw [not_le, ←nat.add_one_le_iff, le_iff_exists_add] at h, obtain ⟨m, rfl⟩ := h, let e : fin (n + 1 + m) ≃ fin n ⊕ fin (1 + m) := (fin_congr (add_assoc _ _ _)).trans fin_sum_fin_equiv.symm, let f' := f.comp ((linear_equiv.sum_arrow_lequiv_prod_arrow _ _ R R).symm.trans (linear_equiv.fun_congr_left R R e)).to_linear_map, have i' : injective f' := i.comp (linear_equiv.injective _), apply @zero_ne_one (fin (1 + m) → R) _ _, apply (is_noetherian.equiv_punit_of_prod_injective f' i').injective, ext, end end /-! We want to show that nontrivial commutative rings have invariant basis number. The idea is to take a maximal ideal `I` of `R` and use an isomorphism `R^n ≃ R^m` of `R` modules to produce an isomorphism `(R/I)^n ≃ (R/I)^m` of `R/I`-modules, which will imply `n = m` since `R/I` is a field and we know that fields have invariant basis number. We construct the isomorphism in two steps: 1. We construct the ring `R^n/I^n`, show that it is an `R/I`-module and show that there is an isomorphism of `R/I`-modules `R^n/I^n ≃ (R/I)^n`. This isomorphism is called `ideal.pi_quot_equiv` and is located in the file `ring_theory/ideals.lean`. 2. We construct an isomorphism of `R/I`-modules `R^n/I^n ≃ R^m/I^m` using the isomorphism `R^n ≃ R^m`. -/ section variables {R : Type u} [comm_ring R] (I : ideal R) {ι : Type v} [fintype ι] {ι' : Type w} /-- An `R`-linear map `R^n → R^m` induces a function `R^n/I^n → R^m/I^m`. -/ private def induced_map (I : ideal R) (e : (ι → R) →ₗ[R] (ι' → R)) : (ι → R) ⧸ (I.pi ι) → (ι' → R) ⧸ I.pi ι' := λ x, quotient.lift_on' x (λ y, ideal.quotient.mk _ (e y)) begin refine λ a b hab, ideal.quotient.eq.2 (λ h, _), rw submodule.quotient_rel_r_def at hab, rw ←linear_map.map_sub, exact ideal.map_pi _ _ hab e h, end /-- An isomorphism of `R`-modules `R^n ≃ R^m` induces an isomorphism of `R/I`-modules `R^n/I^n ≃ R^m/I^m`. -/ private def induced_equiv [fintype ι'] (I : ideal R) (e : (ι → R) ≃ₗ[R] (ι' → R)) : ((ι → R) ⧸ I.pi ι) ≃ₗ[R ⧸ I] (ι' → R) ⧸ I.pi ι' := begin refine { to_fun := induced_map I e, inv_fun := induced_map I e.symm, .. }, all_goals { rintro ⟨a⟩ ⟨b⟩ <|> rintro ⟨a⟩, convert_to ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr, simp only [map_add, linear_equiv.coe_coe, linear_equiv.map_smulₛₗ, ring_hom.id_apply, linear_equiv.symm_apply_apply, linear_equiv.apply_symm_apply] } end end section local attribute [instance] ideal.quotient.field /-- Nontrivial commutative rings have the invariant basis number property. In fact, any nontrivial commutative ring satisfies the strong rank condition, see `comm_ring_strong_rank_condition`. We prove this instance separately to avoid dependency on `linear_algebra.charpoly.basic`. -/ @[priority 100] instance invariant_basis_number_of_nontrivial_of_comm_ring {R : Type u} [comm_ring R] [nontrivial R] : invariant_basis_number R := ⟨λ n m e, let ⟨I, hI⟩ := ideal.exists_maximal R in by exactI eq_of_fin_equiv (R ⧸ I) ((ideal.pi_quot_equiv _ _).symm ≪≫ₗ ((induced_equiv _ e) ≪≫ₗ (ideal.pi_quot_equiv _ _)))⟩ end
9b2442dc80801f03cf99808523acf75e2ffefc49
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/modular_lattice.lean
0c898ebc4a11479d36e6cb3bbb29a88750f7f684
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,728
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.rel_iso import order.lattice_intervals import order.order_dual /-! # Modular Lattices This file defines Modular Lattices, a kind of lattice useful in algebra. For examples, look to the subobject lattices of abelian groups, submodules, and ideals, or consider any distributive lattice. ## Main Definitions - `is_modular_lattice` defines a modular lattice to be one such that `x ≤ z → (x ⊔ y) ⊓ z ≤ x ⊔ (y ⊓ z)` - `inf_Icc_order_iso_Icc_sup` gives an order isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]`. This corresponds to the diamond (or second) isomorphism theorems of algebra. ## Main Results - `is_modular_lattice_iff_inf_sup_inf_assoc`: Modularity is equivalent to the `inf_sup_inf_assoc`: `(x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z` - `distrib_lattice.is_modular_lattice`: Distributive lattices are modular. ## To do - Relate atoms and coatoms in modular lattices -/ variable {α : Type*} /-- A modular lattice is one with a limited associativity between `⊓` and `⊔`. -/ class is_modular_lattice α [lattice α] : Prop := (sup_inf_le_assoc_of_le : ∀ {x : α} (y : α) {z : α}, x ≤ z → (x ⊔ y) ⊓ z ≤ x ⊔ (y ⊓ z)) section is_modular_lattice variables [lattice α] [is_modular_lattice α ] theorem sup_inf_assoc_of_le {x : α} (y : α) {z : α} (h : x ≤ z) : (x ⊔ y) ⊓ z = x ⊔ (y ⊓ z) := le_antisymm (is_modular_lattice.sup_inf_le_assoc_of_le y h) (le_inf (sup_le_sup_left inf_le_left _) (sup_le h inf_le_right)) theorem is_modular_lattice.inf_sup_inf_assoc {x y z : α} : (x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z := (sup_inf_assoc_of_le y inf_le_right).symm lemma inf_sup_assoc_of_le {x : α} (y : α) {z : α} (h : z ≤ x) : (x ⊓ y) ⊔ z = x ⊓ (y ⊔ z) := by rw [inf_comm, sup_comm, ← sup_inf_assoc_of_le y h, inf_comm, sup_comm] instance : is_modular_lattice (order_dual α) := ⟨λ x y z xz, le_of_eq (by { rw [inf_comm, sup_comm, eq_comm, inf_comm, sup_comm], convert sup_inf_assoc_of_le (order_dual.of_dual y) (order_dual.dual_le.2 xz) })⟩ theorem is_modular_lattice.sup_inf_sup_assoc {x y z : α} : (x ⊔ z) ⊓ (y ⊔ z) = ((x ⊔ z) ⊓ y) ⊔ z := @is_modular_lattice.inf_sup_inf_assoc (order_dual α) _ _ _ _ _ /-- The diamond isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]` -/ def inf_Icc_order_iso_Icc_sup (a b : α) : set.Icc (a ⊓ b) a ≃o set.Icc b (a ⊔ b) := { to_fun := λ x, ⟨x ⊔ b, ⟨le_sup_right, sup_le_sup_right x.prop.2 b⟩⟩, inv_fun := λ x, ⟨a ⊓ x, ⟨inf_le_inf_left a x.prop.1, inf_le_left⟩⟩, left_inv := λ x, subtype.ext (by { change a ⊓ (↑x ⊔ b) = ↑x, rw [sup_comm, ← inf_sup_assoc_of_le _ x.prop.2, sup_eq_right.2 x.prop.1] }), right_inv := λ x, subtype.ext (by { change a ⊓ ↑x ⊔ b = ↑x, rw [inf_comm, inf_sup_assoc_of_le _ x.prop.1, inf_eq_left.2 x.prop.2] }), map_rel_iff' := λ x y, begin simp only [subtype.mk_le_mk, equiv.coe_fn_mk, and_true, le_sup_right], rw [← subtype.coe_le_coe], refine ⟨λ h, _, λ h, sup_le_sup_right h _⟩, rw [← sup_eq_right.2 x.prop.1, inf_sup_assoc_of_le _ x.prop.2, sup_comm, ← sup_eq_right.2 y.prop.1, inf_sup_assoc_of_le _ y.prop.2, @sup_comm _ _ b], exact inf_le_inf_left _ h end } end is_modular_lattice namespace is_compl variables [bounded_lattice α] [is_modular_lattice α] /-- The diamond isomorphism between the intervals `set.Iic a` and `set.Ici b`. -/ def Iic_order_iso_Ici {a b : α} (h : is_compl a b) : set.Iic a ≃o set.Ici b := (order_iso.set_congr (set.Iic a) (set.Icc (a ⊓ b) a) (h.inf_eq_bot.symm ▸ set.Icc_bot.symm)).trans $ (inf_Icc_order_iso_Icc_sup a b).trans (order_iso.set_congr (set.Icc b (a ⊔ b)) (set.Ici b) (h.sup_eq_top.symm ▸ set.Icc_top)) end is_compl theorem is_modular_lattice_iff_inf_sup_inf_assoc [lattice α] : is_modular_lattice α ↔ ∀ (x y z : α), (x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z := ⟨λ h, @is_modular_lattice.inf_sup_inf_assoc _ _ h, λ h, ⟨λ x y z xz, by rw [← inf_eq_left.2 xz, h]⟩⟩ namespace distrib_lattice @[priority 100] instance [distrib_lattice α] : is_modular_lattice α := ⟨λ x y z xz, by rw [inf_sup_right, inf_eq_left.2 xz]⟩ end distrib_lattice theorem disjoint.disjoint_sup_right_of_disjoint_sup_left [bounded_lattice α] [is_modular_lattice α] {a b c : α} (h : disjoint a b) (hsup : disjoint (a ⊔ b) c) : disjoint a (b ⊔ c) := begin rw [disjoint, ← h.eq_bot, sup_comm], apply le_inf inf_le_left, apply (inf_le_inf_right (c ⊔ b) le_sup_right).trans, rw [sup_comm, is_modular_lattice.sup_inf_sup_assoc, hsup.eq_bot, bot_sup_eq] end theorem disjoint.disjoint_sup_left_of_disjoint_sup_right [bounded_lattice α] [is_modular_lattice α] {a b c : α} (h : disjoint b c) (hsup : disjoint a (b ⊔ c)) : disjoint (a ⊔ b) c := begin rw [disjoint.comm, sup_comm], apply disjoint.disjoint_sup_right_of_disjoint_sup_left h.symm, rwa [sup_comm, disjoint.comm] at hsup, end namespace is_modular_lattice variables [bounded_lattice α] [is_modular_lattice α] {a : α} instance is_modular_lattice_Iic : is_modular_lattice (set.Iic a) := ⟨λ x y z xz, (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ instance is_modular_lattice_Ici : is_modular_lattice (set.Ici a) := ⟨λ x y z xz, (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ section is_complemented variables [is_complemented α] instance is_complemented_Iic : is_complemented (set.Iic a) := ⟨λ ⟨x, hx⟩, let ⟨y, hy⟩ := exists_is_compl x in ⟨⟨y ⊓ a, set.mem_Iic.2 inf_le_right⟩, begin split, { change x ⊓ (y ⊓ a) ≤ ⊥, -- improve lattice subtype API rw ← inf_assoc, exact le_trans inf_le_left hy.1 }, { change a ≤ x ⊔ (y ⊓ a), -- improve lattice subtype API rw [← sup_inf_assoc_of_le _ (set.mem_Iic.1 hx), top_le_iff.1 hy.2, top_inf_eq] } end⟩⟩ instance is_complemented_Ici : is_complemented (set.Ici a) := ⟨λ ⟨x, hx⟩, let ⟨y, hy⟩ := exists_is_compl x in ⟨⟨y ⊔ a, set.mem_Ici.2 le_sup_right⟩, begin split, { change x ⊓ (y ⊔ a) ≤ a, -- improve lattice subtype API rw [← inf_sup_assoc_of_le _ (set.mem_Ici.1 hx), le_bot_iff.1 hy.1, bot_sup_eq] }, { change ⊤ ≤ x ⊔ (y ⊔ a), -- improve lattice subtype API rw ← sup_assoc, exact le_trans hy.2 le_sup_left } end⟩⟩ end is_complemented end is_modular_lattice
2036010ff0e77cc29a384234be1800fcd815a181
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/meta/coinductive_predicates.lean
21e19a2fd9c4dfa9eea6c8287c201c36cb747e48
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
20,491
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 (CMU) -/ import tactic.core section universe u @[user_attribute] meta def monotonicity : user_attribute := { name := `monotonicity, descr := "Monotonicity rules for predicates" } lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := assume h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := assume h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, eapplyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← whnf p, (expr.pi qn qbi qd qb) ← whnf q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, eapply ((const `monotonicity.pi [u] : expr) pd p' q'), skip) <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, eapply ((const `monotonicity.imp []: expr) pd p' qd q'), skip))) <|> first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip), all_goals' mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ private meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← open_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← open_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binding_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all}, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m.2), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, econstructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h, _) ← elim_gen_prod pds.length h [] [], (hs, h, _) ← elim_gen_prod pds.length h [] [], eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do eapply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, eapply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ eapply (pd.destruct.app_of_list ps) >> skip)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, eapply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, eapply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h, _) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [] [], if n_eqs > 0 then do (eqs, eq', _) ← elim_gen_prod (n_eqs - 1) h [] [], (eqs ++ [eq']).mmap' subst else skip, eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs), iterate assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, eapply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework open lean.parser open interactive @[user_command] meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do { decl ← inductive_decl.parse meta_info, add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros), decl.decls.mmap' $ λ d, do { get_env >>= λ env, set_env $ env.add_namespace d.name, meta_info.attrs.apply d.name, d.attrs.apply d.name, some doc_string ← pure meta_info.doc_string | skip, add_doc_string d.name doc_string } } /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules -/ meta def coinduction (rule : expr) (ns : list name) : tactic unit := focus1 $ do ctxts' ← intros, ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binding_info <$> infer_type v), mvars ← apply_core rule {approx := ff, new_goals := new_goals.all}, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v.2 ≠ g), tgt ← target, (is, ty) ← open_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m.2)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars) <|> do { x ← mk_psigma (eqs.map prod.fst), y ← mk_psigma (eqs.map prod.snd), t ← infer_type x, mk_mapp `eq [t,x,y] }, rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, iterate' (econstructor >> skip)), -- clean up remaining coinduction steps all_goals' (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h, ns) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [] ns, (match eqs with | [] := clear h | (e::eqs) := do (hs, h, ns) ← elim_gen_prod eqs.length h [] ns, (h::(hs.reverse) : list _).mfoldl (λ (hs : list name) (h : expr), do [(_,hs',σ)] ← cases_core h hs, clear (h.instantiate_locals σ), pure $ hs.drop hs'.length) ns, skip end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (ns : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule ns, skip end interactive end tactic
b00b7b7d870fe80c82be046d14411f891a2b1759
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/choose/central.lean
fa021b79d8682eb9a09a6ec7d3142aad4d539bca
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,166
lean
/- Copyright (c) 2021 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens, Thomas Browning -/ import data.nat.choose.basic import data.nat.choose.sum /-! # Central binomial coefficients This file proves properties of the central binomial coefficients (that is, `nat.choose (2 * n) n`). ## Main definition and results * `nat.central_binom`: the central binomial coefficient, `(2 * n).choose n`. * `nat.succ_mul_central_binom_succ`: the inductive relationship between successive central binomial coefficients. * `nat.four_pow_lt_mul_central_binom`: an exponential lower bound on the central binomial coefficient. -/ namespace nat /-- The central binomial coefficient, `nat.choose (2 * n) n`. -/ def central_binom (n : ℕ) := (2 * n).choose n lemma central_binom_eq_two_mul_choose (n : ℕ) : central_binom n = (2 * n).choose n := rfl lemma central_binom_pos (n : ℕ) : 0 < central_binom n := choose_pos (nat.le_mul_of_pos_left zero_lt_two) lemma central_binom_ne_zero (n : ℕ) : central_binom n ≠ 0 := (central_binom_pos n).ne' @[simp] lemma central_binom_zero : central_binom 0 = 1 := choose_zero_right _ /-- The central binomial coefficient is the largest binomial coefficient. -/ lemma choose_le_central_binom (r n : ℕ) : choose (2 * n) r ≤ central_binom n := calc (2 * n).choose r ≤ (2 * n).choose (2 * n / 2) : choose_le_middle r (2 * n) ... = (2 * n).choose n : by rw nat.mul_div_cancel_left n zero_lt_two lemma two_le_central_binom (n : ℕ) (n_pos : 0 < n) : 2 ≤ central_binom n := calc 2 ≤ 2 * n : le_mul_of_pos_right n_pos ... = (2 * n).choose 1 : (choose_one_right (2 * n)).symm ... ≤ central_binom n : choose_le_central_binom 1 n /-- An inductive property of the central binomial coefficient. -/ lemma succ_mul_central_binom_succ (n : ℕ) : (n + 1) * central_binom (n + 1) = 2 * (2 * n + 1) * central_binom n := calc (n + 1) * (2 * (n + 1)).choose (n + 1) = (2 * n + 2).choose (n + 1) * (n + 1) : mul_comm _ _ ... = (2 * n + 1).choose n * (2 * n + 2) : by rw [choose_succ_right_eq, choose_mul_succ_eq] ... = 2 * ((2 * n + 1).choose n * (n + 1)) : by ring ... = 2 * ((2 * n + 1).choose n * ((2 * n + 1) - n)) : by rw [two_mul n, add_assoc, nat.add_sub_cancel_left] ... = 2 * ((2 * n).choose n * (2 * n + 1)) : by rw choose_mul_succ_eq ... = (2 * (2 * n + 1)) * (2 * n).choose n : by rw [mul_assoc, mul_comm (2 * n + 1)] /-- An exponential lower bound on the central binomial coefficient. This bound is of interest because it appears in [Tochiori's refinement of Erdős's proof of Bertrand's postulate](https://en.wikipedia.org/w/index.php?title=Proof_of_Bertrand%27s_postulate&oldid=859165151#Proof_by_Shigenori_Tochiori). -/ lemma four_pow_lt_mul_central_binom (n : ℕ) (n_big : 4 ≤ n) : 4 ^ n < n * central_binom n := begin induction n using nat.strong_induction_on with n IH, rcases lt_trichotomy n 4 with (hn|rfl|hn), { clear IH, dec_trivial! }, { norm_num [central_binom, choose] }, obtain ⟨n, rfl⟩ : ∃ m, n = m + 1 := nat.exists_eq_succ_of_ne_zero (zero_lt_four.trans hn).ne', calc 4 ^ (n + 1) < 4 * (n * central_binom n) : (mul_lt_mul_left zero_lt_four).mpr (IH n n.lt_succ_self (nat.le_of_lt_succ hn)) ... ≤ 2 * (2 * n + 1) * central_binom n : by { rw ← mul_assoc, linarith } ... = (n + 1) * central_binom (n + 1) : (succ_mul_central_binom_succ n).symm, end /-- An exponential lower bound on the central binomial coefficient. This bound is weaker than `four_pow_n_lt_n_mul_central_binom`, but it is of historical interest because it appears in Erdős's proof of Bertrand's postulate. -/ lemma four_pow_le_two_mul_self_mul_central_binom : ∀ (n : ℕ) (n_pos : 0 < n), 4 ^ n ≤ (2 * n) * central_binom n | 0 pr := (nat.not_lt_zero _ pr).elim | 1 pr := by norm_num [central_binom, choose] | 2 pr := by norm_num [central_binom, choose] | 3 pr := by norm_num [central_binom, choose] | n@(m + 4) _ := calc 4 ^ n ≤ n * central_binom n : (four_pow_lt_mul_central_binom _ le_add_self).le ... ≤ 2 * n * central_binom n : by { rw [mul_assoc], refine le_mul_of_pos_left zero_lt_two } end nat
f3e9443dd466d1c8f2dd05cabaa2fcae4246c75d
82e44445c70db0f03e30d7be725775f122d72f3e
/src/linear_algebra/dfinsupp.lean
48ce2a24b7d2da2f3432b9a1a86a6796814a5390
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
9,873
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import data.finsupp.to_dfinsupp import linear_algebra.basis /-! # Properties of the module `Π₀ i, M i` Given an indexed collection of `R`-modules `M i`, the `R`-module structure on `Π₀ i, M i` is defined in `data.dfinsupp`. In this file we define `linear_map` versions of various maps: * `dfinsupp.lsingle a : M →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lmk s : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lapply i : (Π₀ i, M i) →ₗ[R] M`: the map `λ f, f i` as a linear map; * `dfinsupp.lsum`: `dfinsupp.sum` or `dfinsupp.lift_add_hom` as a `linear_map`; ## Implementation notes This file should try to mirror `linear_algebra.finsupp` where possible. The API of `finsupp` is much more developed, but many lemmas in that file should be eligible to copy over. ## Tags function with finite support, module, linear algebra -/ variables {ι : Type*} {R : Type*} {S : Type*} {M : ι → Type*} {N : Type*} variables [dec_ι : decidable_eq ι] variables [semiring R] [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] variables [add_comm_monoid N] [module R N] namespace dfinsupp include dec_ι /-- `dfinsupp.mk` as a `linear_map`. -/ def lmk (s : finset ι) : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i := { to_fun := mk s, map_add' := λ _ _, mk_add, map_smul' := λ c x, mk_smul R x } /-- `dfinsupp.single` as a `linear_map` -/ def lsingle (i) : M i →ₗ[R] Π₀ i, M i := { to_fun := single i, map_smul' := λ r x, single_smul _, .. dfinsupp.single_add_hom _ _ } /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄ (h : ∀ i x, φ (single i x) = ψ (single i x)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. See note [partially-applied ext lemmas]. After apply this lemma, if `M = R` then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄ (h : ∀ i, φ.comp (lsingle i) = ψ.comp (lsingle i)) : φ = ψ := lhom_ext $ λ i, linear_map.congr_fun (h i) omit dec_ι /-- Interpret `λ (f : Π₀ i, M i), f i` as a linear map. -/ def lapply (i : ι) : (Π₀ i, M i) →ₗ[R] M i := { to_fun := λ f, f i, map_add' := λ f g, add_apply f g i, map_smul' := λ c f, smul_apply c f i} include dec_ι @[simp] lemma lmk_apply (s : finset ι) (x) : (lmk s : _ →ₗ[R] Π₀ i, M i) x = mk s x := rfl @[simp] lemma lsingle_apply (i : ι) (x : M i) : (lsingle i : _ →ₗ[R] _) x = single i x := rfl omit dec_ι @[simp] lemma lapply_apply (i : ι) (f : Π₀ i, M i) : (lapply i : _ →ₗ[R] _) f = f i := rfl section lsum /-- Typeclass inference can't find `dfinsupp.add_comm_monoid` without help for this case. This instance allows it to be found where it is needed on the LHS of the colon in `dfinsupp.module_of_linear_map`. -/ instance add_comm_monoid_of_linear_map : add_comm_monoid (Π₀ (i : ι), M i →ₗ[R] N) := @dfinsupp.add_comm_monoid _ (λ i, M i →ₗ[R] N) _ /-- Typeclass inference can't find `dfinsupp.module` without help for this case. This is needed to define `dfinsupp.lsum` below. The cause seems to be an inability to unify the `Π i, add_comm_monoid (M i →ₗ[R] N)` instance that we have with the `Π i, has_zero (M i →ₗ[R] N)` instance which appears as a parameter to the `dfinsupp` type. -/ instance module_of_linear_map [semiring S] [module S N] [smul_comm_class R S N] : module S (Π₀ (i : ι), M i →ₗ[R] N) := @dfinsupp.module _ (λ i, M i →ₗ[R] N) _ _ _ _ variables (S) include dec_ι /-- The `dfinsupp` version of `finsupp.lsum`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def lsum [semiring S] [module S N] [smul_comm_class R S N] : (Π i, M i →ₗ[R] N) ≃ₗ[S] ((Π₀ i, M i) →ₗ[R] N) := { to_fun := λ F, { to_fun := sum_add_hom (λ i, (F i).to_add_monoid_hom), map_add' := (lift_add_hom (λ i, (F i).to_add_monoid_hom)).map_add, map_smul' := λ c f, by { apply dfinsupp.induction f, { rw [smul_zero, add_monoid_hom.map_zero, smul_zero] }, { intros a b f ha hb hf, rw [smul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, smul_add, hf, ←single_smul, sum_add_hom_single, sum_add_hom_single, linear_map.to_add_monoid_hom_coe, linear_map.map_smul], } } }, inv_fun := λ F i, F.comp (lsingle i), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp }, map_smul' := λ c F, by { ext, simp } } end lsum /-! ### Bundled versions of `dfinsupp.map_range` The names should match the equivalent bundled `finsupp.map_range` definitions. -/ section map_range variables {β β₁ β₂: ι → Type*} variables [Π i, add_comm_monoid (β i)] [Π i, add_comm_monoid (β₁ i)] [Π i, add_comm_monoid (β₂ i)] variables [Π i, module R (β i)] [Π i, module R (β₁ i)] [Π i, module R (β₂ i)] lemma map_range_smul (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (r : R) (hf' : ∀ i x, f i (r • x) = r • f i x) (g : Π₀ i, β₁ i): map_range f hf (r • g) = r • map_range f hf g := begin ext, simp only [map_range_apply f, coe_smul, pi.smul_apply, hf'] end /-- `dfinsupp.map_range` as an `linear_map`. -/ @[simps apply] def map_range.linear_map (f : Π i, β₁ i →ₗ[R] β₂ i) : (Π₀ i, β₁ i) →ₗ[R] (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, f i x) (λ i, (f i).map_zero), map_smul' := λ r, map_range_smul _ _ _ (λ i, (f i).map_smul r), .. map_range.add_monoid_hom (λ i, (f i).to_add_monoid_hom) } @[simp] lemma map_range.linear_map_id : map_range.linear_map (λ i, (linear_map.id : (β₂ i) →ₗ[R] _)) = linear_map.id := linear_map.ext map_range_id lemma map_range.linear_map_comp (f : Π i, β₁ i →ₗ[R] β₂ i) (f₂ : Π i, β i →ₗ[R] β₁ i): map_range.linear_map (λ i, (f i).comp (f₂ i)) = (map_range.linear_map f).comp (map_range.linear_map f₂) := linear_map.ext $ map_range_comp (λ i x, f i x) (λ i x, f₂ i x) _ _ _ /-- `dfinsupp.map_range.linear_map` as an `linear_equiv`. -/ @[simps apply] def map_range.linear_equiv (e : Π i, β₁ i ≃ₗ[R] β₂ i) : (Π₀ i, β₁ i) ≃ₗ[R] (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, e i x) (λ i, (e i).map_zero), inv_fun := map_range (λ i x, (e i).symm x) (λ i, (e i).symm.map_zero), .. map_range.add_equiv (λ i, (e i).to_add_equiv), .. map_range.linear_map (λ i, (e i).to_linear_map) } @[simp] lemma map_range.linear_equiv_refl : (map_range.linear_equiv $ λ i, linear_equiv.refl R (β₁ i)) = linear_equiv.refl _ _ := linear_equiv.ext map_range_id lemma map_range.linear_equiv_trans (f : Π i, β i ≃ₗ[R] β₁ i) (f₂ : Π i, β₁ i ≃ₗ[R] β₂ i): map_range.linear_equiv (λ i, (f i).trans (f₂ i)) = (map_range.linear_equiv f).trans (map_range.linear_equiv f₂) := linear_equiv.ext $ map_range_comp (λ i x, f₂ i x) (λ i x, f i x) _ _ _ @[simp] lemma map_range.linear_equiv_symm (e : Π i, β₁ i ≃ₗ[R] β₂ i) : (map_range.linear_equiv e).symm = map_range.linear_equiv (λ i, (e i).symm) := rfl end map_range section basis /-- The direct sum of free modules is free. Note that while this is stated for `dfinsupp` not `direct_sum`, the types are defeq. -/ noncomputable def basis {η : ι → Type*} (b : Π i, basis (η i) R (M i)) : basis (Σ i, η i) R (Π₀ i, M i) := basis.of_repr ((map_range.linear_equiv (λ i, (b i).repr)).trans (sigma_finsupp_lequiv_dfinsupp R).symm) end basis end dfinsupp include dec_ι namespace submodule lemma dfinsupp_sum_mem {β : ι → Type*} [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] (S : submodule R N) (f : Π₀ i, β i) (g : Π i, β i → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.sum g ∈ S := S.to_add_submonoid.dfinsupp_sum_mem f g h lemma dfinsupp_sum_add_hom_mem {β : ι → Type*} [Π i, add_zero_class (β i)] (S : submodule R N) (f : Π₀ i, β i) (g : Π i, β i →+ N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : dfinsupp.sum_add_hom g f ∈ S := S.to_add_submonoid.dfinsupp_sum_add_hom_mem f g h /-- The supremum of a family of submodules is equal to the range of `dfinsupp.lsum`; that is every element in the `supr` can be produced from taking a finite number of non-zero elements of `p i`, coercing them to `N`, and summing them. -/ lemma supr_eq_range_dfinsupp_lsum (p : ι → submodule R N) : supr p = (dfinsupp.lsum ℕ (λ i, (p i).subtype)).range := begin apply le_antisymm, { apply supr_le _, intros i y hy, exact ⟨dfinsupp.single i ⟨y, hy⟩, dfinsupp.sum_add_hom_single _ _ _⟩, }, { rintros x ⟨v, rfl⟩, exact dfinsupp_sum_add_hom_mem _ v _ (λ i _, (le_supr p i : p i ≤ _) (v i).prop) } end lemma mem_supr_iff_exists_dfinsupp (p : ι → submodule R N) (x : N) : x ∈ supr p ↔ ∃ f : Π₀ i, p i, dfinsupp.lsum ℕ (λ i, (p i).subtype) f = x := set_like.ext_iff.mp (supr_eq_range_dfinsupp_lsum p) x /-- A variant of `submodule.mem_supr_iff_exists_dfinsupp` with the RHS fully unfolded. -/ lemma mem_supr_iff_exists_dfinsupp' (p : ι → submodule R N) [Π i (x : p i), decidable (x ≠ 0)] (x : N) : x ∈ supr p ↔ ∃ f : Π₀ i, p i, f.sum (λ i xi, ↑xi) = x := begin rw mem_supr_iff_exists_dfinsupp, simp_rw [dfinsupp.lsum_apply_apply, dfinsupp.sum_add_hom_apply], congr', end end submodule
d4ca72d3a0f5e4b762fcde030ab757f45d60e335
ccb7cdf8ebc2d015a000e8e7904952a36b910425
/src/sep_refinement.lean
56c4549569ef1d744e03c22c792e722afc89e59c
[]
no_license
cipher1024/lean-pl
f7258bda55606b75e3e39deaf7ce8928ed177d66
829680605ac17e91038d793c0188e9614353ca25
refs/heads/master
1,592,558,951,987
1,565,043,356,000
1,565,043,531,000
196,661,367
1
0
null
null
null
null
UTF-8
Lean
false
false
5,411
lean
import prop program import data.finmap import category_theory.category import tactic.interactive import tactic.tauto import tactic.linarith import tactic.monotonicity namespace refinement open category_theory open separation separation.hProp memory variables value : Type -- local notation `heap` := heap value -- local notation `hProp` := hProp value def state := Σ t : Type*, t → hProp value section value variables {value} def state.mk {s} (p : s → hProp value) : state value := ⟨s,p⟩ structure inst (x : state value) := (σ : x.fst) (h : heap value) (shape : x.snd σ h) end value def hom (x y : state value) := inst x → set (inst y) instance : category (state value) := { hom := hom value, id := λ _, pure, comp := λ x y z A₀ A₁, A₀ >=> A₁, id_comp' := λ x y f, fish_pipe _, comp_id' := λ x y f, fish_pure _, assoc' := λ x y z w f g h, fish_assoc _ _ _ } universes u variables {value} {s s' α : Type u} def sat (p : s → hProp value) (m : ST value s α) (q : α → s → hProp value) : Prop := ∀ σ σ' h h' x, (x,σ',h') ∈ m.run (σ,h) → p σ h → q x σ' h' variables {p : s → hProp value} {m : ST value s punit} {q : s → hProp value} variables {p' : s' → hProp value} {m' : ST value s' punit} {q' : s' → hProp value} open function (const) notation `♯` := by repeat { ext : 1; try {refl} } def attach (x : set α) : set { a // a ∈ x } := { a | a.1 ∈ x } def arrow (hm : sat p m (const _ q)) : state.mk p ⟶ state.mk q := show inst (state.mk p) → set (inst (state.mk q)), from λ ⟨σ,h,hp⟩, do ⟨⟨x₀,x₁,x₂⟩,hx⟩ ← attach (m.run (σ,h)), return (inst.mk x₁ x₂ (hm σ _ h _ x₀ hx hp)) def abs {s s' : Type*} (R : s → s' → Prop) {p : s → hProp value} {p' : s' → hProp value} : state.mk p ⟶ state.mk p' := show inst (state.mk p) → set (inst (state.mk p')), from λ ⟨σ,h,hp⟩ ⟨σ',h',hp'⟩, R σ σ' def repr {s s' : Type*} (R : s → s' → Prop) {p : s → hProp value} {p' : s' → hProp value} : state.mk p' ⟶ state.mk p := show inst (state.mk p') → set (inst (state.mk p)), from λ ⟨σ,h,hp⟩ ⟨σ',h',hp'⟩, R σ' σ def ref {X Y : state value} (a b : X ⟶ Y) : Prop := ∀ i, a i ⊆ b i notation `⦃` p `⦄` := inst (state.mk p) def rel (m : ST value s punit) (x : ⦃p⦄) (y : ⦃q⦄) : Prop := (punit.star,y.1,y.2) ∈ m.run (x.1,x.2) infix ` ⊑ `:50 := ref -- #exit -- lemma sound (R : s → s' → Prop) (hc : sat p m (const _ q)) (ha : sat p' m' (const _ q')) -- (hh : arrow hc ≫ abs R ⊑ abs R ≫ arrow ha) : -- ∀ (c : ⦃p⦄) (c' : ⦃q⦄) (a : ⦃p'⦄), -- R c.1 a.1 → rel m c c' → -- ∃ a' : ⦃q'⦄, rel m' a a' ∧ R c'.1 a'.1 := -- begin -- introv hR hm, -- let ha' := m'.run (a.1,a.2), -- let a' : ⦃q'⦄ := ⟨ha'.2.1,ha'.2.2,ha _ _ _ _ _ ♯ a.shape⟩, -- existsi [a'], split, repeat {ext : 1; try { refl <|> apply punit_eq }}, -- specialize @hh c a', cases c, simp [(≫),(>=>),arrow,return,abs] at hh, -- specialize @hh a', -- end lemma sound' (R : s → s' → Prop) (hc : sat p m (const _ q)) (ha : sat p' m' (const _ q')) (hh : repr R ≫ arrow hc ⊑ arrow ha ≫ repr R) : ∀ (c : ⦃p⦄) (c' : ⦃q⦄) (a : ⦃p'⦄), R c.1 a.1 → rel m c c' → ∃ a' : ⦃q'⦄, rel m' a a' ∧ R c'.1 a'.1 := begin introv hR hm, let a' : set ⦃q'⦄ := arrow ha a, specialize @hh a c' ⟨_,_,hm⟩, casesm* ⦃ _ ⦄, -- squeeze_simp [arrow,(≫),(>=>),(>>=),attach,repr] at hh, simp only [category_struct.comp, fish, arrow, return, set.bUnion_singleton, and_imp, attach, exists_prop, set.mem_Union, set.bind_def, set.pure_def, exists_imp_distrib] at hh, revert hh, apply exists_imp_exists, rintros ⟨a,b,c⟩, simp only [repr, true_and, and_imp, subtype.val_prop, bex_imp_distrib, subtype.exists, set.mem_set_of_eq, exists_imp_distrib, prod.exists, rel, arrow, return, pure, set.mem_singleton_iff ], introv h₀ h₁ h₂ h₃, subst x_1, subst x_2, cases x, exact ⟨h₀,h₃⟩, simp [set.mem_singleton_iff], existsi c, cases c, apply set.ext, intro, simp only [arrow, set.Union, exists_prop, set.mem_Union, set.bind_def, subtype.exists, prod.exists], split, { rintro ⟨h₀,⟨⟨⟩,b,c,h₁,h₂,h₃⟩⟩, simp only [return, set.mem_singleton_iff, and_self, set.pure_def] at h₃, subst x, exact h₂, }, { intro h, cases a, existsi [hR,punit.star,_,_,h,h], cases x, simp only [return, set.mem_singleton_iff, and_self, set.pure_def, eq_self_iff_true], }, end open state_t -- instance {α} : has_coe (option α) (ST value s α) := _ /- * framing * assignment * alloc * dealloc * sequencing * loop -/ -- def spec_alloc (s) (free : set ptr) (p : hProp value) (m : ST value s α) (q : α → hProp value) : Prop := -- ∀ σ σ' h h' frame x, (x,σ',h') ∈ m.run (σ,h) → (∀ p ∈ free, ¬ p ∈ h) → holds h frame p → holds h' frame (q x) -- lemma And_frame {α} {p : hProp value} {m : ST value s α} {q : α → hProp value} -- (h : ) : -- spec s p m q := _ -- lemma p_exists_one_point {α} {p : α → hProp value} (x : α) -- (h : ∀ y, p y =*> [| x = y |] ⊛ True) : -- p_exists p = p x := -- begin -- ext; dsimp [p_exists]; split, -- { rintros ⟨x',HH⟩, specialize h _ _ HH, admit }, -- apply @Exists.intro _ (λ x, p x h_1), -- end end refinement
3c9eecba10c079bf0aaf197be5f910b4896e017b
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/analysis/calculus/parametric_integral.lean
2b616b1322eaaa9a0ce45f4b3d7ff085421c7bcc
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
14,720
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import measure_theory.set_integral import analysis.calculus.mean_value /-! # Derivatives of integrals depending on parameters A parametric integral is a function with shape `f = λ x : H, ∫ a : α, F x a ∂μ` for some `F : H → α → E`, where `H` and `E` are normed spaces and `α` is a measured space with measure `μ`. We already know from `continuous_of_dominated` in `measure_theory.bochner_integral` how to guarantee that `f` is continuous using the dominated convergence theorem. In this file, we want to express the derivative of `f` as the integral of the derivative of `F` with respect to `x`. ## Main results As explained above, all results express the derivative of a parametric integral as the integral of a derivative. The variations come from the assumptions and from the different ways of expressing derivative, especially Fréchet derivatives vs elementary derivative of function of one real variable. * `has_fderiv_at_of_dominated_loc_of_lip`: this version assumes `F x` is ae-measurable for x near `x₀`, `F x₀` is integrable, `λ x, F x a` has derivative `F' a : H →L[ℝ] E` at `x₀` which is ae-measurable, `λ x, F x a` is locally Lipschitz near `x₀` for almost every `a`, with a Lipschitz bound which is integrable with respect to `a`. A subtle point is that the "near x₀" in the last condition has to be uniform in `a`. This is controlled by a positive number `ε`. * `has_fderiv_at_of_dominated_of_fderiv_le`: this version assume `λ x, F x a` has derivative `F' x a` for `x` near `x₀` and `F' x` is bounded by an integrable function independent from `x` near `x₀`. `has_deriv_at_of_dominated_loc_of_lip` and `has_deriv_at_of_dominated_loc_of_deriv_le ` are versions of the above two results that assume `H = ℝ` and use the high-school derivative `deriv` instead of Fréchet derivative `fderiv`. -/ noncomputable theory open topological_space measure_theory filter metric open_locale topological_space filter variables {α : Type*} [measurable_space α] {μ : measure α} {E : Type*} [normed_group E] [normed_space ℝ E] [complete_space E] [second_countable_topology E] [measurable_space E] [borel_space E] {H : Type*} [normed_group H] [normed_space ℝ H] [second_countable_topology $ H →L[ℝ] E] /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` with integrable Lipschitz bound (with a ball radius independent of `a`), and `F x` is ae-measurable for `x` in the same ball. See `has_fderiv_at_of_dominated_loc_of_lip` for a slightly more general version. -/ lemma has_fderiv_at_of_dominated_loc_of_lip' {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ x ∈ ball x₀ ε, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have nneg : ∀ x, 0 ≤ ∥x - x₀∥⁻¹ := λ x, inv_nonneg.mpr (norm_nonneg _) , set b : α → ℝ := λ a, abs (bound a), have b_int : integrable b μ := bound_integrable.norm, have b_nonneg : ∀ a, 0 ≤ b a := λ a, abs_nonneg _, have hF_int' : ∀ x ∈ ball x₀ ε, integrable (F x) μ, { intros x x_in, have : ∀ᵐ a ∂μ, ∥F x₀ a - F x a∥ ≤ ε * ∥(bound a : ℝ)∥, { apply h_lipsch.mono, intros a ha, rw lipschitz_on_with_iff_norm_sub_le at ha, apply (ha x₀ x₀_in x x_in).trans, rw [mul_comm, nnreal.coe_nnabs, real.norm_eq_abs], rw [mem_ball, dist_eq_norm, norm_sub_rev] at x_in, exact mul_le_mul_of_nonneg_right (le_of_lt x_in) (abs_nonneg _) }, exact integrable_of_norm_sub_le (hF_meas x x_in) hF_int (integrable.const_mul bound_integrable.norm ε) this }, have hF'_int : integrable F' μ, { have : ∀ᵐ a ∂μ, ∥F' a∥ ≤ b a, { apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_diff, ha_lip⟩, exact ha_diff.le_of_lip (ball_mem_nhds _ ε_pos) ha_lip }, exact b_int.mono' hF'_meas this }, refine ⟨hF'_int, _⟩, have h_ball: ball x₀ ε ∈ 𝓝 x₀ := ball_mem_nhds x₀ ε_pos, have : ∀ᶠ x in 𝓝 x₀, ∥x - x₀∥⁻¹ * ∥∫ a, F x a ∂μ - ∫ a, F x₀ a ∂μ - (∫ a, F' a ∂μ) (x - x₀)∥ = ∥∫ a, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀)) ∂μ∥, { apply mem_sets_of_superset (ball_mem_nhds _ ε_pos), intros x x_in, rw [set.mem_set_of_eq, ← norm_smul_of_nonneg (nneg _), integral_smul, integral_sub, integral_sub, ← continuous_linear_map.integral_apply hF'_int], exacts [hF_int' x x_in, hF_int, (hF_int' x x_in).sub hF_int, hF'_int.apply_continuous_linear_map _] }, rw [has_fderiv_at_iff_tendsto, tendsto_congr' this, ← tendsto_zero_iff_norm_tendsto_zero, ← show ∫ (a : α), ∥x₀ - x₀∥⁻¹ • (F x₀ a - F x₀ a - (F' a) (x₀ - x₀)) ∂μ = 0, by simp], apply tendsto_integral_filter_of_dominated_convergence, { apply is_countably_generated_nhds }, { filter_upwards [h_ball], intros x x_in, apply ae_measurable.const_smul, exact ((hF_meas _ x_in).sub (hF_meas _ x₀_in)).sub (hF'_meas.apply_continuous_linear_map _) }, { simp [measurable_const] }, { apply mem_sets_of_superset h_ball, intros x hx, apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_deriv, ha_bound⟩, show ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ ≤ b a + ∥F' a∥, replace ha_bound : ∥F x a - F x₀ a∥ ≤ b a * ∥x - x₀∥, { rw lipschitz_on_with_iff_norm_sub_le at ha_bound, exact ha_bound _ hx _ x₀_in }, calc ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ = ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a) - ∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : by rw smul_sub ... ≤ ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a)∥ + ∥∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : norm_sub_le _ _ ... = ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a∥ + ∥x - x₀∥⁻¹ * ∥F' a (x - x₀)∥ : by { rw [norm_smul_of_nonneg, norm_smul_of_nonneg] ; exact nneg _} ... ≤ ∥x - x₀∥⁻¹ * (b a * ∥x - x₀∥) + ∥x - x₀∥⁻¹ * (∥F' a∥ * ∥x - x₀∥) : add_le_add _ _ ... ≤ b a + ∥F' a∥ : _, exact mul_le_mul_of_nonneg_left ha_bound (nneg _), apply mul_le_mul_of_nonneg_left ((F' a).le_op_norm _) (nneg _), by_cases h : ∥x - x₀∥ = 0, { simpa [h] using add_nonneg (b_nonneg a) (norm_nonneg (F' a)) }, { field_simp [h] } }, { exact b_int.add hF'_int.norm }, { apply h_diff.mono, intros a ha, suffices : tendsto (λ x, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))) (𝓝 x₀) (𝓝 0), by simpa, rw tendsto_zero_iff_norm_tendsto_zero, have : (λ x, ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a - F' a (x - x₀)∥) = λ x, ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥, { ext x, rw norm_smul_of_nonneg (nneg _) }, rwa [has_fderiv_at_iff_tendsto, this] at ha }, end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_loc_of_lip {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lip : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin obtain ⟨ε', ε'_pos, h'⟩ : ∃ ε' > 0, ∀ x ∈ ball x₀ ε', ae_measurable (F x) μ, by simpa using nhds_basis_ball.eventually_iff.mp hF_meas, set δ := min ε ε', have δ_pos : 0 < δ := lt_min ε_pos ε'_pos, replace h' : ∀ x, x ∈ ball x₀ δ → ae_measurable (F x) μ, { intros x x_in, exact h' _ (ball_subset_ball (min_le_right ε ε') x_in) }, replace h_lip : ∀ᵐ (a : α) ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ δ), { apply h_lip.mono, intros a lip, exact lip.mono (ball_subset_ball $ min_le_left ε ε') }, apply has_fderiv_at_of_dominated_loc_of_lip' δ_pos ; assumption end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_of_fderiv_le {F : H → α → E} {F' : H → α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x a) (F' x a) x) : has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ x, F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, have bound_nonneg : 0 ≤ bound a := (norm_nonneg (F' x₀ a)).trans (ha_bound x₀ x₀_in), rw show real.nnabs (bound a) = nnreal.of_real (bound a), by simp [bound_nonneg], apply convex.lipschitz_on_with_of_norm_has_fderiv_within_le _ ha_bound (convex_ball _ _), intros x x_in, exact (ha_deriv x x_in).has_fderiv_within_at, }, exact (has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀).2 end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_lip {F : ℝ → α → E} {F' : α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) {bound : α → ℝ} (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' a) x₀) : (integrable F' μ) ∧ has_deriv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have hm := (continuous_linear_map.smul_rightL ℝ ℝ E 1).continuous.measurable.comp_ae_measurable hF'_meas, cases has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hm h_lipsch bound_integrable h_diff with hF'_int key, replace hF'_int : integrable F' μ, { rw [← integrable_norm_iff hm] at hF'_int, simpa only [integrable_norm_iff, hF'_meas, one_mul, continuous_linear_map.norm_id_field', continuous_linear_map.norm_smul_rightL_apply] using hF'_int}, refine ⟨hF'_int, _⟩, simp_rw has_deriv_at_iff_has_fderiv_at at h_diff ⊢, rwa continuous_linear_map.integral_comp_comm _ hF'_int at key, end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_deriv_le {F : ℝ → α → E} {F' : ℝ → α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) {bound : α → ℝ} (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x a) (F' x a) x) : (integrable (F' x₀) μ) ∧ has_deriv_at (λn, ∫ a, F n a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ (x : ℝ), F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, have bound_nonneg : 0 ≤ bound a := (norm_nonneg (F' x₀ a)).trans (ha_bound x₀ x₀_in), rw show real.nnabs (bound a) = nnreal.of_real (bound a), by simp [bound_nonneg], apply convex.lipschitz_on_with_of_norm_has_deriv_within_le (convex_ball _ _) (λ x x_in, (ha_deriv x x_in).has_deriv_within_at) ha_bound }, exact has_deriv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀ end
8ec64893b7ad0790d5ac5129b26751549def540b
7056dcccc8ffc1e6f9f533f3fed8ef16ff9fcc1e
/src/Init/Lean/Util/Trace.lean
79e4837011f846273171dc309527cf3d3e51049a
[ "Apache-2.0" ]
permissive
graydon/lean4
d73f60d0aa60e64e8d15674538bb5921aad5a4d1
ec9f4b579dc6b4a20407d2735f8ad91de29bfdb5
refs/heads/master
1,650,641,753,817
1,587,651,832,000
1,587,733,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,253
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ prelude import Init.Lean.Message universe u namespace Lean class MonadTracer (m : Type → Type u) := (traceCtx {α} : Name → m α → m α) (trace {} : Name → (Unit → MessageData) → m PUnit) (traceM {} : Name → m MessageData → m PUnit) class MonadTracerAdapter (m : Type → Type) := (isTracingEnabledFor {} : Name → m Bool) (addContext {} : MessageData → m MessageData) (enableTracing {} : Bool → m Bool) (getTraces {} : m (PersistentArray MessageData)) (modifyTraces {} : (PersistentArray MessageData → PersistentArray MessageData) → m Unit) private def checkTraceOptionAux (opts : Options) : Name → Bool | n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux p) | _ => false def checkTraceOption (opts : Options) (cls : Name) : Bool := if opts.isEmpty then false else checkTraceOptionAux opts (`trace ++ cls) namespace MonadTracerAdapter section variables {m : Type → Type} variables [Monad m] [MonadTracerAdapter m] variables {α : Type} private def addNode (oldTraces : PersistentArray MessageData) (cls : Name) : m Unit := modifyTraces $ fun traces => let d := MessageData.tagged cls (MessageData.node traces.toArray); oldTraces.push d private def getResetTraces : m (PersistentArray MessageData) := do oldTraces ← getTraces; modifyTraces $ fun _ => {}; pure oldTraces def addTrace (cls : Name) (msg : MessageData) : m Unit := do msg ← addContext msg; modifyTraces $ fun traces => traces.push (MessageData.tagged cls msg) @[inline] protected def trace (cls : Name) (msg : Unit → MessageData) : m Unit := whenM (isTracingEnabledFor cls) (addTrace cls (msg ())) @[inline] protected def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := whenM (isTracingEnabledFor cls) (do msg ← mkMsg; addTrace cls msg) @[inline] def traceCtx (cls : Name) (ctx : m α) : m α := do b ← isTracingEnabledFor cls; if !b then do old ← enableTracing false; a ← ctx; _ ← enableTracing old; pure a else do oldCurrTraces ← getResetTraces; a ← ctx; addNode oldCurrTraces cls; pure a end section variables {ε : Type} {m : Type → Type} variables [MonadExcept ε m] [Monad m] [MonadTracerAdapter m] variables {α : Type} /- Version of `traceCtx` with exception handling support. -/ @[inline] protected def traceCtxExcept (cls : Name) (ctx : m α) : m α := do b ← isTracingEnabledFor cls; if !b then do old ← enableTracing false; catch (do a ← ctx; _ ← enableTracing old; pure a) (fun e => do _ ← enableTracing old; throw e) else do oldCurrTraces ← getResetTraces; catch (do a ← ctx; addNode oldCurrTraces cls; pure a) (fun e => do addNode oldCurrTraces cls; throw e) end end MonadTracerAdapter instance monadTracerAdapter {m : Type → Type} [Monad m] [MonadTracerAdapter m] : MonadTracer m := { traceCtx := @MonadTracerAdapter.traceCtx _ _ _, trace := @MonadTracerAdapter.trace _ _ _, traceM := @MonadTracerAdapter.traceM _ _ _ } instance monadTracerAdapterExcept {ε : Type} {m : Type → Type} [Monad m] [MonadExcept ε m] [MonadTracerAdapter m] : MonadTracer m := { traceCtx := @MonadTracerAdapter.traceCtxExcept _ _ _ _ _, trace := @MonadTracerAdapter.trace _ _ _, traceM := @MonadTracerAdapter.traceM _ _ _ } structure TraceState := (enabled : Bool := true) (traces : PersistentArray MessageData := {}) namespace TraceState instance : Inhabited TraceState := ⟨{}⟩ private def toFormat (traces : PersistentArray MessageData) (sep : Format) : Format := traces.size.fold (fun i r => let curr := format $ traces.get! i; if i > 0 then r ++ sep ++ curr else r ++ curr) Format.nil instance : HasFormat TraceState := ⟨fun s => toFormat s.traces Format.line⟩ instance : HasToString TraceState := ⟨toString ∘ fmt⟩ end TraceState class SimpleMonadTracerAdapter (m : Type → Type) := (getOptions {} : m Options) (modifyTraceState {} : (TraceState → TraceState) → m Unit) (getTraceState {} : m TraceState) (addContext {} : MessageData → m MessageData) namespace SimpleMonadTracerAdapter variables {m : Type → Type} [Monad m] [SimpleMonadTracerAdapter m] private def checkTraceOptionM (cls : Name) : m Bool := do opts ← getOptions; pure $ checkTraceOption opts cls @[inline] def isTracingEnabledFor (cls : Name) : m Bool := do s ← getTraceState; if !s.enabled then pure false else checkTraceOptionM cls @[inline] def enableTracing (b : Bool) : m Bool := do s ← getTraceState; let oldEnabled := s.enabled; modifyTraceState $ fun s => { enabled := b, .. s }; pure oldEnabled @[inline] def getTraces : m (PersistentArray MessageData) := do s ← getTraceState; pure s.traces @[inline] def modifyTraces (f : PersistentArray MessageData → PersistentArray MessageData) : m Unit := modifyTraceState $ fun s => { traces := f s.traces, .. s } @[inline] def setTrace (f : PersistentArray MessageData → PersistentArray MessageData) : m Unit := modifyTraceState $ fun s => { traces := f s.traces, .. s } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState $ fun _ => s end SimpleMonadTracerAdapter instance simpleMonadTracerAdapter {m : Type → Type} [SimpleMonadTracerAdapter m] [Monad m] : MonadTracerAdapter m := { isTracingEnabledFor := @SimpleMonadTracerAdapter.isTracingEnabledFor _ _ _, enableTracing := @SimpleMonadTracerAdapter.enableTracing _ _ _, getTraces := @SimpleMonadTracerAdapter.getTraces _ _ _, addContext := @SimpleMonadTracerAdapter.addContext _ _, modifyTraces := @SimpleMonadTracerAdapter.modifyTraces _ _ _ } export MonadTracer (traceCtx trace traceM) /- Recipe for adding tracing support for a monad `M`. 1- Define the instance `SimpleMonadTracerAdapter M` by showing how to retrieve `Options` and get/modify `TraceState` object. 2- The `Options` control whether tracing commands are ignored or not. 3- The macro `trace! <cls> <msg>` adds the trace message `<msg>` if `<cls>` is activate and tracing is enabled. 4- We activate the tracing class `<cls>` by setting option `trace.<cls>` to true. If a prefix `p` of `trace.<cls>` is set to true, and there isn't a longer prefix `p'` set to false, then `<cls>` is also considered active. 5- `traceCtx <cls> <action>` groups all messages generated by `<action>` into a single `MessageData.node`. If `<cls> is not activate, then (all) tracing is disabled while executing `<action>`. This feature is useful for the following scenario: a) We have a tactic called `mysimp` which uses trace class `mysimp`. b) `mysimp invokes the unifier module which uses trace class `unify`. c) In the beginning of `mysimp`, we use `traceCtx`. In this scenario, by not enabling `mysimp` we also disable the `unify` trace messages produced by executing `mysimp`. -/ def registerTraceClass (traceClassName : Name) : IO Unit := registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" } end Lean
135bba141c2663b1b905d34c4f387e069bda15af
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/polish.lean
e4cc253a4a45e6f44e2fa2edae2a1355f1bc7229
[ "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
22,684
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.pi_nat import topology.metric_space.isometry import topology.metric_space.gluing import analysis.normed.field.basic /-! # Polish spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A topological space is Polish if its topology is second-countable and there exists a compatible complete metric. This is the class of spaces that is well-behaved with respect to measure theory. In this file, we establish the basic properties of Polish spaces. ## Main definitions and results * `polish_space α` is a mixin typeclass on a topological space, requiring that the topology is second-countable and compatible with a complete metric. To endow the space with such a metric, use in a proof `letI := upgrade_polish_space α`. We register an instance from complete second-countable metric spaces to Polish spaces, not the other way around. * We register that countable products and sums of Polish spaces are Polish. * `is_closed.polish_space`: a closed subset of a Polish space is Polish. * `is_open.polish_space`: an open subset of a Polish space is Polish. * `exists_nat_nat_continuous_surjective`: any nonempty Polish space is the continuous image of the fundamental Polish space `ℕ → ℕ`. A fundamental property of Polish spaces is that one can put finer topologies, still Polish, with additional properties: * `exists_polish_space_forall_le`: on a topological space, consider countably many topologies `t n`, all Polish and finer than the original topology. Then there exists another Polish topology which is finer than all the `t n`. * `is_clopenable s` is a property of a subset `s` of a topological space, requiring that there exists a finer topology, which is Polish, for which `s` becomes open and closed. We show that this property is satisfied for open sets, closed sets, for complements, and for countable unions. Once Borel-measurable sets are defined in later files, it will follow that any Borel-measurable set is clopenable. Once the Lusin-Souslin theorem is proved using analytic sets, we will even show that a set is clopenable if and only if it is Borel-measurable, see `is_clopenable_iff_measurable_set`. -/ noncomputable theory open_locale classical topology filter open topological_space set metric filter function variables {α : Type*} {β : Type*} /-! ### Basic properties of Polish spaces -/ /-- A Polish space is a topological space with second countable topology, that can be endowed with a metric for which it is complete. We register an instance from complete second countable metric space to polish space, and not the other way around as this is the most common use case. To endow a Polish space with a complete metric space structure, do `letI := upgrade_polish_space α`. -/ class polish_space (α : Type*) [h : topological_space α] : Prop := (second_countable [] : second_countable_topology α) (complete : ∃ m : metric_space α, m.to_uniform_space.to_topological_space = h ∧ @complete_space α m.to_uniform_space) /-- A convenience class, for a Polish space endowed with a complete metric. No instance of this class should be registered: It should be used as `letI := upgrade_polish_space α` to endow a Polish space with a complete metric. -/ class upgraded_polish_space (α : Type*) extends metric_space α, second_countable_topology α, complete_space α @[priority 100] instance polish_space_of_complete_second_countable [m : metric_space α] [h : second_countable_topology α] [h' : complete_space α] : polish_space α := { second_countable := h, complete := ⟨m, rfl, h'⟩ } /-- Construct on a Polish space a metric (compatible with the topology) which is complete. -/ def polish_space_metric (α : Type*) [ht : topological_space α] [h : polish_space α] : metric_space α := h.complete.some.replace_topology h.complete.some_spec.1.symm lemma complete_polish_space_metric (α : Type*) [ht : topological_space α] [h : polish_space α] : @complete_space α (polish_space_metric α).to_uniform_space := begin convert h.complete.some_spec.2, exact metric_space.replace_topology_eq _ _ end /-- This definition endows a Polish space with a complete metric. Use it as: `letI := upgrade_polish_space α`. -/ def upgrade_polish_space (α : Type*) [ht : topological_space α] [h : polish_space α] : upgraded_polish_space α := begin letI := polish_space_metric α, exact { .. complete_polish_space_metric α, .. polish_space.second_countable α } end namespace polish_space @[priority 100] instance t2_space (α : Type*) [topological_space α] [polish_space α] : t2_space α := by { letI := upgrade_polish_space α, apply_instance } /-- A countable product of Polish spaces is Polish. -/ instance pi_countable {ι : Type*} [countable ι] {E : ι → Type*} [∀ i, topological_space (E i)] [∀ i, polish_space (E i)] : polish_space (Π i, E i) := begin casesI nonempty_encodable ι, letI := λ i, upgrade_polish_space (E i), letI : metric_space (Π i, E i) := pi_countable.metric_space, apply_instance, end /-- Without this instance, `polish_space (ℕ → ℕ)` is not found by typeclass inference. -/ instance nat_fun [topological_space α] [polish_space α] : polish_space (ℕ → α) := by apply_instance /-- A countable disjoint union of Polish spaces is Polish. -/ instance sigma {ι : Type*} [countable ι] {E : ι → Type*} [∀ n, topological_space (E n)] [∀ n, polish_space (E n)] : polish_space (Σ n, E n) := begin letI := λ n, upgrade_polish_space (E n), letI : metric_space (Σ n, E n) := sigma.metric_space, haveI : complete_space (Σ n, E n) := sigma.complete_space, apply_instance end /-- The disjoint union of two Polish spaces is Polish. -/ instance sum [topological_space α] [polish_space α] [topological_space β] [polish_space β] : polish_space (α ⊕ β) := begin letI := upgrade_polish_space α, letI := upgrade_polish_space β, letI : metric_space (α ⊕ β) := metric_space_sum, apply_instance end /-- Any nonempty Polish space is the continuous image of the fundamental space `ℕ → ℕ`. -/ lemma exists_nat_nat_continuous_surjective (α : Type*) [topological_space α] [polish_space α] [nonempty α] : ∃ (f : (ℕ → ℕ) → α), continuous f ∧ surjective f := begin letI := upgrade_polish_space α, exact exists_nat_nat_continuous_surjective_of_complete_space α end /-- Given a closed embedding into a Polish space, the source space is also Polish. -/ lemma _root_.closed_embedding.polish_space [topological_space α] [topological_space β] [polish_space β] {f : α → β} (hf : closed_embedding f) : polish_space α := begin letI := upgrade_polish_space β, letI : metric_space α := hf.to_embedding.comap_metric_space f, haveI : second_countable_topology α := hf.to_embedding.second_countable_topology, haveI : complete_space α, { rw complete_space_iff_is_complete_range hf.to_embedding.to_isometry.uniform_inducing, apply is_closed.is_complete, exact hf.closed_range }, apply_instance end /-- Pulling back a Polish topology under an equiv gives again a Polish topology. -/ lemma _root_.equiv.polish_space_induced [t : topological_space β] [polish_space β] (f : α ≃ β) : @polish_space α (t.induced f) := begin letI : topological_space α := t.induced f, exact (f.to_homeomorph_of_inducing ⟨rfl⟩).closed_embedding.polish_space, end /-- A closed subset of a Polish space is also Polish. -/ lemma _root_.is_closed.polish_space {α : Type*} [topological_space α] [polish_space α] {s : set α} (hs : is_closed s) : polish_space s := (is_closed.closed_embedding_subtype_coe hs).polish_space /-- A sequence of type synonyms of a given type `α`, useful in the proof of `exists_polish_space_forall_le` to endow each copy with a different topology. -/ @[nolint unused_arguments has_nonempty_instance] def aux_copy (α : Type*) {ι : Type*} (i : ι) : Type* := α /-- Given a Polish space, and countably many finer Polish topologies, there exists another Polish topology which is finer than all of them. -/ lemma exists_polish_space_forall_le {ι : Type*} [countable ι] [t : topological_space α] [p : polish_space α] (m : ι → topological_space α) (hm : ∀ n, m n ≤ t) (h'm : ∀ n, @polish_space α (m n)) : ∃ (t' : topological_space α), (∀ n, t' ≤ m n) ∧ (t' ≤ t) ∧ @polish_space α t' := begin rcases is_empty_or_nonempty ι with hι|hι, { exact ⟨t, λ i, (is_empty.elim hι i : _), le_rfl, p⟩ }, unfreezingI { inhabit ι }, /- Consider the product of infinitely many copies of `α`, each endowed with the topology `m n`. This is a Polish space, as a product of Polish spaces. Pulling back this topology under the diagonal embedding of `α`, one gets a Polish topology which is finer than all the `m n`. -/ letI : ∀ (n : ι), topological_space (aux_copy α n) := λ n, m n, haveI : ∀ (n : ι), polish_space (aux_copy α n) := λ n, h'm n, letI T : topological_space (Π (n : ι), aux_copy α n) := by apply_instance, let f : α → Π (n : ι), aux_copy α n := λ x n, x, -- show that the induced topology is finer than all the `m n`. have T_le_m : ∀ n, T.induced f ≤ m n, { assume n s hs, refine ⟨set.pi ({n} : set ι) (λ i, s), _, _⟩, { apply is_open_set_pi (finite_singleton _), assume a ha, rw mem_singleton_iff.1 ha, exact hs }, { ext x, simp only [singleton_pi, mem_preimage] } }, refine ⟨T.induced f, λ n, T_le_m n, (T_le_m default).trans (hm default), _⟩, -- show that the new topology is Polish, as the pullback of a Polish topology under a closed -- embedding. have A : range f = ⋂ n, {x | x n = x default}, { ext x, split, { rintros ⟨y, rfl⟩, exact mem_Inter.2 (λ n, by simp only [mem_set_of_eq]) }, { assume hx, refine ⟨x default, _⟩, ext1 n, symmetry, exact (mem_Inter.1 hx n : _) } }, have f_closed : is_closed (range f), { rw A, apply is_closed_Inter (λ n, _), have C : ∀ (i : ι), continuous (λ (x : Π n, aux_copy α n), (id (x i) : α)), { assume i, apply continuous.comp _ (continuous_apply i), apply continuous_def.2 (λ s hs, _), exact hm i s hs }, apply is_closed_eq (C n) (C default) }, have K : @_root_.embedding _ _ (T.induced f) T f, { apply function.injective.embedding_induced, assume x y hxy, have : f x default = f y default, by rw hxy, exact this }, have L : @closed_embedding _ _ (T.induced f) T f, { split, { exact K }, { exact f_closed } }, exact @closed_embedding.polish_space _ _ (T.induced f) T (by apply_instance) _ L end /-! ### An open subset of a Polish space is Polish To prove this fact, one needs to construct another metric, giving rise to the same topology, for which the open subset is complete. This is not obvious, as for instance `(0,1) ⊆ ℝ` is not complete for the usual metric of `ℝ`: one should build a new metric that blows up close to the boundary. -/ section complete_copy variables [metric_space α] {s : set α} /-- A type synonym for a subset `s` of a metric space, on which we will construct another metric for which it will be complete. -/ @[nolint has_nonempty_instance] def complete_copy {α : Type*} (s : set α) : Type* := s /-- A distance on a subset `s` of a metric space, designed to make it complete if `s` is open. It is given by `dist' x y = dist x y + |1 / dist x sᶜ - 1 / dist y sᶜ|`, where the second term blows up close to the boundary to ensure that Cauchy sequences for `dist'` remain well inside `s`. -/ def has_dist_complete_copy (s : set α) : has_dist (complete_copy s) := ⟨λ x y, dist x.1 y.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ)⟩ local attribute [instance] has_dist_complete_copy lemma dist_complete_copy_eq (x y : complete_copy s) : dist x y = dist x.1 y.1 + abs (1/inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ) := rfl lemma dist_le_dist_complete_copy (x y : complete_copy s) : dist x.1 y.1 ≤ dist x y := (le_add_iff_nonneg_right _).2 (abs_nonneg _) /-- A metric space structure on a subset `s` of a metric space, designed to make it complete if `s` is open. It is given by `dist' x y = dist x y + |1 / dist x sᶜ - 1 / dist y sᶜ|`, where the second term blows up close to the boundary to ensure that Cauchy sequences for `dist'` remain well inside `s`. -/ def complete_copy_metric_space (s : set α) : metric_space (complete_copy s) := { dist_self := λ x, by simp [dist_complete_copy_eq], dist_comm := λ x y, by simp [dist_complete_copy_eq, dist_comm, abs_sub_comm], dist_triangle := λ x y z, calc dist x z = dist x.1 z.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist z.1 sᶜ) : rfl ... ≤ (dist x.1 y.1 + dist y.1 z.1) + (abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ) + abs (1 / inf_dist y.1 sᶜ - 1 / inf_dist z.1 sᶜ)) : begin rw [← real.dist_eq, ← real.dist_eq, ← real.dist_eq], exact add_le_add (dist_triangle _ _ _) (dist_triangle _ _ _) end ... = dist x y + dist y z : by { rw [dist_complete_copy_eq, dist_complete_copy_eq], abel }, eq_of_dist_eq_zero := begin assume x y hxy, apply subtype.coe_injective, refine dist_le_zero.1 _, rw ← hxy, exact dist_le_dist_complete_copy x y end } local attribute [instance] complete_copy_metric_space /-- The identity between the type synonym `complete_copy s` (with its modified metric) and the original subtype `s` is a homeomorphism. -/ def complete_copy_id_homeo (hs : is_open s) (h's : sᶜ.nonempty) : complete_copy s ≃ₜ s := { to_fun := id, inv_fun := id, left_inv := λ x, rfl, right_inv := λ x, rfl, continuous_to_fun := begin have : lipschitz_with 1 (λ (x : complete_copy s), (id x : s)), { apply lipschitz_with.mk_one, exact dist_le_dist_complete_copy }, exact this.continuous, end, continuous_inv_fun := begin apply continuous_iff_continuous_at.2 (λ x, _), suffices H : tendsto (λ (b : s), dist b.1 x.1 + |1 / inf_dist b.1 sᶜ - 1 / inf_dist x.1 sᶜ|) (𝓝 x) (𝓝 (dist x.1 x.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist x.1 sᶜ))), { rw [continuous_at, tendsto_iff_dist_tendsto_zero], simpa only [sub_self, abs_zero, add_zero, dist_self] using H }, have I : 0 < inf_dist x.val sᶜ, { rw ← hs.is_closed_compl.not_mem_iff_inf_dist_pos h's, simp }, apply tendsto.add, { apply continuous.tendsto, exact continuous_subtype_coe.dist continuous_const }, { refine (tendsto.sub_const _ _).abs, refine tendsto.div tendsto_const_nhds _ I.ne', exact ((continuous_inf_dist_pt _).comp continuous_subtype_coe).tendsto _ } end } lemma complete_space_complete_copy [complete_space α] (hs : is_open s) (h's : sᶜ.nonempty) : complete_space (complete_copy s) := begin refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) (by simp) _, assume u hu, have A : cauchy_seq (λ n, (u n).1), { apply cauchy_seq_of_le_tendsto_0 (λ (n : ℕ), (1/2)^n) (λ n m N hNn hNm, _) _, { exact (dist_le_dist_complete_copy (u n) (u m)).trans (hu N n m hNn hNm).le }, { exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) } }, obtain ⟨x, xlim⟩ : ∃ x, tendsto (λ n, (u n).1) at_top (𝓝 x), { haveI : nonempty α := ⟨(u 0).1⟩, exact ⟨_, A.tendsto_lim⟩ }, suffices xs : x ∈ s, { refine ⟨⟨x, xs⟩, _⟩, have L : tendsto (λ n, (id ⟨(u n).1, (u n).2⟩ : s)) at_top (𝓝 (⟨x, xs⟩)), { apply embedding_subtype_coe.tendsto_nhds_iff.2, exact xlim }, convert ((complete_copy_id_homeo hs h's).symm.continuous.tendsto _).comp L, ext1 n, simp [complete_copy_id_homeo] }, obtain ⟨C, hC⟩ : ∃ C, ∀ n, 1 / inf_dist (u n).1 sᶜ < C, { refine ⟨(1/2)^0 + dist (1 / inf_dist (u 0).1 sᶜ) 0, λ n, _⟩, calc 1 / inf_dist (u n).val sᶜ ≤ dist (1 / inf_dist (u n).val sᶜ) 0 : by { rw real.dist_0_eq_abs, exact le_abs_self _ } ... ≤ dist (1 / inf_dist (u n).1 sᶜ) (1 / inf_dist (u 0).1 sᶜ) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : dist_triangle _ _ _ ... ≤ (dist (u n).1 (u 0).1 + dist (1 / inf_dist (u n).1 sᶜ) (1 / inf_dist (u 0).1 sᶜ)) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : add_le_add (le_add_of_nonneg_left dist_nonneg) le_rfl ... = dist (u n) (u 0) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : rfl ... < (1/2)^0 + dist (1 / inf_dist (u 0).1 sᶜ) 0 : add_lt_add_right (hu 0 n 0 (zero_le _) le_rfl) _ }, have Cpos : 0 < C, { apply lt_of_le_of_lt _ (hC 0), simp [inf_dist_nonneg] }, have I : ∀ n, 1/C ≤ inf_dist (u n).1 sᶜ, { assume n, have : 0 < inf_dist (u n).val sᶜ, { apply (hs.is_closed_compl.not_mem_iff_inf_dist_pos h's).1, simp }, rw div_le_iff' Cpos, exact (div_le_iff this).1 (hC n).le }, have I' : 1/C ≤ inf_dist x sᶜ, { have : tendsto (λ n, inf_dist (u n).1 sᶜ) at_top (𝓝 (inf_dist x sᶜ)) := ((continuous_inf_dist_pt sᶜ).tendsto x).comp xlim, exact ge_of_tendsto' this I }, suffices : x ∉ sᶜ, by simpa, apply (hs.is_closed_compl.not_mem_iff_inf_dist_pos h's).2 (lt_of_lt_of_le _ I'), simp [Cpos], end /-- An open subset of a Polish space is also Polish. -/ lemma _root_.is_open.polish_space {α : Type*} [topological_space α] [polish_space α] {s : set α} (hs : is_open s) : polish_space s := begin rcases eq_empty_or_nonempty sᶜ with h's|h's, { simp at h's, apply is_closed.polish_space, rw h's, exact is_closed_univ }, { letI := upgrade_polish_space α, haveI : complete_space (complete_copy s) := complete_space_complete_copy hs h's, haveI : second_countable_topology (complete_copy s) := (complete_copy_id_homeo hs h's).embedding.second_countable_topology, exact (complete_copy_id_homeo hs h's).symm.closed_embedding.polish_space } end end complete_copy /-! ### Clopenable sets in Polish spaces -/ /-- A set in a topological space is clopenable if there exists a finer Polish topology for which this set is open and closed. It turns out that this notion is equivalent to being Borel-measurable, but this is nontrivial (see `is_clopenable_iff_measurable_set`). -/ def is_clopenable [t : topological_space α] (s : set α) : Prop := ∃ (t' : topological_space α), t' ≤ t ∧ @polish_space α t' ∧ is_closed[t'] s ∧ is_open[t'] s /-- Given a closed set `s` in a Polish space, one can construct a finer Polish topology for which `s` is both open and closed. -/ lemma _root_.is_closed.is_clopenable [topological_space α] [polish_space α] {s : set α} (hs : is_closed s) : is_clopenable s := begin /- Both sets `s` and `sᶜ` admit a Polish topology. So does their disjoint union `s ⊕ sᶜ`. Pulling back this topology by the canonical bijection with `α` gives the desired Polish topology in which `s` is both open and closed. -/ haveI : polish_space s := hs.polish_space, let t : set α := sᶜ, haveI : polish_space t := hs.is_open_compl.polish_space, let f : α ≃ (s ⊕ t) := (equiv.set.sum_compl s).symm, letI T : topological_space (s ⊕ t) := by apply_instance, let t' : topological_space α := T.induced f, let g := @equiv.to_homeomorph_of_inducing _ _ t' T f { induced := rfl }, have A : g ⁻¹' (range (sum.inl : s → s ⊕ t)) = s, { ext x, by_cases h : x ∈ s, { simp only [equiv.set.sum_compl_symm_apply_of_mem, h, mem_preimage, equiv.to_fun_as_coe, mem_range_self, equiv.to_homeomorph_of_inducing_apply]}, { simp only [equiv.set.sum_compl_symm_apply_of_not_mem, h, not_false_iff, mem_preimage, equiv.to_homeomorph_of_inducing_apply, equiv.to_fun_as_coe, mem_range, exists_false]} }, refine ⟨t', _, f.polish_space_induced, _, _⟩, { assume u hu, change ∃ (s' : set (↥s ⊕ ↥t)), T.is_open s' ∧ f ⁻¹' s' = u, refine ⟨f.symm ⁻¹' u, _, by simp only [equiv.symm_symm, equiv.symm_preimage_preimage]⟩, refine is_open_sum_iff.2 ⟨_, _⟩, { have : is_open ((coe : s → α) ⁻¹' u) := is_open.preimage continuous_subtype_coe hu, have : sum.inl ⁻¹' (⇑(f.symm) ⁻¹' u) = (coe : s → α) ⁻¹' u, by { ext x, simp only [equiv.symm_symm, mem_preimage, equiv.set.sum_compl_apply_inl] }, rwa this }, { have : is_open ((coe : t → α) ⁻¹' u) := is_open.preimage continuous_subtype_coe hu, have : sum.inr ⁻¹' (⇑(f.symm) ⁻¹' u) = (coe : t → α) ⁻¹' u, by { ext x, simp only [equiv.symm_symm, mem_preimage, equiv.set.sum_compl_apply_inr] }, rwa this } }, { have : is_closed[t'] (g ⁻¹' (range (sum.inl : s → s ⊕ t))), { apply is_closed.preimage, { exact @homeomorph.continuous _ _ t' _ g }, { exact is_closed_range_inl } }, convert this, exact A.symm }, { have : is_open[t'] (g ⁻¹' (range (sum.inl : s → s ⊕ t))), { apply is_open.preimage, { exact @homeomorph.continuous _ _ t' _ g }, { exact is_open_range_inl } }, convert this, exact A.symm }, end lemma is_clopenable.compl [topological_space α] {s : set α} (hs : is_clopenable s) : is_clopenable sᶜ := begin rcases hs with ⟨t, t_le, t_polish, h, h'⟩, exact ⟨t, t_le, t_polish, @is_open.is_closed_compl α t s h', @is_closed.is_open_compl α t s h⟩, end lemma _root_.is_open.is_clopenable [topological_space α] [polish_space α] {s : set α} (hs : is_open s) : is_clopenable s := by simpa using hs.is_closed_compl.is_clopenable.compl lemma is_clopenable.Union [t : topological_space α] [polish_space α] {s : ℕ → set α} (hs : ∀ n, is_clopenable (s n)) : is_clopenable (⋃ n, s n) := begin choose m mt m_polish m_closed m_open using hs, obtain ⟨t', t'm, -, t'_polish⟩ : ∃ (t' : topological_space α), (∀ (n : ℕ), t' ≤ m n) ∧ (t' ≤ t) ∧ @polish_space α t' := exists_polish_space_forall_le m mt m_polish, have A : is_open[t'] (⋃ n, s n), { apply is_open_Union, assume n, apply t'm n, exact m_open n }, obtain ⟨t'', t''_le, t''_polish, h1, h2⟩ : ∃ (t'' : topological_space α), t'' ≤ t' ∧ @polish_space α t'' ∧ is_closed[t''] (⋃ n, s n) ∧ is_open[t''] (⋃ n, s n) := @is_open.is_clopenable α t' t'_polish _ A, exact ⟨t'', t''_le.trans ((t'm 0).trans (mt 0)), t''_polish, h1, h2⟩, end end polish_space
deff1b1696eb2d571140a3f807e4c4c95cdef2c9
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Meta/Tactic/Simp/Main.lean
d25ba97dde5266e914cdb67ee21f3244af1b918c
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,612
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Simp.Types import Lean.Meta.Tactic.Simp.Rewrite namespace Lean.Meta namespace Simp def Result.getProof (r : Result) : MetaM Expr := do match r.proof? with | some p => return p | none => mkEqRefl r.expr private def mkEqTrans (r₁ r₂ : Result) : MetaM Result := do match r₁.proof? with | none => return r₂ | some p₁ => match r₂.proof? with | none => return { r₂ with proof? := r₁.proof? } | some p₂ => return { r₂ with proof? := (← Meta.mkEqTrans p₁ p₂) } private def mkCongrFun (r : Result) (a : Expr) : MetaM Result := match r.proof? with | none => return { expr := mkApp r.expr a, proof? := none } | some h => return { expr := mkApp r.expr a, proof? := (← Meta.mkCongrFun h a) } private def mkCongr (r₁ r₂ : Result) : MetaM Result := let e := mkApp r₁.expr r₂.expr match r₁.proof?, r₂.proof? with | none, none => return { expr := e, proof? := none } | some h, none => return { expr := e, proof? := (← Meta.mkCongrFun h r₂.expr) } | none, some h => return { expr := e, proof? := (← Meta.mkCongrArg r₁.expr h) } | some h₁, some h₂ => return { expr := e, proof? := (← Meta.mkCongr h₁ h₂) } private def mkImpCongr (r₁ r₂ : Result) : MetaM Result := do let e ← mkArrow r₁.expr r₂.expr match r₁.proof?, r₂.proof? with | none, none => return { expr := e, proof? := none } | _, _ => return { expr := e, proof? := (← Meta.mkImpCongr (← r₁.getProof) (← r₂.getProof)) } -- TODO specialize if bootleneck private def reduceProj (e : Expr) : MetaM Expr := do match (← reduceProj? e) with | some e => return e | _ => return e private def reduceProjFn? (e : Expr) : MetaM (Option Expr) := do matchConst e.getAppFn (fun _ => pure none) fun cinfo _ => do if !(← isProjectionFn cinfo.name) then return none else match (← unfoldDefinition? e) with | none => pure none | some e => match (← reduceProj? e.getAppFn) with | some f => return some (mkAppN f e.getAppArgs) | none => return none private def reduceFVar (cfg : Config) (e : Expr) : MetaM Expr := do if cfg.zeta then match (← getFVarLocalDecl e).value? with | some v => return v | none => return e else return e private partial def reduce (cfg : Config) (e : Expr) : MetaM Expr := withIncRecDepth do if cfg.beta then let e' := e.headBeta if e' != e then return (← reduce cfg e') -- TODO: eta reduction if cfg.proj then match (← reduceProjFn? e) with | some e => return (← reduce cfg e) | none => pure () if cfg.iota then match (← reduceRecMatcher? e) with | some e => return (← reduce cfg e) | none => pure () return e private partial def dsimp (e : Expr) : M Expr := do return e -- TODO partial def simp (e : Expr) : M Result := withIncRecDepth do let cfg ← getConfig if cfg.memoize then if let some result := (← get).cache.find? e then return result simpLoop { expr := e } where simpLoop (r : Result) : M Result := do let cfg ← getConfig if (← get).numSteps > cfg.maxSteps then throwError! "simp failed, maximum number of steps exceeded" else let init := r.expr modify fun s => { s with numSteps := s.numSteps + 1 } match (← pre r.expr) with | Step.done r => cacheResult cfg r | Step.visit r' => let r ← mkEqTrans r r' let r ← mkEqTrans r (← simpStep r.expr) match (← post r.expr) with | Step.done r' => cacheResult cfg (← mkEqTrans r r') | Step.visit r' => let r ← mkEqTrans r r' if cfg.singlePass || init == r.expr then cacheResult cfg r else simpLoop r simpStep (e : Expr) : M Result := do match e with | Expr.mdata _ e _ => simp e | Expr.proj .. => pure { expr := (← reduceProj e) } | Expr.app .. => simpApp e | Expr.lam .. => simpLambda e | Expr.forallE .. => simpForall e | Expr.letE .. => simpLet e | Expr.const .. => pure { expr := e } | Expr.bvar .. => unreachable! | Expr.sort .. => pure { expr := e } | Expr.lit .. => pure { expr := e } | Expr.mvar .. => pure { expr := (← instantiateMVars e) } | Expr.fvar .. => pure { expr := (← reduceFVar (← getConfig) e) } simpApp (e : Expr) : M Result := do let e ← reduce (← getConfig) e if !e.isApp then simp e else withParent e <| e.withApp fun f args => do let infos := (← getFunInfoNArgs f args.size).paramInfo let mut r ← simp f let mut i := 0 for arg in args do trace[Meta.Tactic.simp]! "app [{i}] {infos.size} {arg} hasFwdDeps: {infos[i].hasFwdDeps}" if i < infos.size && !infos[i].hasFwdDeps then r ← mkCongr r (← simp arg) else r ← mkCongrFun r (← dsimp arg) i := i + 1 return r withNewLemmas (xs : Array Expr) (f : M Result) : M Result := do if (← getConfig).contextual then let mut s ← getSimpLemmas let mut updated := false for x in xs do if (← isProof x) then s ← s.add x updated := true if updated then withSimpLemmas s f else f else f simpLambda (e : Expr) : M Result := withParent e $ lambdaTelescope e fun xs e => withNewLemmas xs do let r ← simp e let eNew ← mkLambdaFVars xs r.expr match r.proof? with | none => return { expr := eNew } | some h => let p ← xs.foldrM (init := h) fun x h => do mkFunExt (← mkLambdaFVars #[x] h) return { expr := eNew, proof? := p } simpArrow (e : Expr) : M Result := do trace[Meta.Tactic.simp]! "arrow {e}" let p := e.bindingDomain! let q := e.bindingBody! let rp ← simp p trace[Meta.Tactic.simp]! "arrow [{(← getConfig).contextual}] {p} [{← isProp p}] -> {q} [{← isProp q}]" if (← (← getConfig).contextual <&&> isProp p <&&> isProp q) then trace[Meta.Tactic.simp]! "ctx arrow {rp.expr} -> {q}" withLocalDeclD e.bindingName! rp.expr fun h => do let s ← getSimpLemmas let s ← s.add h withSimpLemmas s do let rq ← simp q match rq.proof? with | none => mkImpCongr rp rq | some hq => let hq ← mkLambdaFVars #[h] hq return { expr := (← mkArrow rp.expr rq.expr), proof? := (← mkImpCongrCtx (← rp.getProof) hq) } else mkImpCongr rp (← simp q) simpForall (e : Expr) : M Result := withParent e do trace[Meta.Tactic.simp]! "forall {e}" if e.isArrow then simpArrow e else if (← isProp e) then withLocalDecl e.bindingName! e.bindingInfo! e.bindingDomain! fun x => withNewLemmas #[x] do let b := e.bindingBody!.instantiate1 x let rb ← simp b let eNew ← mkForallFVars #[x] rb.expr match rb.proof? with | none => return { expr := eNew } | some h => return { expr := eNew, proof? := (← mkForallCongr (← mkLambdaFVars #[x] h)) } else return { expr := (← dsimp e) } simpLet (e : Expr) : M Result := do if (← getConfig).zeta then match e with | Expr.letE _ _ v b _ => return { expr := b.instantiate1 v } | _ => unreachable! else -- TODO: simplify nondependent let-decls return { expr := (← dsimp e) } cacheResult (cfg : Config) (r : Result) : M Result := do if cfg.memoize then modify fun s => { s with cache := s.cache.insert e r } return r def main (e : Expr) (config : Config := {}) (methods : Methods := {}) (simpLemmas : SimpLemmas := {}) : MetaM Result := do withReducible do simp e methods { config := config, simpLemmas := simpLemmas } |>.run' {} end Simp def simp (e : Expr) (config : Simp.Config := {}) (simpLemmas : SimpLemmas := {}) : MetaM Simp.Result := do let discharge? (e : Expr) : SimpM (Option Expr) := return none -- TODO: use simp, and add config option let pre := (Simp.preDefault · discharge?) let post := (Simp.postDefault · discharge?) Simp.main e (config := config) (methods := { pre := pre, post := post, discharge? := discharge? }) (simpLemmas := simpLemmas) end Lean.Meta
35039782e40609b7774b82d66e354fd875d28af8
ed544fdbb470075305eb2a01b0491ce8a6ba05c8
/src/certigrad/id.lean
8cf2ca122d50efed33685243b43e93eea1be65be
[ "Apache-2.0" ]
permissive
gazimahmud/certigrad
d12caa30c6fc3adf9bb1fcd61479af0faad8b6c3
38cc6377dbd5025eb074188a1acd02147a92bdba
refs/heads/master
1,606,977,759,336
1,498,686,571,000
1,498,686,571,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,594
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Identifiers. -/ import .util .label namespace certigrad inductive ID : Type | str : label → ID | nat : ℕ → ID namespace ID instance : decidable_eq ID := by tactic.mk_dec_eq_instance instance : inhabited ID := ⟨ID.str label.default⟩ private def add : ID → ID → ID | (ID.nat n₁) (ID.nat n₂) := ID.nat (n₁ + n₂) | _ _ := default ID def to_str : ID → string | (str l) := to_string l | (nat n) := "#" ++ to_string n instance : has_to_string ID := ⟨to_str⟩ def less_than : ID → ID → Prop | (nat n) (str s) := true | (str s) (nat n) := false | (nat n₁) (nat n₂) := n₁ < n₂ | (str s₁) (str s₂) := s₁ < s₂ instance : has_lt ID := ⟨less_than⟩ instance decidable_less_than : Π (x y : ID), decidable (x < y) | (nat n) (str s) := decidable.true | (str s) (nat n) := decidable.false | (nat n₁) (nat n₂) := show decidable (n₁ < n₂), by apply_instance | (str s₁) (str s₂) := by apply label.decidable_less_than end ID section tactics open tactic meta def prove_ids_neq : tactic unit := do H ← intro `H, Hs ← injection H, match Hs with | [] := done | [H'] := contra_nats_eq H' <|> (do H''_ty ← mk_app `certigrad.label.label_eq_of_to_nat [H'], note `H'' none H''_ty, get_local `H'' >>= contra_nats_eq) | (x::y::xs) := fail "injection produced multiple hyps" end end tactics end certigrad
54ef9c3707992cc3149ddf25c567e8cbf8b26e80
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/match_tac.lean
e16ce6837ddd79f66e2bba3ecb4407ca304269b0
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
336
lean
import data.nat example (a b c : Prop) : a ∧ b ↔ b ∧ a := begin apply iff.intro, {intro H, match H with | and.intro H₁ H₂ := and.intro H₂ H₁ end}, {intro H, match H with | and.intro H₁ H₂ := and.intro H₂ H₁ end}, end open nat example : ∀ (a b : nat), a = b → b = a | a a rfl := rfl
2291c0f18ee7baf86ea50befe966d7ef8d5f1b26
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/tactic/squeeze.lean
d179d41d09a87d05df26b1798fcfb6daab1e85fd
[ "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
3,650
lean
import meta.rb_map import tactic.basic data.list.defs import category.traversable.basic import tactic.simpa open interactive interactive.types lean.parser meta def loc.to_string_aux : option name → string | none := "⊢" | (some x) := to_string x meta def loc.to_string : loc → string | (loc.ns []) := "" | (loc.ns [none]) := "" | (loc.ns ls) := string.join $ list.intersperse " " (" at" :: ls.map loc.to_string_aux) | loc.wildcard := " at *" namespace tactic namespace interactive meta def arg.to_tactic_format : simp_arg_type → tactic format | (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp | simp_arg_type.all_hyps := pure "*" | (simp_arg_type.except n) := pure format!"-{n}" open list meta def record_lit : lean.parser pexpr := do tk "{", ls ← sep_by (skip_info (tk ",")) ( sum.inl <$> (tk ".." *> texpr) <|> sum.inr <$> (prod.mk <$> ident <* tk ":=" <*> texpr)), tk "}", let (srcs,fields) := partition_map id ls, let (names,values) := unzip fields, pure $ pexpr.mk_structure_instance { field_names := names, field_values := values, sources := srcs } meta def rec.to_tactic_format (e : pexpr) : tactic format := do r ← e.get_structure_instance_info, fs ← mzip_with (λ n v, do v ← to_expr v >>= pp, pure $ format!"{n} := {v}" ) r.field_names r.field_values, let ss := r.sources.map (λ s, format!" .. {s}"), let x : format := format.join $ list.intersperse ", " (fs ++ ss), pure format!" {{{x}}" local postfix `?`:9001 := optional meta def parse_config : option pexpr → tactic (simp_config_ext × format) | none := pure ({}, "") | (some cfg) := do e ← to_expr ``(%%cfg : simp_config_ext), fmt ← has_to_tactic_format.to_tactic_format cfg, prod.mk <$> eval_expr simp_config_ext e <*> rec.to_tactic_format cfg meta def squeeze_simp (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : parse record_lit?) : tactic unit := do g ← main_goal, (cfg',c) ← parse_config cfg, hs' ← hs.mmap arg.to_tactic_format, simp use_iota_eqn no_dflt hs attr_names locat cfg', g ← instantiate_mvars g, let vs := g.list_constant, vs ← vs.mfilter (succeeds ∘ has_attribute `simp), let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", let attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), let loc := loc.to_string locat, let args := hs' ++ vs.to_list.map to_fmt, trace format!"simp{use_iota_eqn} only {args}{attrs}{loc}{c}" meta def squeeze_simpa (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : parse record_lit?) : tactic unit := do g ← main_goal, (cfg',c) ← parse_config cfg, tgt' ← traverse (λ t, do t ← to_expr t >>= pp, pure format!" using {t}") tgt, simpa use_iota_eqn no_dflt hs attr_names tgt cfg', g ← instantiate_mvars g, let vs := g.list_constant, vs ← vs.mfilter (succeeds ∘ has_attribute `simp), let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", let attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), let tgt' := tgt'.get_or_else "", hs ← hs.mmap arg.to_tactic_format, let args := hs ++ vs.to_list.map to_fmt, trace format!"simpa{use_iota_eqn} only {args}{attrs}{tgt'}{c}" end interactive end tactic
bd016370b558b97c710744ba453ce1d5959d3cad
d751a70f46ed26dc0111a87f5bbe83e5c6648904
/Code/src/inst/network/basic.lean
8b38539ae47cd39bfe4b4afa229df5db334fad21
[]
no_license
marcusrossel/bachelors-thesis
92cb12ae8436c10fbfab9bfe4929a0081e615b37
d1ec2c2b5c3c6700a506f2e3cc93f1160e44b422
refs/heads/main
1,682,873,547,703
1,619,795,735,000
1,619,795,735,000
306,041,494
2
0
null
null
null
null
UTF-8
Lean
false
false
3,469
lean
import inst.network.prec open reactor -- Cf. inst/primitives.lean variables (υ : Type*) [decidable_eq υ] -- An instantaneous reactor network is an instantaneous reactor network graph with the constraints -- of having unique input-port connections as well as being precedence-acyclic. @[ext] structure inst.network := (η : inst.network.graph υ) (unique_ins : η.has_unique_port_ins) (prec_acyclic : η.is_prec_acyclic) variables {υ} namespace inst namespace network -- Forwards the `edges` property from the network graph to the network. noncomputable def edges (σ : network υ) := σ.η.edges -- Forwards equivalence from the network graph to the network. instance equiv : has_equiv (network υ) := ⟨λ σ σ', σ.η ≈ σ'.η⟩ -- Network equivalence is reflexive. @[refl] lemma equiv_refl (σ : network υ) : σ ≈ σ := by refl -- Network equivalence is symmetric. @[symm] lemma equiv_symm {σ σ' : network υ} (h : σ ≈ σ') : σ' ≈ σ := by { simp only [(≈)] at h ⊢, simp [h] } -- Network equivalence is transitive. @[trans] lemma equiv_trans {σ₁ σ₂ σ₃ : network υ} (h₁₂ : σ₁ ≈ σ₂) (h₂₃ : σ₂ ≈ σ₃) : σ₁ ≈ σ₃ := by { simp [(≈)] at ⊢ h₁₂ h₂₃, simp [h₁₂, h₂₃] } -- Forwards the `update_port` function from the network graph to the network. noncomputable def update_port (σ : network υ) (r : ports.role) (p : port.id) (v : option υ) : network υ := { η := σ.η.update_port r p v, unique_ins := graph.eq_edges_unique_port_ins (refl _) σ.unique_ins, prec_acyclic := graph.equiv_prec_acyc_inv (graph.update_port_equiv _ _ _ _) σ.prec_acyclic } -- Forwards the equivalence of `update_port` from the network graph to the network. lemma update_port_equiv (σ : network υ) (r : ports.role) (p : port.id) (v : option υ) : σ.update_port r p v ≈ σ := by { unfold update_port, exact equiv_symm (graph.update_port_equiv _ _ _ _) } -- Forwards the `clear_all_ports` function from the network graph to the network. noncomputable def clear_all_ports (σ : inst.network υ) : inst.network υ := { η := σ.η.clear_all_ports, unique_ins := graph.eq_edges_unique_port_ins (symm (graph.clear_all_ports_equiv _).left) σ.unique_ins, prec_acyclic := graph.equiv_prec_acyc_inv (graph.equiv_symm (graph.clear_all_ports_equiv _)) σ.prec_acyclic } -- Forwards the equivalence of `clear_all_ports` from the network graph to the network. lemma clear_all_ports_equiv (σ : inst.network υ) : σ.clear_all_ports ≈ σ := by { unfold clear_all_ports, exact graph.clear_all_ports_equiv _ } -- Forwards the `copy_ports` function from the network graph to the network. noncomputable def copy_ports (σ σ' : inst.network υ) (ps : finset port.id) (r : ports.role) : inst.network υ := { η := σ.η.copy_ports σ'.η ps r, unique_ins := graph.eq_edges_unique_port_ins (symm (graph.copy_ports_equiv _ _ _ _).left) σ.unique_ins, prec_acyclic := graph.equiv_prec_acyc_inv (graph.equiv_symm (graph.copy_ports_equiv _ _ _ _)) σ.prec_acyclic } -- Forwards the equivalence of `copy_ports` from the network graph to the network. lemma copy_ports_equiv (σ σ' : inst.network υ) (ps : finset port.id) (r : ports.role) : σ.copy_ports σ' ps r ≈ σ := by { unfold copy_ports, exact graph.copy_ports_equiv _ _ _ _ } end network end inst
8b96328073ee30bb57e4672eca5e3f5f7ba3549f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/set_theory/surreal/basic.lean
eb65789c550f9445e1237ce2dd9f90988cffb875
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
14,337
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Scott Morrison -/ import set_theory.pgame /-! # Surreal numbers The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games. A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and all those options are themselves numeric. In terms of combinatorial games, the numeric games have "frozen"; you can only make your position worse by playing, and Left is some definite "number" of moves ahead (or behind) Right. A surreal number is an equivalence class of numeric pregames. In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else besides!) but we do not yet have a complete development. ## Order properties Surreal numbers inherit the relations `≤` and `<` from games, and these relations satisfy the axioms of a partial order (recall that `x < y ↔ x ≤ y ∧ ¬ y ≤ x` did not hold for games). ## Algebraic operations We show that the surreals form a linear ordered commutative group. One can also map all the ordinals into the surreals! ### Multiplication of surreal numbers The definition of multiplication for surreal numbers is surprisingly difficult and is currently missing in the library. A sample proof can be found in Theorem 3.8 in the second reference below. The difficulty lies in the length of the proof and the number of theorems that need to proven simultaneously. This will make for a fun and challenging project. ## References * [Conway, *On numbers and games*][conway2001] * [Schleicher, Stoll, *An introduction to Conway's games and numbers*][schleicher_stoll] -/ universes u local infix ` ≈ ` := pgame.equiv namespace pgame /-- A pre-game is numeric if everything in the L set is less than everything in the R set, and all the elements of L and R are also numeric. -/ def numeric : pgame → Prop | ⟨l, r, L, R⟩ := (∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ i, numeric (R i)) lemma numeric.move_left {x : pgame} (o : numeric x) (i : x.left_moves) : numeric (x.move_left i) := begin cases x with xl xr xL xR, exact o.2.1 i, end lemma numeric.move_right {x : pgame} (o : numeric x) (j : x.right_moves) : numeric (x.move_right j) := begin cases x with xl xr xL xR, exact o.2.2 j, end @[elab_as_eliminator] theorem numeric_rec {C : pgame → Prop} (H : ∀ l r (L : l → pgame) (R : r → pgame), (∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) → (∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) : ∀ x, numeric x → C x | ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ := H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i)) theorem lt_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y → ¬ y < x := begin refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy, refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _), rw [mk_lt_mk, mk_lt_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩), { exact IHxl _ _ (oyl _) (lt_of_le_mk h₁) (lt_of_le_mk h₂) }, { exact not_lt.2 (le_trans h₂ h₁) (hy _ _) }, { exact not_lt.2 (le_trans h₁ h₂) (hx _ _) }, { exact IHxr _ _ (oyr _) (lt_of_mk_le h₁) (lt_of_mk_le h₂) }, end theorem le_of_lt {x y : pgame} (ox : numeric x) (oy : numeric y) (h : x < y) : x ≤ y := not_lt.1 (lt_asymm ox oy h) /-- On numeric pre-games, `<` and `≤` satisfy the axioms of a partial order (even though they don't on all pre-games). -/ theorem lt_iff_le_not_le {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y ↔ x ≤ y ∧ ¬ y ≤ x := ⟨λ h, ⟨le_of_lt ox oy h, not_le.2 h⟩, λ h, not_le.1 h.2⟩ theorem numeric_zero : numeric 0 := ⟨by rintros ⟨⟩ ⟨⟩, ⟨by rintros ⟨⟩, by rintros ⟨⟩⟩⟩ theorem numeric_one : numeric 1 := ⟨by rintros ⟨⟩ ⟨⟩, ⟨λ x, numeric_zero, by rintros ⟨⟩⟩⟩ theorem numeric_neg : Π {x : pgame} (o : numeric x), numeric (-x) | ⟨l, r, L, R⟩ o := ⟨λ j i, lt_iff_neg_gt.1 (o.1 i j), ⟨λ j, numeric_neg (o.2.2 j), λ i, numeric_neg (o.2.1 i)⟩⟩ -- We provide this as an analogue for `numeric.move_left_le`, -- even though it does not need the `numeric` hypothesis. @[nolint unused_arguments] theorem numeric.move_left_lt {x : pgame.{u}} (o : numeric x) (i : x.left_moves) : x.move_left i < x := begin rw lt_def_le, left, use i, end theorem numeric.move_left_le {x : pgame} (o : numeric x) (i : x.left_moves) : x.move_left i ≤ x := le_of_lt (o.move_left i) o (o.move_left_lt i) -- We provide this as an analogue for `numeric.le_move_right`, -- even though it does not need the `numeric` hypothesis. @[nolint unused_arguments] theorem numeric.lt_move_right {x : pgame} (o : numeric x) (j : x.right_moves) : x < x.move_right j := begin rw lt_def_le, right, use j, end theorem numeric.le_move_right {x : pgame} (o : numeric x) (j : x.right_moves) : x ≤ x.move_right j := le_of_lt o (o.move_right j) (o.lt_move_right j) theorem add_lt_add {w x y z : pgame.{u}} (oy : numeric y) (oz : numeric z) (hwx : w < x) (hyz : y < z) : w + y < x + z := begin rw lt_def_le at *, rcases hwx with ⟨ix, hix⟩|⟨jw, hjw⟩; rcases hyz with ⟨iz, hiz⟩|⟨jy, hjy⟩, { left, use (left_moves_add x z).symm (sum.inl ix), simp only [add_move_left_inl], calc w + y ≤ move_left x ix + y : add_le_add_right hix ... ≤ move_left x ix + move_left z iz : add_le_add_left hiz ... ≤ move_left x ix + z : add_le_add_left (oz.move_left_le iz) }, { left, use (left_moves_add x z).symm (sum.inl ix), simp only [add_move_left_inl], calc w + y ≤ move_left x ix + y : add_le_add_right hix ... ≤ move_left x ix + move_right y jy : add_le_add_left (oy.le_move_right jy) ... ≤ move_left x ix + z : add_le_add_left hjy }, { right, use (right_moves_add w y).symm (sum.inl jw), simp only [add_move_right_inl], calc move_right w jw + y ≤ x + y : add_le_add_right hjw ... ≤ x + move_left z iz : add_le_add_left hiz ... ≤ x + z : add_le_add_left (oz.move_left_le iz), }, { right, use (right_moves_add w y).symm (sum.inl jw), simp only [add_move_right_inl], calc move_right w jw + y ≤ x + y : add_le_add_right hjw ... ≤ x + move_right y jy : add_le_add_left (oy.le_move_right jy) ... ≤ x + z : add_le_add_left hjy, }, end theorem numeric_add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy := ⟨begin rintros (ix|iy) (jx|jy), { show xL ix + ⟨yl, yr, yL, yR⟩ < xR jx + ⟨yl, yr, yL, yR⟩, exact add_lt_add_right (ox.1 ix jx), }, { show xL ix + ⟨yl, yr, yL, yR⟩ < ⟨xl, xr, xL, xR⟩ + yR jy, exact add_lt_add oy (oy.move_right jy) (ox.move_left_lt _) (oy.lt_move_right _), }, { -- show ⟨xl, xr, xL, xR⟩ + yL iy < xR jx + ⟨yl, yr, yL, yR⟩, -- fails? exact add_lt_add (oy.move_left iy) oy (ox.lt_move_right _) (oy.move_left_lt _), }, { -- show ⟨xl, xr, xL, xR⟩ + yL iy < ⟨xl, xr, xL, xR⟩ + yR jy, -- fails? exact @add_lt_add_left ⟨xl, xr, xL, xR⟩ _ _ (oy.1 iy jy), } end, begin split, { rintros (ix|iy), { apply numeric_add (ox.move_left ix) oy, }, { apply numeric_add ox (oy.move_left iy), }, }, { rintros (jx|jy), { apply numeric_add (ox.move_right jx) oy, }, { apply numeric_add ox (oy.move_right jy), }, }, end⟩ using_well_founded { dec_tac := pgame_wf_tac } /-- Pre-games defined by natural numbers are numeric. -/ theorem numeric_nat : Π (n : ℕ), numeric n | 0 := numeric_zero | (n + 1) := numeric_add (numeric_nat n) numeric_one /-- The pre-game omega is numeric. -/ theorem numeric_omega : numeric omega := ⟨by rintros ⟨⟩ ⟨⟩, λ i, numeric_nat i.down, by rintros ⟨⟩⟩ /-- The pre-game `half` is numeric. -/ theorem numeric_half : numeric half := begin split, { rintros ⟨ ⟩ ⟨ ⟩, exact zero_lt_one }, split; rintro ⟨ ⟩, { exact numeric_zero }, { exact numeric_one } end theorem half_add_half_equiv_one : half + half ≈ 1 := begin split; rw le_def; split, { rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩), { right, use (sum.inr punit.star), calc ((half + half).move_left (sum.inl punit.star)).move_right (sum.inr punit.star) = (half.move_left punit.star + half).move_right (sum.inr punit.star) : by fsplit ... = (0 + half).move_right (sum.inr punit.star) : by fsplit ... ≈ 1 : zero_add_equiv 1 ... ≤ 1 : pgame.le_refl 1 }, { right, use (sum.inl punit.star), calc ((half + half).move_left (sum.inr punit.star)).move_right (sum.inl punit.star) = (half + half.move_left punit.star).move_right (sum.inl punit.star) : by fsplit ... = (half + 0).move_right (sum.inl punit.star) : by fsplit ... ≈ 1 : add_zero_equiv 1 ... ≤ 1 : pgame.le_refl 1 } }, { rintro ⟨ ⟩ }, { rintro ⟨ ⟩, left, use (sum.inl punit.star), calc 0 ≤ half : le_of_lt numeric_zero numeric_half zero_lt_half ... ≈ 0 + half : (zero_add_equiv half).symm ... = (half + half).move_left (sum.inl punit.star) : by fsplit }, { rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩); left, { exact ⟨sum.inr punit.star, le_of_le_of_equiv (pgame.le_refl _) (add_zero_equiv _).symm⟩ }, { exact ⟨sum.inl punit.star, le_of_le_of_equiv (pgame.le_refl _) (zero_add_equiv _).symm⟩ } } end end pgame /-- The equivalence on numeric pre-games. -/ def surreal.equiv (x y : {x // pgame.numeric x}) : Prop := x.1.equiv y.1 instance surreal.setoid : setoid {x // pgame.numeric x} := ⟨λ x y, x.1.equiv y.1, λ x, pgame.equiv_refl _, λ x y, pgame.equiv_symm, λ x y z, pgame.equiv_trans⟩ /-- The type of surreal numbers. These are the numeric pre-games quotiented by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient, the order becomes a total order. -/ def surreal := quotient surreal.setoid namespace surreal open pgame /-- Construct a surreal number from a numeric pre-game. -/ def mk (x : pgame) (h : x.numeric) : surreal := quotient.mk ⟨x, h⟩ instance : has_zero surreal := { zero := ⟦⟨0, numeric_zero⟩⟧ } instance : has_one surreal := { one := ⟦⟨1, numeric_one⟩⟧ } instance : inhabited surreal := ⟨0⟩ /-- Lift an equivalence-respecting function on pre-games to surreals. -/ def lift {α} (f : ∀ x, numeric x → α) (H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α := quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2) /-- Lift a binary equivalence-respecting function on pre-games to surreals. -/ def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α) (H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂), x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α := lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂ h, H _ _ _ _ (equiv_refl _) h)) (λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h (equiv_refl _)) /-- The relation `x ≤ y` on surreals. -/ def le : surreal → surreal → Prop := lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy)) /-- The relation `x < y` on surreals. -/ def lt : surreal → surreal → Prop := lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy)) theorem not_le : ∀ {x y : surreal}, ¬ le x y ↔ lt y x := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact not_le /-- Addition on surreals is inherited from pre-game addition: the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add : surreal → surreal → surreal := surreal.lift₂ (λ (x y : pgame) (ox) (oy), ⟦⟨x + y, numeric_add ox oy⟩⟧) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quotient.sound (pgame.add_congr hx hy)) /-- Negation for surreal numbers is inherited from pre-game negation: the negation of `{L | R}` is `{-R | -L}`. -/ def neg : surreal → surreal := surreal.lift (λ x ox, ⟦⟨-x, pgame.numeric_neg ox⟩⟧) (λ _ _ _ _ a, quotient.sound (pgame.neg_congr a)) instance : has_le surreal := ⟨le⟩ instance : has_lt surreal := ⟨lt⟩ instance : has_add surreal := ⟨add⟩ instance : has_neg surreal := ⟨neg⟩ instance : ordered_add_comm_group surreal := { add := (+), add_assoc := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact quotient.sound add_assoc_equiv }, zero := 0, zero_add := by { rintros ⟨_⟩, exact quotient.sound (pgame.zero_add_equiv _) }, add_zero := by { rintros ⟨_⟩, exact quotient.sound (pgame.add_zero_equiv _) }, neg := has_neg.neg, add_left_neg := by { rintros ⟨_⟩, exact quotient.sound pgame.add_left_neg_equiv }, add_comm := by { rintros ⟨_⟩ ⟨_⟩, exact quotient.sound pgame.add_comm_equiv }, le := (≤), lt := (<), le_refl := by { rintros ⟨_⟩, refl }, le_trans := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact pgame.le_trans }, lt_iff_le_not_le := by { rintros ⟨_, ox⟩ ⟨_, oy⟩, exact pgame.lt_iff_le_not_le ox oy }, le_antisymm := by { rintros ⟨_⟩ ⟨_⟩ h₁ h₂, exact quotient.sound ⟨h₁, h₂⟩ }, add_le_add_left := by { rintros ⟨_⟩ ⟨_⟩ hx ⟨_⟩, exact pgame.add_le_add_left hx } } noncomputable instance : linear_ordered_add_comm_group surreal := { le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact or_iff_not_imp_left.2 (λ h, le_of_lt oy ox (pgame.not_le.1 h)), decidable_le := classical.dec_rel _, ..surreal.ordered_add_comm_group } -- We conclude with some ideas for further work on surreals; these would make fun projects. -- TODO define the inclusion of groups `surreal → game` -- TODO define the field structure on the surreals end surreal
e0ffa3abfbb6642ccc1e738fc712bd035beeac3a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/616c.hlean
cbb536dbfbe6e4d0147f21cc77d92f7bc8b51236
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
233
hlean
open eq definition my_elim {A P : Type} {R : A → A → Type} (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : quotient R) : P := begin induction x, exact (Pc a), refine (pathover_of_eq (Pp H)) end
3a4900531c9ada20ac7ada52364bd45506f0ce4e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/sheaves/presheaf.lean
d1ed99e8c6c50a5eb21935036beb8a585816e854
[]
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,424
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Mario Carneiro, Reid Barton -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.category.Top.opens import Mathlib.PostPort universes v u namespace Mathlib /-! # Presheaves on a topological space We define `presheaf C X` simply as `(opens X)ᵒᵖ ⥤ C`, and inherit the category structure with natural transformations as morphisms. We define * `pushforward_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C` with notation `f _* ℱ` and for `ℱ : X.presheaf C` provide the natural isomorphisms * `pushforward.id : (𝟙 X) _* ℱ ≅ ℱ`` * `pushforward.comp : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ)` along with their `@[simp]` lemmas. -/ namespace Top def presheaf (C : Type u) [category_theory.category C] (X : Top) := topological_space.opens ↥Xᵒᵖ ⥤ C namespace presheaf /-- Pushforward a presheaf on `X` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `Y`. -/ def pushforward_obj {C : Type u} [category_theory.category C] {X : Top} {Y : Top} (f : X ⟶ Y) (ℱ : presheaf C X) : presheaf C Y := category_theory.functor.op (topological_space.opens.map f) ⋙ ℱ infixl:80 " _* " => Mathlib.Top.presheaf.pushforward_obj @[simp] theorem pushforward_obj_obj {C : Type u} [category_theory.category C] {X : Top} {Y : Top} (f : X ⟶ Y) (ℱ : presheaf C X) (U : topological_space.opens ↥Yᵒᵖ) : category_theory.functor.obj (f _* ℱ) U = category_theory.functor.obj ℱ (category_theory.functor.obj (category_theory.functor.op (topological_space.opens.map f)) U) := rfl @[simp] theorem pushforward_obj_map {C : Type u} [category_theory.category C] {X : Top} {Y : Top} (f : X ⟶ Y) (ℱ : presheaf C X) {U : topological_space.opens ↥Yᵒᵖ} {V : topological_space.opens ↥Yᵒᵖ} (i : U ⟶ V) : category_theory.functor.map (f _* ℱ) i = category_theory.functor.map ℱ (category_theory.functor.map (category_theory.functor.op (topological_space.opens.map f)) i) := rfl def pushforward_eq {C : Type u} [category_theory.category C] {X : Top} {Y : Top} {f : X ⟶ Y} {g : X ⟶ Y} (h : f = g) (ℱ : presheaf C X) : f _* ℱ ≅ g _* ℱ := category_theory.iso_whisker_right (category_theory.nat_iso.op (category_theory.iso.symm (topological_space.opens.map_iso f g h))) ℱ @[simp] theorem pushforward_eq_hom_app {C : Type u} [category_theory.category C] {X : Top} {Y : Top} {f : X ⟶ Y} {g : X ⟶ Y} (h : f = g) (ℱ : presheaf C X) (U : topological_space.opens ↥Yᵒᵖ) : category_theory.nat_trans.app (category_theory.iso.hom (pushforward_eq h ℱ)) U = category_theory.functor.map ℱ (id (category_theory.has_hom.hom.op (category_theory.eq_to_hom (eq.mpr (id (Eq._oldrec (Eq.refl (category_theory.functor.obj (topological_space.opens.map g) (opposite.unop U) = category_theory.functor.obj (topological_space.opens.map f) (opposite.unop U))) h)) (Eq.refl (category_theory.functor.obj (topological_space.opens.map g) (opposite.unop U))))))) := rfl @[simp] theorem pushforward_eq_rfl {C : Type u} [category_theory.category C] {X : Top} {Y : Top} (f : X ⟶ Y) (ℱ : presheaf C X) (U : topological_space.opens ↥Y) : category_theory.nat_trans.app (category_theory.iso.hom (pushforward_eq rfl ℱ)) (opposite.op U) = 𝟙 := sorry theorem pushforward_eq_eq {C : Type u} [category_theory.category C] {X : Top} {Y : Top} {f : X ⟶ Y} {g : X ⟶ Y} (h₁ : f = g) (h₂ : f = g) (ℱ : presheaf C X) : pushforward_eq h₁ ℱ = pushforward_eq h₂ ℱ := rfl namespace pushforward def id {C : Type u} [category_theory.category C] {X : Top} (ℱ : presheaf C X) : 𝟙 _* ℱ ≅ ℱ := category_theory.iso_whisker_right (category_theory.nat_iso.op (category_theory.iso.symm (topological_space.opens.map_id X))) ℱ ≪≫ category_theory.functor.left_unitor ℱ @[simp] theorem id_hom_app' {C : Type u} [category_theory.category C] {X : Top} (ℱ : presheaf C X) (U : set ↥X) (p : is_open U) : category_theory.nat_trans.app (category_theory.iso.hom (id ℱ)) (opposite.op { val := U, property := p }) = category_theory.functor.map ℱ 𝟙 := sorry @[simp] theorem id_hom_app {C : Type u} [category_theory.category C] {X : Top} (ℱ : presheaf C X) (U : topological_space.opens ↥Xᵒᵖ) : category_theory.nat_trans.app (category_theory.iso.hom (id ℱ)) U = category_theory.functor.map ℱ (category_theory.eq_to_hom (topological_space.opens.op_map_id_obj U)) := sorry @[simp] theorem id_inv_app' {C : Type u} [category_theory.category C] {X : Top} (ℱ : presheaf C X) (U : set ↥X) (p : is_open U) : category_theory.nat_trans.app (category_theory.iso.inv (id ℱ)) (opposite.op { val := U, property := p }) = category_theory.functor.map ℱ 𝟙 := sorry def comp {C : Type u} [category_theory.category C] {X : Top} (ℱ : presheaf C X) {Y : Top} {Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ) := category_theory.iso_whisker_right (category_theory.nat_iso.op (category_theory.iso.symm (topological_space.opens.map_comp f g))) ℱ @[simp] theorem comp_hom_app {C : Type u} [category_theory.category C] {X : Top} (ℱ : presheaf C X) {Y : Top} {Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) (U : topological_space.opens ↥Zᵒᵖ) : category_theory.nat_trans.app (category_theory.iso.hom (comp ℱ f g)) U = 𝟙 := sorry @[simp] theorem comp_inv_app {C : Type u} [category_theory.category C] {X : Top} (ℱ : presheaf C X) {Y : Top} {Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) (U : topological_space.opens ↥Zᵒᵖ) : category_theory.nat_trans.app (category_theory.iso.inv (comp ℱ f g)) U = 𝟙 := sorry end pushforward /-- A morphism of presheaves gives rise to a morphisms of the pushforwards of those presheaves. -/ def pushforward_map {C : Type u} [category_theory.category C] {X : Top} {Y : Top} (f : X ⟶ Y) {ℱ : presheaf C X} {𝒢 : presheaf C X} (α : ℱ ⟶ 𝒢) : f _* ℱ ⟶ f _* 𝒢 := category_theory.nat_trans.mk fun (U : topological_space.opens ↥Yᵒᵖ) => category_theory.nat_trans.app α (category_theory.functor.obj (category_theory.functor.op (topological_space.opens.map f)) U)