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
6b1ecab3d462e4c28354c81c191bfdd1ebf005f6
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/geometry/manifold/times_cont_mdiff.lean
969f2b694c117518c121b673f33f6210eee8dbce
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
85,713
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 geometry.manifold.mfderiv import geometry.manifold.local_invariant_properties /-! # Smooth functions between smooth manifolds We define `Cⁿ` functions between smooth manifolds, as functions which are `Cⁿ` in charts, and prove basic properties of these notions. ## Main definitions and statements Let `M ` and `M'` be two smooth manifolds, with respect to model with corners `I` and `I'`. Let `f : M → M'`. * `times_cont_mdiff_within_at I I' n f s x` states that the function `f` is `Cⁿ` within the set `s` around the point `x`. * `times_cont_mdiff_at I I' n f x` states that the function `f` is `Cⁿ` around `x`. * `times_cont_mdiff_on I I' n f s` states that the function `f` is `Cⁿ` on the set `s` * `times_cont_mdiff I I' n f` states that the function `f` is `Cⁿ`. * `times_cont_mdiff_on.comp` gives the invariance of the `Cⁿ` property under composition * `times_cont_mdiff_on.times_cont_mdiff_on_tangent_map_within` states that the bundled derivative of a `Cⁿ` function in a domain is `Cᵐ` when `m + 1 ≤ n`. * `times_cont_mdiff.times_cont_mdiff_tangent_map` states that the bundled derivative of a `Cⁿ` function is `Cᵐ` when `m + 1 ≤ n`. * `times_cont_mdiff_iff_times_cont_diff` states that, for functions between vector spaces, manifold-smoothness is equivalent to usual smoothness. We also give many basic properties of smooth functions between manifolds, following the API of smooth functions between vector spaces. ## Implementation details Many properties follow for free from the corresponding properties of functions in vector spaces, as being `Cⁿ` is a local property invariant under the smooth groupoid. We take advantage of the general machinery developed in `local_invariant_properties.lean` to get these properties automatically. For instance, the fact that being `Cⁿ` does not depend on the chart one considers is given by `lift_prop_within_at_indep_chart`. For this to work, the definition of `times_cont_mdiff_within_at` and friends has to follow definitionally the setup of local invariant properties. Still, we recast the definition in terms of extended charts in `times_cont_mdiff_on_iff` and `times_cont_mdiff_iff`. -/ open set function filter charted_space smooth_manifold_with_corners open_locale topological_space manifold /-! ### Definition of smooth functions between manifolds -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] -- declare a smooth manifold `M` over the pair `(E, H)`. {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [Is : smooth_manifold_with_corners I M] -- declare a smooth manifold `M'` over the pair `(E', H')`. {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] [I's : smooth_manifold_with_corners I' M'] -- declare a smooth manifold `N` over the pair `(F, G)`. {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [topological_space G] {J : model_with_corners 𝕜 F G} {N : Type*} [topological_space N] [charted_space G N] [Js : smooth_manifold_with_corners J N] -- declare a smooth manifold `N'` over the pair `(F', G')`. {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {G' : Type*} [topological_space G'] {J' : model_with_corners 𝕜 F' G'} {N' : Type*} [topological_space N'] [charted_space G' N'] [J's : smooth_manifold_with_corners J' N'] -- declare functions, sets, points and smoothness indices {f f₁ : M → M'} {s s₁ t : set M} {x : M} {m n : with_top ℕ} /-- Property in the model space of a model with corners of being `C^n` within at set at a point, when read in the model vector space. This property will be lifted to manifolds to define smooth functions between manifolds. -/ def times_cont_diff_within_at_prop (n : with_top ℕ) (f s x) : Prop := times_cont_diff_within_at 𝕜 n (I' ∘ f ∘ I.symm) (range I ∩ I.symm ⁻¹' s) (I x) /-- Being `Cⁿ` in the model space is a local property, invariant under smooth maps. Therefore, it will lift nicely to manifolds. -/ lemma times_cont_diff_within_at_local_invariant_prop (n : with_top ℕ) : (times_cont_diff_groupoid ∞ I).local_invariant_prop (times_cont_diff_groupoid ∞ I') (times_cont_diff_within_at_prop I I' n) := { is_local := begin assume s x u f u_open xu, have : range I ∩ I.symm ⁻¹' (s ∩ u) = (range I ∩ I.symm ⁻¹' s) ∩ I.symm ⁻¹' u, by simp only [inter_assoc, preimage_inter], rw [times_cont_diff_within_at_prop, times_cont_diff_within_at_prop, this], symmetry, apply times_cont_diff_within_at_inter, have : u ∈ 𝓝 (I.symm (I x)), by { rw [model_with_corners.left_inv], exact mem_nhds_sets u_open xu }, apply continuous_at.preimage_mem_nhds I.continuous_symm.continuous_at this, end, right_invariance := begin assume s x f e he hx h, rw times_cont_diff_within_at_prop at h ⊢, have : I x = (I ∘ e.symm ∘ I.symm) (I (e x)), by simp only [hx] with mfld_simps, rw this at h, have : I (e x) ∈ (I.symm) ⁻¹' e.target ∩ range ⇑I, by simp only [hx] with mfld_simps, have := ((mem_groupoid_of_pregroupoid.2 he).2.times_cont_diff_within_at this).of_le le_top, convert h.comp' _ this using 1, { ext y, simp only with mfld_simps }, { mfld_set_tac } end, congr := begin assume s x f g h hx hf, apply hf.congr, { assume y hy, simp only with mfld_simps at hy, simp only [h, hy] with mfld_simps }, { simp only [hx] with mfld_simps } end, left_invariance := begin assume s x f e' he' hs hx h, rw times_cont_diff_within_at_prop at h ⊢, have A : (I' ∘ f ∘ I.symm) (I x) ∈ (I'.symm ⁻¹' e'.source ∩ range I'), by simp only [hx] with mfld_simps, have := ((mem_groupoid_of_pregroupoid.2 he').1.times_cont_diff_within_at A).of_le le_top, convert this.comp _ h _, { ext y, simp only with mfld_simps }, { assume y hy, simp only with mfld_simps at hy, simpa only [hy] with mfld_simps using hs hy.2 } end } lemma times_cont_diff_within_at_local_invariant_prop_mono (n : with_top ℕ) ⦃s x t⦄ ⦃f : H → H'⦄ (hts : t ⊆ s) (h : times_cont_diff_within_at_prop I I' n f s x) : times_cont_diff_within_at_prop I I' n f t x := begin apply h.mono (λ y hy, _), simp only with mfld_simps at hy, simp only [hy, hts _] with mfld_simps end lemma times_cont_diff_within_at_local_invariant_prop_id (x : H) : times_cont_diff_within_at_prop I I ∞ id univ x := begin simp [times_cont_diff_within_at_prop], have : times_cont_diff_within_at 𝕜 ∞ id (range I) (I x) := times_cont_diff_id.times_cont_diff_at.times_cont_diff_within_at, apply this.congr (λ y hy, _), { simp only with mfld_simps }, { simp only [model_with_corners.right_inv I hy] with mfld_simps } end /-- A function is `n` times continuously differentiable within a set at a point in a manifold if it is continuous and it is `n` times continuously differentiable in this set around this point, when read in the preferred chart at this point. -/ def times_cont_mdiff_within_at (n : with_top ℕ) (f : M → M') (s : set M) (x : M) := lift_prop_within_at (times_cont_diff_within_at_prop I I' n) f s x /-- Abbreviation for `times_cont_mdiff_within_at I I' ⊤ f s x`. See also documentation for `smooth`. -/ @[reducible] def smooth_within_at (f : M → M') (s : set M) (x : M) := times_cont_mdiff_within_at I I' ⊤ f s x /-- A function is `n` times continuously differentiable at a point in a manifold if it is continuous and it is `n` times continuously differentiable around this point, when read in the preferred chart at this point. -/ def times_cont_mdiff_at (n : with_top ℕ) (f : M → M') (x : M) := times_cont_mdiff_within_at I I' n f univ x /-- Abbreviation for `times_cont_mdiff_at I I' ⊤ f x`. See also documentation for `smooth`. -/ @[reducible] def smooth_at (f : M → M') (x : M) := times_cont_mdiff_at I I' ⊤ f x /-- A function is `n` times continuously differentiable in a set of a manifold if it is continuous and, for any pair of points, it is `n` times continuously differentiable on this set in the charts around these points. -/ def times_cont_mdiff_on (n : with_top ℕ) (f : M → M') (s : set M) := ∀ x ∈ s, times_cont_mdiff_within_at I I' n f s x /-- Abbreviation for `times_cont_mdiff_on I I' ⊤ f s`. See also documentation for `smooth`. -/ @[reducible] def smooth_on (f : M → M') (s : set M) := times_cont_mdiff_on I I' ⊤ f s /-- A function is `n` times continuously differentiable in a manifold if it is continuous and, for any pair of points, it is `n` times continuously differentiable in the charts around these points. -/ def times_cont_mdiff (n : with_top ℕ) (f : M → M') := ∀ x, times_cont_mdiff_at I I' n f x /-- Abbreviation for `times_cont_mdiff I I' ⊤ f`. Short note to work with these abbreviations: a lemma of the form `times_cont_mdiff_foo.bar` will apply fine to an assumption `smooth_foo` using dot notation or normal notation. If the consequence `bar` of the lemma involves `times_cont_diff`, it is still better to restate the lemma replacing `times_cont_diff` with `smooth` both in the assumption and in the conclusion, to make it possible to use `smooth` consistently. This also applies to `smooth_at`, `smooth_on` and `smooth_within_at`.-/ @[reducible] def smooth (f : M → M') := times_cont_mdiff I I' ⊤ f /-! ### Basic properties of smooth functions between manifolds -/ variables {I I'} lemma times_cont_mdiff.smooth (h : times_cont_mdiff I I' ⊤ f) : smooth I I' f := h lemma smooth.times_cont_mdiff (h : smooth I I' f) : times_cont_mdiff I I' ⊤ f := h lemma times_cont_mdiff_on.smooth_on (h : times_cont_mdiff_on I I' ⊤ f s) : smooth_on I I' f s := h lemma smooth_on.times_cont_mdiff_on (h : smooth_on I I' f s) : times_cont_mdiff_on I I' ⊤ f s := h lemma times_cont_mdiff_at.smooth_at (h : times_cont_mdiff_at I I' ⊤ f x) : smooth_at I I' f x := h lemma smooth_at.times_cont_mdiff_at (h : smooth_at I I' f x) : times_cont_mdiff_at I I' ⊤ f x := h lemma times_cont_mdiff_within_at.smooth_within_at (h : times_cont_mdiff_within_at I I' ⊤ f s x) : smooth_within_at I I' f s x := h lemma smooth_within_at.times_cont_mdiff_within_at (h : smooth_within_at I I' f s x) : times_cont_mdiff_within_at I I' ⊤ f s x := h lemma times_cont_mdiff.times_cont_mdiff_at (h : times_cont_mdiff I I' n f) : times_cont_mdiff_at I I' n f x := h x lemma smooth.smooth_at (h : smooth I I' f) : smooth_at I I' f x := times_cont_mdiff.times_cont_mdiff_at h lemma times_cont_mdiff_within_at_univ : times_cont_mdiff_within_at I I' n f univ x ↔ times_cont_mdiff_at I I' n f x := iff.rfl lemma smooth_at_univ : smooth_within_at I I' f univ x ↔ smooth_at I I' f x := times_cont_mdiff_within_at_univ lemma times_cont_mdiff_on_univ : times_cont_mdiff_on I I' n f univ ↔ times_cont_mdiff I I' n f := by simp only [times_cont_mdiff_on, times_cont_mdiff, times_cont_mdiff_within_at_univ, forall_prop_of_true, mem_univ] lemma smooth_on_univ : smooth_on I I' f univ ↔ smooth I I' f := times_cont_mdiff_on_univ /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in the corresponding extended chart. -/ lemma times_cont_mdiff_within_at_iff : times_cont_mdiff_within_at I I' n f s x ↔ continuous_within_at f s x ∧ times_cont_diff_within_at 𝕜 n ((ext_chart_at I' (f x)) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' (f x)).source)) (ext_chart_at I x x) := begin rw [times_cont_mdiff_within_at, lift_prop_within_at, times_cont_diff_within_at_prop], congr' 3, mfld_set_tac end /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in the corresponding extended chart. This form states smoothness of `f` written in the `ext_chart_at`s within the set `(ext_chart_at I x).symm ⁻¹' s ∩ range I`. This set is larger than the set `(ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' (f x)).source)` used in `times_cont_mdiff_within_at_iff` but their germs at `ext_chart_at I x x` are equal. It may be useful to rewrite using `times_cont_mdiff_within_at_iff''` in the *assumptions* of a lemma and using `times_cont_mdiff_within_at_iff` in the goal. -/ lemma times_cont_mdiff_within_at_iff'' : times_cont_mdiff_within_at I I' n f s x ↔ continuous_within_at f s x ∧ times_cont_diff_within_at 𝕜 n (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) (ext_chart_at I x x) := begin rw [times_cont_mdiff_within_at_iff, and.congr_right_iff], set e := ext_chart_at I x, set e' := ext_chart_at I' (f x), refine λ hc, times_cont_diff_within_at_congr_nhds _, rw [← e.image_source_inter_eq', ← ext_chart_at_map_nhds_within_eq_image, ← ext_chart_at_map_nhds_within, inter_comm, nhds_within_inter_of_mem], exact hc (ext_chart_at_source_mem_nhds _ _) end /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in the corresponding extended chart in the target. -/ lemma times_cont_mdiff_within_at_iff_target : times_cont_mdiff_within_at I I' n f s x ↔ continuous_within_at f s x ∧ times_cont_mdiff_within_at I 𝓘(𝕜, E') n ((ext_chart_at I' (f x)) ∘ f) (s ∩ f ⁻¹' (ext_chart_at I' (f x)).source) x := begin rw [times_cont_mdiff_within_at, times_cont_mdiff_within_at, lift_prop_within_at, lift_prop_within_at, ← and_assoc], have cont : (continuous_within_at f s x ∧ continuous_within_at ((I' ∘ (chart_at H' (f x))) ∘ f) (s ∩ f ⁻¹' (chart_at H' (f x)).to_local_equiv.source) x) ↔ continuous_within_at f s x, { refine ⟨λ h, h.1, λ h, ⟨h, _⟩⟩, have h₁ : continuous_within_at _ univ ((chart_at H' (f x)) (f x)), { exact (model_with_corners.continuous I').continuous_within_at }, have h₂ := (chart_at H' (f x)).continuous_to_fun.continuous_within_at (mem_chart_source _ _), convert (h₁.comp' h₂).comp' h, simp }, simp [cont, times_cont_diff_within_at_prop] end lemma smooth_within_at_iff : smooth_within_at I I' f s x ↔ continuous_within_at f s x ∧ times_cont_diff_within_at 𝕜 ∞ ((ext_chart_at I' (f x)) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' (f x)).source)) (ext_chart_at I x x) := times_cont_mdiff_within_at_iff lemma smooth_within_at_iff_target : smooth_within_at I I' f s x ↔ continuous_within_at f s x ∧ smooth_within_at I 𝓘(𝕜, E') ((ext_chart_at I' (f x)) ∘ f) (s ∩ f ⁻¹' (ext_chart_at I' (f x)).source) x := times_cont_mdiff_within_at_iff_target lemma times_cont_mdiff_at_ext_chart_at : times_cont_mdiff_at I 𝓘(𝕜, E) n (ext_chart_at I x) x := begin rw [times_cont_mdiff_at, times_cont_mdiff_within_at_iff], refine ⟨(ext_chart_at_continuous_at _ _).continuous_within_at, _⟩, refine times_cont_diff_within_at_id.congr _ _; simp only with mfld_simps { contextual := tt } end include Is I's /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in the corresponding extended chart. -/ lemma times_cont_mdiff_within_at_iff' {x' : M} {y : M'} (hx : x' ∈ (chart_at H x).source) (hy : f x' ∈ (chart_at H' y).source) : times_cont_mdiff_within_at I I' n f s x' ↔ continuous_within_at f s x' ∧ times_cont_diff_within_at 𝕜 n ((ext_chart_at I' y) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' y).source)) (ext_chart_at I x x') := begin refine ((times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_indep_chart (structure_groupoid.chart_mem_maximal_atlas _ x) hx (structure_groupoid.chart_mem_maximal_atlas _ y) hy).trans _, rw [times_cont_diff_within_at_prop, iff_eq_eq], congr' 2, mfld_set_tac end omit I's lemma times_cont_mdiff_at_ext_chart_at' {x' : M} (h : x' ∈ (chart_at H x).source) : times_cont_mdiff_at I 𝓘(𝕜, E) n (ext_chart_at I x) x' := begin refine (times_cont_mdiff_within_at_iff' h (mem_chart_source _ _)).2 _, refine ⟨(ext_chart_at_continuous_at' _ _ _).continuous_within_at, _⟩, { rwa ext_chart_at_source }, refine times_cont_diff_within_at_id.congr' _ _; simp only [h] with mfld_simps { contextual := tt } end include I's /-- One can reformulate smoothness on a set as continuity on this set, and smoothness in any extended chart. -/ lemma times_cont_mdiff_on_iff : times_cont_mdiff_on I I' n f s ↔ continuous_on f s ∧ ∀ (x : M) (y : M'), times_cont_diff_on 𝕜 n ((ext_chart_at I' y) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' y).source)) := begin split, { assume h, refine ⟨λ x hx, (h x hx).1, λ x y z hz, _⟩, simp only with mfld_simps at hz, let w := (ext_chart_at I x).symm z, have : w ∈ s, by simp only [w, hz] with mfld_simps, specialize h w this, have w1 : w ∈ (chart_at H x).source, by simp only [w, hz] with mfld_simps, have w2 : f w ∈ (chart_at H' y).source, by simp only [w, hz] with mfld_simps, convert (((times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_indep_chart (structure_groupoid.chart_mem_maximal_atlas _ x) w1 (structure_groupoid.chart_mem_maximal_atlas _ y) w2).1 h).2 using 1, { mfld_set_tac }, { simp only [w, hz] with mfld_simps } }, { rintros ⟨hcont, hdiff⟩ x hx, refine ⟨hcont x hx, _⟩, have Z := hdiff x (f x) (ext_chart_at I x x) (by simp only [hx] with mfld_simps), dsimp [times_cont_diff_within_at_prop], convert Z using 1, mfld_set_tac } end /-- One can reformulate smoothness on a set as continuity on this set, and smoothness in any extended chart in the target. -/ lemma times_cont_mdiff_on_iff_target : times_cont_mdiff_on I I' n f s ↔ continuous_on f s ∧ ∀ (y : M'), times_cont_mdiff_on I 𝓘(𝕜, E') n ((ext_chart_at I' y) ∘ f) (s ∩ f ⁻¹' (ext_chart_at I' y).source) := begin inhabit E', simp only [times_cont_mdiff_on_iff, model_with_corners.source_eq, chart_at_self_eq, local_homeomorph.refl_local_equiv, local_equiv.refl_trans, ext_chart_at.equations._eqn_1, set.preimage_univ, set.inter_univ, and.congr_right_iff], intros h, split, { refine λ h' y, ⟨_, λ x _, h' x y⟩, have h'' : continuous_on _ univ := (model_with_corners.continuous I').continuous_on, convert (h''.comp' (chart_at H' y).continuous_to_fun).comp' h, simp }, { exact λ h' x y, (h' y).2 x (default E') } end lemma smooth_on_iff : smooth_on I I' f s ↔ continuous_on f s ∧ ∀ (x : M) (y : M'), times_cont_diff_on 𝕜 ⊤ ((ext_chart_at I' y) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' y).source)) := times_cont_mdiff_on_iff lemma smooth_on_iff_target : smooth_on I I' f s ↔ continuous_on f s ∧ ∀ (y : M'), smooth_on I 𝓘(𝕜, E') ((ext_chart_at I' y) ∘ f) (s ∩ f ⁻¹' (ext_chart_at I' y).source) := times_cont_mdiff_on_iff_target /-- One can reformulate smoothness as continuity and smoothness in any extended chart. -/ lemma times_cont_mdiff_iff : times_cont_mdiff I I' n f ↔ continuous f ∧ ∀ (x : M) (y : M'), times_cont_diff_on 𝕜 n ((ext_chart_at I' y) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' y).source)) := by simp [← times_cont_mdiff_on_univ, times_cont_mdiff_on_iff, continuous_iff_continuous_on_univ] /-- One can reformulate smoothness as continuity and smoothness in any extended chart in the target. -/ lemma times_cont_mdiff_iff_target : times_cont_mdiff I I' n f ↔ continuous f ∧ ∀ (y : M'), times_cont_mdiff_on I 𝓘(𝕜, E') n ((ext_chart_at I' y) ∘ f) (f ⁻¹' (ext_chart_at I' y).source) := begin rw [← times_cont_mdiff_on_univ, times_cont_mdiff_on_iff_target], simp [continuous_iff_continuous_on_univ] end lemma smooth_iff : smooth I I' f ↔ continuous f ∧ ∀ (x : M) (y : M'), times_cont_diff_on 𝕜 ⊤ ((ext_chart_at I' y) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' y).source)) := times_cont_mdiff_iff lemma smooth_iff_target : smooth I I' f ↔ continuous f ∧ ∀ (y : M'), smooth_on I 𝓘(𝕜, E') ((ext_chart_at I' y) ∘ f) (f ⁻¹' (ext_chart_at I' y).source) := times_cont_mdiff_iff_target omit Is I's /-! ### Deducing smoothness from higher smoothness -/ lemma times_cont_mdiff_within_at.of_le (hf : times_cont_mdiff_within_at I I' n f s x) (le : m ≤ n) : times_cont_mdiff_within_at I I' m f s x := ⟨hf.1, hf.2.of_le le⟩ lemma times_cont_mdiff_at.of_le (hf : times_cont_mdiff_at I I' n f x) (le : m ≤ n) : times_cont_mdiff_at I I' m f x := times_cont_mdiff_within_at.of_le hf le lemma times_cont_mdiff_on.of_le (hf : times_cont_mdiff_on I I' n f s) (le : m ≤ n) : times_cont_mdiff_on I I' m f s := λ x hx, (hf x hx).of_le le lemma times_cont_mdiff.of_le (hf : times_cont_mdiff I I' n f) (le : m ≤ n) : times_cont_mdiff I I' m f := λ x, (hf x).of_le le /-! ### Deducing smoothness from smoothness one step beyond -/ lemma times_cont_mdiff_within_at.of_succ {n : ℕ} (h : times_cont_mdiff_within_at I I' n.succ f s x) : times_cont_mdiff_within_at I I' n f s x := h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)) lemma times_cont_mdiff_at.of_succ {n : ℕ} (h : times_cont_mdiff_at I I' n.succ f x) : times_cont_mdiff_at I I' n f x := times_cont_mdiff_within_at.of_succ h lemma times_cont_mdiff_on.of_succ {n : ℕ} (h : times_cont_mdiff_on I I' n.succ f s) : times_cont_mdiff_on I I' n f s := λ x hx, (h x hx).of_succ lemma times_cont_mdiff.of_succ {n : ℕ} (h : times_cont_mdiff I I' n.succ f) : times_cont_mdiff I I' n f := λ x, (h x).of_succ /-! ### Deducing continuity from smoothness-/ lemma times_cont_mdiff_within_at.continuous_within_at (hf : times_cont_mdiff_within_at I I' n f s x) : continuous_within_at f s x := hf.1 lemma times_cont_mdiff_at.continuous_at (hf : times_cont_mdiff_at I I' n f x) : continuous_at f x := (continuous_within_at_univ _ _ ).1 $ times_cont_mdiff_within_at.continuous_within_at hf lemma times_cont_mdiff_on.continuous_on (hf : times_cont_mdiff_on I I' n f s) : continuous_on f s := λ x hx, (hf x hx).continuous_within_at lemma times_cont_mdiff.continuous (hf : times_cont_mdiff I I' n f) : continuous f := continuous_iff_continuous_at.2 $ λ x, (hf x).continuous_at /-! ### Deducing differentiability from smoothness -/ lemma times_cont_mdiff_within_at.mdifferentiable_within_at (hf : times_cont_mdiff_within_at I I' n f s x) (hn : 1 ≤ n) : mdifferentiable_within_at I I' f s x := begin suffices h : mdifferentiable_within_at I I' f (s ∩ (f ⁻¹' (ext_chart_at I' (f x)).source)) x, { rwa mdifferentiable_within_at_inter' at h, apply (hf.1).preimage_mem_nhds_within, exact mem_nhds_sets (ext_chart_at_open_source I' (f x)) (mem_ext_chart_source I' (f x)) }, rw mdifferentiable_within_at_iff, exact ⟨hf.1.mono (inter_subset_left _ _), (hf.2.differentiable_within_at hn).mono (by mfld_set_tac)⟩, end lemma times_cont_mdiff_at.mdifferentiable_at (hf : times_cont_mdiff_at I I' n f x) (hn : 1 ≤ n) : mdifferentiable_at I I' f x := mdifferentiable_within_at_univ.1 $ times_cont_mdiff_within_at.mdifferentiable_within_at hf hn lemma times_cont_mdiff_on.mdifferentiable_on (hf : times_cont_mdiff_on I I' n f s) (hn : 1 ≤ n) : mdifferentiable_on I I' f s := λ x hx, (hf x hx).mdifferentiable_within_at hn lemma times_cont_mdiff.mdifferentiable (hf : times_cont_mdiff I I' n f) (hn : 1 ≤ n) : mdifferentiable I I' f := λ x, (hf x).mdifferentiable_at hn lemma smooth.mdifferentiable (hf : smooth I I' f) : mdifferentiable I I' f := times_cont_mdiff.mdifferentiable hf le_top lemma smooth.mdifferentiable_at (hf : smooth I I' f) : mdifferentiable_at I I' f x := hf.mdifferentiable x lemma smooth.mdifferentiable_within_at (hf : smooth I I' f) : mdifferentiable_within_at I I' f s x := hf.mdifferentiable_at.mdifferentiable_within_at /-! ### `C^∞` smoothness -/ lemma times_cont_mdiff_within_at_top : smooth_within_at I I' f s x ↔ (∀n:ℕ, times_cont_mdiff_within_at I I' n f s x) := ⟨λ h n, ⟨h.1, times_cont_diff_within_at_top.1 h.2 n⟩, λ H, ⟨(H 0).1, times_cont_diff_within_at_top.2 (λ n, (H n).2)⟩⟩ lemma times_cont_mdiff_at_top : smooth_at I I' f x ↔ (∀n:ℕ, times_cont_mdiff_at I I' n f x) := times_cont_mdiff_within_at_top lemma times_cont_mdiff_on_top : smooth_on I I' f s ↔ (∀n:ℕ, times_cont_mdiff_on I I' n f s) := ⟨λ h n, h.of_le le_top, λ h x hx, times_cont_mdiff_within_at_top.2 (λ n, h n x hx)⟩ lemma times_cont_mdiff_top : smooth I I' f ↔ (∀n:ℕ, times_cont_mdiff I I' n f) := ⟨λ h n, h.of_le le_top, λ h x, times_cont_mdiff_within_at_top.2 (λ n, h n x)⟩ lemma times_cont_mdiff_within_at_iff_nat : times_cont_mdiff_within_at I I' n f s x ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → times_cont_mdiff_within_at I I' m f s x) := begin refine ⟨λ h m hm, h.of_le hm, λ h, _⟩, cases n, { exact times_cont_mdiff_within_at_top.2 (λ n, h n le_top) }, { exact h n (le_refl _) } end /-! ### Restriction to a smaller set -/ lemma times_cont_mdiff_within_at.mono (hf : times_cont_mdiff_within_at I I' n f s x) (hts : t ⊆ s) : times_cont_mdiff_within_at I I' n f t x := structure_groupoid.local_invariant_prop.lift_prop_within_at_mono (times_cont_diff_within_at_local_invariant_prop_mono I I' n) hf hts lemma times_cont_mdiff_at.times_cont_mdiff_within_at (hf : times_cont_mdiff_at I I' n f x) : times_cont_mdiff_within_at I I' n f s x := times_cont_mdiff_within_at.mono hf (subset_univ _) lemma smooth_at.smooth_within_at (hf : smooth_at I I' f x) : smooth_within_at I I' f s x := times_cont_mdiff_at.times_cont_mdiff_within_at hf lemma times_cont_mdiff_on.mono (hf : times_cont_mdiff_on I I' n f s) (hts : t ⊆ s) : times_cont_mdiff_on I I' n f t := λ x hx, (hf x (hts hx)).mono hts lemma times_cont_mdiff.times_cont_mdiff_on (hf : times_cont_mdiff I I' n f) : times_cont_mdiff_on I I' n f s := λ x hx, (hf x).times_cont_mdiff_within_at lemma smooth.smooth_on (hf : smooth I I' f) : smooth_on I I' f s := times_cont_mdiff.times_cont_mdiff_on hf lemma times_cont_mdiff_within_at_inter' (ht : t ∈ 𝓝[s] x) : times_cont_mdiff_within_at I I' n f (s ∩ t) x ↔ times_cont_mdiff_within_at I I' n f s x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_inter' ht lemma times_cont_mdiff_within_at_inter (ht : t ∈ 𝓝 x) : times_cont_mdiff_within_at I I' n f (s ∩ t) x ↔ times_cont_mdiff_within_at I I' n f s x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_inter ht lemma times_cont_mdiff_within_at.times_cont_mdiff_at (h : times_cont_mdiff_within_at I I' n f s x) (ht : s ∈ 𝓝 x) : times_cont_mdiff_at I I' n f x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_at_of_lift_prop_within_at h ht lemma smooth_within_at.smooth_at (h : smooth_within_at I I' f s x) (ht : s ∈ 𝓝 x) : smooth_at I I' f x := times_cont_mdiff_within_at.times_cont_mdiff_at h ht include Is lemma times_cont_mdiff_on_ext_chart_at : times_cont_mdiff_on I 𝓘(𝕜, E) n (ext_chart_at I x) (chart_at H x).source := λ x' hx', (times_cont_mdiff_at_ext_chart_at' hx').times_cont_mdiff_within_at include I's /-- A function is `C^n` within a set at a point, for `n : ℕ`, if and only if it is `C^n` on a neighborhood of this point. -/ lemma times_cont_mdiff_within_at_iff_times_cont_mdiff_on_nhds {n : ℕ} : times_cont_mdiff_within_at I I' n f s x ↔ ∃ u ∈ 𝓝[insert x s] x, times_cont_mdiff_on I I' n f u := begin split, { assume h, -- the property is true in charts. We will pull such a good neighborhood in the chart to the -- manifold. For this, we need to restrict to a small enough set where everything makes sense obtain ⟨o, o_open, xo, ho, h'o⟩ : ∃ (o : set M), is_open o ∧ x ∈ o ∧ o ⊆ (chart_at H x).source ∧ o ∩ s ⊆ f ⁻¹' (chart_at H' (f x)).source, { have : (chart_at H' (f x)).source ∈ 𝓝 (f x) := mem_nhds_sets (local_homeomorph.open_source _) (mem_chart_source H' (f x)), rcases mem_nhds_within.1 (h.1.preimage_mem_nhds_within this) with ⟨u, u_open, xu, hu⟩, refine ⟨u ∩ (chart_at H x).source, _, ⟨xu, mem_chart_source _ _⟩, _, _⟩, { exact is_open_inter u_open (local_homeomorph.open_source _) }, { assume y hy, exact hy.2 }, { assume y hy, exact hu ⟨hy.1.1, hy.2⟩ } }, have h' : times_cont_mdiff_within_at I I' n f (s ∩ o) x := h.mono (inter_subset_left _ _), simp only [times_cont_mdiff_within_at, lift_prop_within_at, times_cont_diff_within_at_prop] at h', -- let `u` be a good neighborhood in the chart where the function is smooth rcases h.2.times_cont_diff_on (le_refl _) with ⟨u, u_nhds, u_subset, hu⟩, -- pull it back to the manifold, and intersect with a suitable neighborhood of `x`, to get the -- desired good neighborhood `v`. let v := ((insert x s) ∩ o) ∩ (ext_chart_at I x) ⁻¹' u, have v_incl : v ⊆ (chart_at H x).source := λ y hy, ho hy.1.2, have v_incl' : ∀ y ∈ v, f y ∈ (chart_at H' (f x)).source, { assume y hy, rcases hy.1.1 with rfl|h', { simp only with mfld_simps }, { apply h'o ⟨hy.1.2, h'⟩ } }, refine ⟨v, _, _⟩, show v ∈ 𝓝[insert x s] x, { rw nhds_within_restrict _ xo o_open, refine filter.inter_mem_sets self_mem_nhds_within _, suffices : u ∈ 𝓝[(ext_chart_at I x) '' (insert x s ∩ o)] (ext_chart_at I x x), from (ext_chart_at_continuous_at I x).continuous_within_at.preimage_mem_nhds_within' this, apply nhds_within_mono _ _ u_nhds, rw image_subset_iff, assume y hy, rcases hy.1 with rfl|h', { simp only [mem_insert_iff] with mfld_simps }, { simp only [mem_insert_iff, ho hy.2, h', h'o ⟨hy.2, h'⟩] with mfld_simps } }, show times_cont_mdiff_on I I' n f v, { assume y hy, apply (((times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_indep_chart (structure_groupoid.chart_mem_maximal_atlas _ x) (v_incl hy) (structure_groupoid.chart_mem_maximal_atlas _ (f x)) (v_incl' y hy))).2, split, { apply (((ext_chart_at_continuous_on_symm I' (f x) _ _).comp' (hu _ hy.2).continuous_within_at).comp' (ext_chart_at_continuous_on I x _ _)).congr_mono, { assume z hz, simp only [v_incl hz, v_incl' z hz] with mfld_simps }, { assume z hz, simp only [v_incl hz, v_incl' z hz] with mfld_simps, exact hz.2 }, { simp only [v_incl hy, v_incl' y hy] with mfld_simps }, { simp only [v_incl hy, v_incl' y hy] with mfld_simps }, { simp only [v_incl hy] with mfld_simps } }, { apply hu.mono, { assume z hz, simp only [v] with mfld_simps at hz, have : I ((chart_at H x) (((chart_at H x).symm) (I.symm z))) ∈ u, by simp only [hz], simpa only [hz] with mfld_simps using this }, { have exty : I (chart_at H x y) ∈ u := hy.2, simp only [v_incl hy, v_incl' y hy, exty, hy.1.1, hy.1.2] with mfld_simps } } } }, { rintros ⟨u, u_nhds, hu⟩, have : times_cont_mdiff_within_at I I' ↑n f (insert x s ∩ u) x, { have : x ∈ insert x s := mem_insert x s, exact hu.mono (inter_subset_right _ _) _ ⟨this, mem_of_mem_nhds_within this u_nhds⟩ }, rw times_cont_mdiff_within_at_inter' u_nhds at this, exact this.mono (subset_insert x s) } end /-- A function is `C^n` at a point, for `n : ℕ`, if and only if it is `C^n` on a neighborhood of this point. -/ lemma times_cont_mdiff_at_iff_times_cont_mdiff_on_nhds {n : ℕ} : times_cont_mdiff_at I I' n f x ↔ ∃ u ∈ 𝓝 x, times_cont_mdiff_on I I' n f u := by simp [← times_cont_mdiff_within_at_univ, times_cont_mdiff_within_at_iff_times_cont_mdiff_on_nhds, nhds_within_univ] omit Is I's /-! ### Congruence lemmas -/ lemma times_cont_mdiff_within_at.congr (h : times_cont_mdiff_within_at I I' n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : times_cont_mdiff_within_at I I' n f₁ s x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_congr h h₁ hx lemma times_cont_mdiff_within_at_congr (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : times_cont_mdiff_within_at I I' n f₁ s x ↔ times_cont_mdiff_within_at I I' n f s x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_congr_iff h₁ hx lemma times_cont_mdiff_within_at.congr_of_eventually_eq (h : times_cont_mdiff_within_at I I' n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_mdiff_within_at I I' n f₁ s x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_congr_of_eventually_eq h h₁ hx lemma filter.eventually_eq.times_cont_mdiff_within_at_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_mdiff_within_at I I' n f₁ s x ↔ times_cont_mdiff_within_at I I' n f s x := (times_cont_diff_within_at_local_invariant_prop I I' n) .lift_prop_within_at_congr_iff_of_eventually_eq h₁ hx lemma times_cont_mdiff_at.congr_of_eventually_eq (h : times_cont_mdiff_at I I' n f x) (h₁ : f₁ =ᶠ[𝓝 x] f) : times_cont_mdiff_at I I' n f₁ x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_at_congr_of_eventually_eq h h₁ lemma filter.eventually_eq.times_cont_mdiff_at_iff (h₁ : f₁ =ᶠ[𝓝 x] f) : times_cont_mdiff_at I I' n f₁ x ↔ times_cont_mdiff_at I I' n f x := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_at_congr_iff_of_eventually_eq h₁ lemma times_cont_mdiff_on.congr (h : times_cont_mdiff_on I I' n f s) (h₁ : ∀ y ∈ s, f₁ y = f y) : times_cont_mdiff_on I I' n f₁ s := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_on_congr h h₁ lemma times_cont_mdiff_on_congr (h₁ : ∀ y ∈ s, f₁ y = f y) : times_cont_mdiff_on I I' n f₁ s ↔ times_cont_mdiff_on I I' n f s := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_on_congr_iff h₁ /-! ### Locality -/ /-- Being `C^n` is a local property. -/ lemma times_cont_mdiff_on_of_locally_times_cont_mdiff_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_mdiff_on I I' n f (s ∩ u)) : times_cont_mdiff_on I I' n f s := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_on_of_locally_lift_prop_on h lemma times_cont_mdiff_of_locally_times_cont_mdiff_on (h : ∀x, ∃u, is_open u ∧ x ∈ u ∧ times_cont_mdiff_on I I' n f u) : times_cont_mdiff I I' n f := (times_cont_diff_within_at_local_invariant_prop I I' n).lift_prop_of_locally_lift_prop_on h /-! ### Smoothness of the composition of smooth functions between manifolds -/ section composition variables {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] /-- The composition of `C^n` functions within domains at points is `C^n`. -/ lemma times_cont_mdiff_within_at.comp {t : set M'} {g : M' → M''} (x : M) (hg : times_cont_mdiff_within_at I' I'' n g t (f x)) (hf : times_cont_mdiff_within_at I I' n f s x) (st : maps_to f s t) : times_cont_mdiff_within_at I I'' n (g ∘ f) s x := begin rw times_cont_mdiff_within_at_iff'' at hg hf ⊢, refine ⟨hg.1.comp hf.1 st, _⟩, set e := ext_chart_at I x, set e' := ext_chart_at I' (f x), set e'' := ext_chart_at I'' (g (f x)), have : e' (f x) = (written_in_ext_chart_at I I' x f) (e x), by simp only [e, e'] with mfld_simps, rw this at hg, have A : {y | y ∈ e.target ∧ f (e.symm y) ∈ t ∧ f (e.symm y) ∈ e'.source ∧ g (f (e.symm y)) ∈ e''.source} ∈ 𝓝[e.symm ⁻¹' s ∩ range I] e x, { simp only [← ext_chart_at_map_nhds_within, mem_map, mem_preimage], filter_upwards [hf.1.tendsto (ext_chart_at_source_mem_nhds I' (f x)), (hg.1.comp hf.1 st).tendsto (ext_chart_at_source_mem_nhds I'' (g (f x))), (inter_mem_nhds_within s (ext_chart_at_source_mem_nhds I x))], rintros x' (hfx' : f x' ∈ _) (hgfx' : g (f x') ∈ _) ⟨hx's, hx'⟩, simp only [e.map_source hx', mem_preimage, true_and, e.left_inv hx', st hx's, *] }, refine ((hg.2.comp _ (hf.2.mono (inter_subset_right _ _)) (inter_subset_left _ _)).mono_of_mem (inter_mem_sets _ self_mem_nhds_within)).congr_of_eventually_eq _ _, { filter_upwards [A], rintro x' ⟨hx', ht, hfx', hgfx'⟩, simp only [*, mem_preimage, written_in_ext_chart_at, (∘), mem_inter_eq, e'.left_inv, true_and], exact mem_range_self _ }, { filter_upwards [A], rintro x' ⟨hx', ht, hfx', hgfx'⟩, simp only [*, (∘), written_in_ext_chart_at, e'.left_inv] }, { simp only [written_in_ext_chart_at, (∘), mem_ext_chart_source, e.left_inv, e'.left_inv] } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_mdiff_on.comp {t : set M'} {g : M' → M''} (hg : times_cont_mdiff_on I' I'' n g t) (hf : times_cont_mdiff_on I I' n f s) (st : s ⊆ f ⁻¹' t) : times_cont_mdiff_on I I'' n (g ∘ f) s := λ x hx, (hg _ (st hx)).comp x (hf x hx) st /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_mdiff_on.comp' {t : set M'} {g : M' → M''} (hg : times_cont_mdiff_on I' I'' n g t) (hf : times_cont_mdiff_on I I' n f s) : times_cont_mdiff_on I I'' n (g ∘ f) (s ∩ f ⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_mdiff.comp {g : M' → M''} (hg : times_cont_mdiff I' I'' n g) (hf : times_cont_mdiff I I' n f) : times_cont_mdiff I I'' n (g ∘ f) := begin rw ← times_cont_mdiff_on_univ at hf hg ⊢, exact hg.comp hf subset_preimage_univ, end /-- The composition of `C^n` functions within domains at points is `C^n`. -/ lemma times_cont_mdiff_within_at.comp' {t : set M'} {g : M' → M''} (x : M) (hg : times_cont_mdiff_within_at I' I'' n g t (f x)) (hf : times_cont_mdiff_within_at I I' n f s x) : times_cont_mdiff_within_at I I'' n (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- `g ∘ f` is `C^n` within `s` at `x` if `g` is `C^n` at `f x` and `f` is `C^n` within `s` at `x`. -/ lemma times_cont_mdiff_at.comp_times_cont_mdiff_within_at {g : M' → M''} (x : M) (hg : times_cont_mdiff_at I' I'' n g (f x)) (hf : times_cont_mdiff_within_at I I' n f s x) : times_cont_mdiff_within_at I I'' n (g ∘ f) s x := hg.comp x hf (maps_to_univ _ _) /-- The composition of `C^n` functions at points is `C^n`. -/ lemma times_cont_mdiff_at.comp {g : M' → M''} (x : M) (hg : times_cont_mdiff_at I' I'' n g (f x)) (hf : times_cont_mdiff_at I I' n f x) : times_cont_mdiff_at I I'' n (g ∘ f) x := hg.comp x hf (maps_to_univ _ _) lemma times_cont_mdiff.comp_times_cont_mdiff_on {f : M → M'} {g : M' → M''} {s : set M} (hg : times_cont_mdiff I' I'' n g) (hf : times_cont_mdiff_on I I' n f s) : times_cont_mdiff_on I I'' n (g ∘ f) s := hg.times_cont_mdiff_on.comp hf set.subset_preimage_univ lemma smooth.comp_smooth_on {f : M → M'} {g : M' → M''} {s : set M} (hg : smooth I' I'' g) (hf : smooth_on I I' f s) : smooth_on I I'' (g ∘ f) s := hg.smooth_on.comp hf set.subset_preimage_univ end composition /-! ### Atlas members are smooth -/ section atlas variables {e : local_homeomorph M H} include Is /-- An atlas member is `C^n` for any `n`. -/ lemma times_cont_mdiff_on_of_mem_maximal_atlas (h : e ∈ maximal_atlas I M) : times_cont_mdiff_on I I n e e.source := times_cont_mdiff_on.of_le ((times_cont_diff_within_at_local_invariant_prop I I ∞).lift_prop_on_of_mem_maximal_atlas (times_cont_diff_within_at_local_invariant_prop_id I) h) le_top /-- The inverse of an atlas member is `C^n` for any `n`. -/ lemma times_cont_mdiff_on_symm_of_mem_maximal_atlas (h : e ∈ maximal_atlas I M) : times_cont_mdiff_on I I n e.symm e.target := times_cont_mdiff_on.of_le ((times_cont_diff_within_at_local_invariant_prop I I ∞).lift_prop_on_symm_of_mem_maximal_atlas (times_cont_diff_within_at_local_invariant_prop_id I) h) le_top lemma times_cont_mdiff_on_chart : times_cont_mdiff_on I I n (chart_at H x) (chart_at H x).source := times_cont_mdiff_on_of_mem_maximal_atlas ((times_cont_diff_groupoid ⊤ I).chart_mem_maximal_atlas x) lemma times_cont_mdiff_on_chart_symm : times_cont_mdiff_on I I n (chart_at H x).symm (chart_at H x).target := times_cont_mdiff_on_symm_of_mem_maximal_atlas ((times_cont_diff_groupoid ⊤ I).chart_mem_maximal_atlas x) end atlas /-! ### The identity is smooth -/ section id lemma times_cont_mdiff_id : times_cont_mdiff I I n (id : M → M) := times_cont_mdiff.of_le ((times_cont_diff_within_at_local_invariant_prop I I ∞).lift_prop_id (times_cont_diff_within_at_local_invariant_prop_id I)) le_top lemma smooth_id : smooth I I (id : M → M) := times_cont_mdiff_id lemma times_cont_mdiff_on_id : times_cont_mdiff_on I I n (id : M → M) s := times_cont_mdiff_id.times_cont_mdiff_on lemma smooth_on_id : smooth_on I I (id : M → M) s := times_cont_mdiff_on_id lemma times_cont_mdiff_at_id : times_cont_mdiff_at I I n (id : M → M) x := times_cont_mdiff_id.times_cont_mdiff_at lemma smooth_at_id : smooth_at I I (id : M → M) x := times_cont_mdiff_at_id lemma times_cont_mdiff_within_at_id : times_cont_mdiff_within_at I I n (id : M → M) s x := times_cont_mdiff_at_id.times_cont_mdiff_within_at lemma smooth_within_at_id : smooth_within_at I I (id : M → M) s x := times_cont_mdiff_within_at_id end id /-! ### Constants are smooth -/ section id variable {c : M'} lemma times_cont_mdiff_const : times_cont_mdiff I I' n (λ (x : M), c) := begin assume x, refine ⟨continuous_within_at_const, _⟩, simp only [times_cont_diff_within_at_prop, (∘)], exact times_cont_diff_within_at_const, end lemma smooth_const : smooth I I' (λ (x : M), c) := times_cont_mdiff_const lemma times_cont_mdiff_on_const : times_cont_mdiff_on I I' n (λ (x : M), c) s := times_cont_mdiff_const.times_cont_mdiff_on lemma smooth_on_const : smooth_on I I' (λ (x : M), c) s := times_cont_mdiff_on_const lemma times_cont_mdiff_at_const : times_cont_mdiff_at I I' n (λ (x : M), c) x := times_cont_mdiff_const.times_cont_mdiff_at lemma smooth_at_const : smooth_at I I' (λ (x : M), c) x := times_cont_mdiff_at_const lemma times_cont_mdiff_within_at_const : times_cont_mdiff_within_at I I' n (λ (x : M), c) s x := times_cont_mdiff_at_const.times_cont_mdiff_within_at lemma smooth_within_at_const : smooth_within_at I I' (λ (x : M), c) s x := times_cont_mdiff_within_at_const end id lemma times_cont_mdiff_of_support {f : M → F} (hf : ∀ x ∈ closure (support f), times_cont_mdiff_at I 𝓘(𝕜, F) n f x) : times_cont_mdiff I 𝓘(𝕜, F) n f := begin intro x, by_cases hx : x ∈ closure (support f), { exact hf x hx }, { refine times_cont_mdiff_at.congr_of_eventually_eq _ (eventually_eq_zero_nhds.2 hx), exact times_cont_mdiff_at_const } end /-! ### Equivalence with the basic definition for functions between vector spaces -/ section vector_space lemma times_cont_mdiff_within_at_iff_times_cont_diff_within_at {f : E → E'} {s : set E} {x : E} : times_cont_mdiff_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') n f s x ↔ times_cont_diff_within_at 𝕜 n f s x := begin simp only [times_cont_mdiff_within_at, lift_prop_within_at, times_cont_diff_within_at_prop, iff_def] with mfld_simps {contextual := tt}, exact times_cont_diff_within_at.continuous_within_at end alias times_cont_mdiff_within_at_iff_times_cont_diff_within_at ↔ times_cont_mdiff_within_at.times_cont_diff_within_at times_cont_diff_within_at.times_cont_mdiff_within_at lemma times_cont_mdiff_at_iff_times_cont_diff_at {f : E → E'} {x : E} : times_cont_mdiff_at 𝓘(𝕜, E) 𝓘(𝕜, E') n f x ↔ times_cont_diff_at 𝕜 n f x := by rw [← times_cont_mdiff_within_at_univ, times_cont_mdiff_within_at_iff_times_cont_diff_within_at, times_cont_diff_within_at_univ] alias times_cont_mdiff_at_iff_times_cont_diff_at ↔ times_cont_mdiff_at.times_cont_diff_at times_cont_diff_at.times_cont_mdiff_at lemma times_cont_mdiff_on_iff_times_cont_diff_on {f : E → E'} {s : set E} : times_cont_mdiff_on 𝓘(𝕜, E) 𝓘(𝕜, E') n f s ↔ times_cont_diff_on 𝕜 n f s := forall_congr $ by simp [times_cont_mdiff_within_at_iff_times_cont_diff_within_at] alias times_cont_mdiff_on_iff_times_cont_diff_on ↔ times_cont_mdiff_on.times_cont_diff_on times_cont_diff_on.times_cont_mdiff_on lemma times_cont_mdiff_iff_times_cont_diff {f : E → E'} : times_cont_mdiff 𝓘(𝕜, E) 𝓘(𝕜, E') n f ↔ times_cont_diff 𝕜 n f := by rw [← times_cont_diff_on_univ, ← times_cont_mdiff_on_univ, times_cont_mdiff_on_iff_times_cont_diff_on] alias times_cont_mdiff_iff_times_cont_diff ↔ times_cont_mdiff.times_cont_diff times_cont_diff.times_cont_mdiff end vector_space /-! ### The tangent map of a smooth function is smooth -/ section tangent_map /-- If a function is `C^n` with `1 ≤ n` on a domain with unique derivatives, then its bundled derivative is continuous. In this auxiliary lemma, we prove this fact when the source and target space are model spaces in models with corners. The general fact is proved in `times_cont_mdiff_on.continuous_on_tangent_map_within`-/ lemma times_cont_mdiff_on.continuous_on_tangent_map_within_aux {f : H → H'} {s : set H} (hf : times_cont_mdiff_on I I' n f s) (hn : 1 ≤ n) (hs : unique_mdiff_on I s) : continuous_on (tangent_map_within I I' f s) ((tangent_bundle.proj I H) ⁻¹' s) := begin suffices h : continuous_on (λ (p : H × E), (f p.fst, (fderiv_within 𝕜 (written_in_ext_chart_at I I' p.fst f) (I.symm ⁻¹' s ∩ range I) ((ext_chart_at I p.fst) p.fst) : E →L[𝕜] E') p.snd)) (prod.fst ⁻¹' s), { have A := (tangent_bundle_model_space_homeomorph H I).continuous, rw continuous_iff_continuous_on_univ at A, have B := ((tangent_bundle_model_space_homeomorph H' I').symm.continuous.comp_continuous_on h) .comp' A, have : (univ ∩ ⇑(tangent_bundle_model_space_homeomorph H I) ⁻¹' (prod.fst ⁻¹' s)) = tangent_bundle.proj I H ⁻¹' s, by { ext ⟨x, v⟩, simp only with mfld_simps }, rw this at B, apply B.congr, rintros ⟨x, v⟩ hx, dsimp [tangent_map_within], ext, { refl }, simp only with mfld_simps, apply congr_fun, apply congr_arg, rw mdifferentiable_within_at.mfderiv_within (hf.mdifferentiable_on hn x hx), refl }, suffices h : continuous_on (λ (p : H × E), (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I p.fst) : E →L[𝕜] E') p.snd) (prod.fst ⁻¹' s), { dsimp [written_in_ext_chart_at, ext_chart_at], apply continuous_on.prod (continuous_on.comp hf.continuous_on continuous_fst.continuous_on (subset.refl _)), apply h.congr, assume p hp, refl }, suffices h : continuous_on (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I)) (I '' s), { have C := continuous_on.comp h I.continuous_to_fun.continuous_on (subset.refl _), have A : continuous (λq : (E →L[𝕜] E') × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : H × E, (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I p.1), p.2)) (prod.fst ⁻¹' s), { apply continuous_on.prod _ continuous_snd.continuous_on, refine (continuous_on.comp C continuous_fst.continuous_on _ : _), exact preimage_mono (subset_preimage_image _ _) }, exact A.comp_continuous_on B }, rw times_cont_mdiff_on_iff at hf, let x : H := I.symm (0 : E), let y : H' := I'.symm (0 : E'), have A := hf.2 x y, simp only [I.image_eq, inter_comm] with mfld_simps at A ⊢, apply A.continuous_on_fderiv_within _ hn, convert hs.unique_diff_on_target_inter x using 1, simp only [inter_comm] with mfld_simps end /-- If a function is `C^n` on a domain with unique derivatives, then its bundled derivative is `C^m` when `m+1 ≤ n`. In this auxiliary lemma, we prove this fact when the source and target space are model spaces in models with corners. The general fact is proved in `times_cont_mdiff_on.times_cont_mdiff_on_tangent_map_within` -/ lemma times_cont_mdiff_on.times_cont_mdiff_on_tangent_map_within_aux {f : H → H'} {s : set H} (hf : times_cont_mdiff_on I I' n f s) (hmn : m + 1 ≤ n) (hs : unique_mdiff_on I s) : times_cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' f s) ((tangent_bundle.proj I H) ⁻¹' s) := begin have m_le_n : m ≤ n, { apply le_trans _ hmn, have : m + 0 ≤ m + 1 := add_le_add_left (zero_le _) _, simpa only [add_zero] using this }, have one_le_n : 1 ≤ n, { apply le_trans _ hmn, change 0 + 1 ≤ m + 1, exact add_le_add_right (zero_le _) _ }, have U': unique_diff_on 𝕜 (range I ∩ I.symm ⁻¹' s), { assume y hy, simpa only [unique_mdiff_on, unique_mdiff_within_at, hy.1, inter_comm] with mfld_simps using hs (I.symm y) hy.2 }, have U : unique_diff_on 𝕜 (set.prod (range I ∩ I.symm ⁻¹' s) (univ : set E)) := U'.prod unique_diff_on_univ, rw times_cont_mdiff_on_iff, refine ⟨hf.continuous_on_tangent_map_within_aux one_le_n hs, λp q, _⟩, have A : (range I).prod univ ∩ ((equiv.sigma_equiv_prod H E).symm ∘ λ (p : E × E), ((I.symm) p.fst, p.snd)) ⁻¹' (tangent_bundle.proj I H ⁻¹' s) = set.prod (range I ∩ I.symm ⁻¹' s) univ, by { ext ⟨x, v⟩, simp only with mfld_simps }, suffices h : times_cont_diff_on 𝕜 m (((λ (p : H' × E'), (I' p.fst, p.snd)) ∘ (equiv.sigma_equiv_prod H' E')) ∘ tangent_map_within I I' f s ∘ ((equiv.sigma_equiv_prod H E).symm) ∘ λ (p : E × E), (I.symm p.fst, p.snd)) ((range ⇑I ∩ ⇑(I.symm) ⁻¹' s).prod univ), by simpa [A] using h, change times_cont_diff_on 𝕜 m (λ (p : E × E), ((I' (f (I.symm p.fst)), ((mfderiv_within I I' f s (I.symm p.fst)) : E → E') p.snd) : E' × E')) (set.prod (range I ∩ I.symm ⁻¹' s) univ), -- check that all bits in this formula are `C^n` have hf' := times_cont_mdiff_on_iff.1 hf, have A : times_cont_diff_on 𝕜 m (I' ∘ f ∘ I.symm) (range I ∩ I.symm ⁻¹' s) := by simpa only with mfld_simps using (hf'.2 (I.symm 0) (I'.symm 0)).of_le m_le_n, have B : times_cont_diff_on 𝕜 m ((I' ∘ f ∘ I.symm) ∘ prod.fst) (set.prod (range I ∩ I.symm ⁻¹' s) (univ : set E)) := A.comp (times_cont_diff_fst.times_cont_diff_on) (prod_subset_preimage_fst _ _), suffices C : times_cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) p.1 : _) p.2)) (set.prod (range I ∩ I.symm ⁻¹' s) univ), { apply times_cont_diff_on.prod B _, apply C.congr (λp hp, _), simp only with mfld_simps at hp, simp only [mfderiv_within, hf.mdifferentiable_on one_le_n _ hp.2, hp.1, dif_pos] with mfld_simps }, have D : times_cont_diff_on 𝕜 m (λ x, (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) x)) (range I ∩ I.symm ⁻¹' s), { have : times_cont_diff_on 𝕜 n (I' ∘ f ∘ I.symm) (range I ∩ I.symm ⁻¹' s) := by simpa only with mfld_simps using (hf'.2 (I.symm 0) (I'.symm 0)), simpa only [inter_comm] using this.fderiv_within U' hmn }, have := D.comp (times_cont_diff_fst.times_cont_diff_on) (prod_subset_preimage_fst _ _), have := times_cont_diff_on.prod this (times_cont_diff_snd.times_cont_diff_on), exact is_bounded_bilinear_map_apply.times_cont_diff.comp_times_cont_diff_on this, end include Is I's /-- If a function is `C^n` on a domain with unique derivatives, then its bundled derivative is `C^m` when `m+1 ≤ n`. -/ theorem times_cont_mdiff_on.times_cont_mdiff_on_tangent_map_within (hf : times_cont_mdiff_on I I' n f s) (hmn : m + 1 ≤ n) (hs : unique_mdiff_on I s) : times_cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' f s) ((tangent_bundle.proj I M) ⁻¹' s) := begin /- The strategy of the proof is to avoid unfolding the definitions, and reduce by functoriality to the case of functions on the model spaces, where we have already proved the result. Let `l` and `r` be the charts to the left and to the right, so that we have ``` l^{-1} f r H --------> M ---> M' ---> H' ``` Then the tangent map `T(r ∘ f ∘ l)` is smooth by a previous result. Consider the composition ``` Tl T(r ∘ f ∘ l^{-1}) Tr^{-1} TM -----> TH -------------------> TH' ---------> TM' ``` where `Tr^{-1}` and `Tl` are the tangent maps of `r^{-1}` and `l`. Writing `Tl` and `Tr^{-1}` as composition of charts (called `Dl` and `il` for `l` and `Dr` and `ir` in the proof below), it follows that they are smooth. The composition of all these maps is `Tf`, and is therefore smooth as a composition of smooth maps. -/ have m_le_n : m ≤ n, { apply le_trans _ hmn, have : m + 0 ≤ m + 1 := add_le_add_left (zero_le _) _, simpa only [add_zero] }, have one_le_n : 1 ≤ n, { apply le_trans _ hmn, change 0 + 1 ≤ m + 1, exact add_le_add_right (zero_le _) _ }, /- First step: local reduction on the space, to a set `s'` which is contained in chart domains. -/ refine times_cont_mdiff_on_of_locally_times_cont_mdiff_on (λp hp, _), have hf' := times_cont_mdiff_on_iff.1 hf, simp [tangent_bundle.proj] at hp, let l := chart_at H p.1, set Dl := chart_at (model_prod H E) p with hDl, let r := chart_at H' (f p.1), let Dr := chart_at (model_prod H' E') (tangent_map_within I I' f s p), let il := chart_at (model_prod H E) (tangent_map I I l p), let ir := chart_at (model_prod H' E') (tangent_map I I' (r ∘ f) p), let s' := f ⁻¹' r.source ∩ s ∩ l.source, let s'_lift := (tangent_bundle.proj I M)⁻¹' s', let s'l := l.target ∩ l.symm ⁻¹' s', let s'l_lift := (tangent_bundle.proj I H) ⁻¹' s'l, rcases continuous_on_iff'.1 hf'.1 r.source r.open_source with ⟨o, o_open, ho⟩, suffices h : times_cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' f s) s'_lift, { refine ⟨(tangent_bundle.proj I M)⁻¹' (o ∩ l.source), _, _, _⟩, show is_open ((tangent_bundle.proj I M)⁻¹' (o ∩ l.source)), from (is_open_inter o_open l.open_source).preimage (tangent_bundle_proj_continuous _ _) , show p ∈ tangent_bundle.proj I M ⁻¹' (o ∩ l.source), { simp [tangent_bundle.proj] at ⊢, have : p.1 ∈ f ⁻¹' r.source ∩ s, by simp [hp], rw ho at this, exact this.1 }, { have : tangent_bundle.proj I M ⁻¹' s ∩ tangent_bundle.proj I M ⁻¹' (o ∩ l.source) = s'_lift, { dsimp only [s'_lift, s'], rw [ho], mfld_set_tac }, rw this, exact h } }, /- Second step: check that all functions are smooth, and use the chain rule to write the bundled derivative as a composition of a function between model spaces and of charts. Convention: statements about the differentiability of `a ∘ b ∘ c` are named `diff_abc`. Statements about differentiability in the bundle have a `_lift` suffix. -/ have U' : unique_mdiff_on I s', { apply unique_mdiff_on.inter _ l.open_source, rw [ho, inter_comm], exact hs.inter o_open }, have U'l : unique_mdiff_on I s'l := U'.unique_mdiff_on_preimage (mdifferentiable_chart _ _), have diff_f : times_cont_mdiff_on I I' n f s' := hf.mono (by mfld_set_tac), have diff_r : times_cont_mdiff_on I' I' n r r.source := times_cont_mdiff_on_chart, have diff_rf : times_cont_mdiff_on I I' n (r ∘ f) s', { apply times_cont_mdiff_on.comp diff_r diff_f (λx hx, _), simp only [s'] with mfld_simps at hx, simp only [hx] with mfld_simps }, have diff_l : times_cont_mdiff_on I I n l.symm s'l, { have A : times_cont_mdiff_on I I n l.symm l.target := times_cont_mdiff_on_chart_symm, exact A.mono (by mfld_set_tac) }, have diff_rfl : times_cont_mdiff_on I I' n (r ∘ f ∘ l.symm) s'l, { apply times_cont_mdiff_on.comp diff_rf diff_l, mfld_set_tac }, have diff_rfl_lift : times_cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l) s'l_lift := diff_rfl.times_cont_mdiff_on_tangent_map_within_aux hmn U'l, have diff_irrfl_lift : times_cont_mdiff_on I.tangent I'.tangent m (ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l)) s'l_lift, { have A : times_cont_mdiff_on I'.tangent I'.tangent m ir ir.source := times_cont_mdiff_on_chart, exact times_cont_mdiff_on.comp A diff_rfl_lift (λp hp, by simp only [ir] with mfld_simps) }, have diff_Drirrfl_lift : times_cont_mdiff_on I.tangent I'.tangent m (Dr.symm ∘ (ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l))) s'l_lift, { have A : times_cont_mdiff_on I'.tangent I'.tangent m Dr.symm Dr.target := times_cont_mdiff_on_chart_symm, apply times_cont_mdiff_on.comp A diff_irrfl_lift (λp hp, _), simp only [s'l_lift, tangent_bundle.proj] with mfld_simps at hp, simp only [ir, @local_equiv.refl_coe (model_prod H' E'), hp] with mfld_simps }, -- conclusion of this step: the composition of all the maps above is smooth have diff_DrirrflilDl : times_cont_mdiff_on I.tangent I'.tangent m (Dr.symm ∘ (ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l)) ∘ (il.symm ∘ Dl)) s'_lift, { have A : times_cont_mdiff_on I.tangent I.tangent m Dl Dl.source := times_cont_mdiff_on_chart, have A' : times_cont_mdiff_on I.tangent I.tangent m Dl s'_lift, { apply A.mono (λp hp, _), simp only [s'_lift, tangent_bundle.proj] with mfld_simps at hp, simp only [Dl, hp] with mfld_simps }, have B : times_cont_mdiff_on I.tangent I.tangent m il.symm il.target := times_cont_mdiff_on_chart_symm, have C : times_cont_mdiff_on I.tangent I.tangent m (il.symm ∘ Dl) s'_lift := times_cont_mdiff_on.comp B A' (λp hp, by simp only [il] with mfld_simps), apply times_cont_mdiff_on.comp diff_Drirrfl_lift C (λp hp, _), simp only [s'_lift, tangent_bundle.proj] with mfld_simps at hp, simp only [il, s'l_lift, hp, tangent_bundle.proj] with mfld_simps }, /- Third step: check that the composition of all the maps indeed coincides with the derivative we are looking for -/ have eq_comp : ∀q ∈ s'_lift, tangent_map_within I I' f s q = (Dr.symm ∘ ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l) ∘ (il.symm ∘ Dl)) q, { assume q hq, simp only [s'_lift, tangent_bundle.proj] with mfld_simps at hq, have U'q : unique_mdiff_within_at I s' q.1, by { apply U', simp only [hq, s'] with mfld_simps }, have U'lq : unique_mdiff_within_at I s'l (Dl q).1, by { apply U'l, simp only [hq, s'l] with mfld_simps }, have A : tangent_map_within I I' ((r ∘ f) ∘ l.symm) s'l (il.symm (Dl q)) = tangent_map_within I I' (r ∘ f) s' (tangent_map_within I I l.symm s'l (il.symm (Dl q))), { refine tangent_map_within_comp_at (il.symm (Dl q)) _ _ (λp hp, _) U'lq, { apply diff_rf.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, { apply diff_l.mdifferentiable_on one_le_n, simp only [s'l, hq] with mfld_simps }, { simp only with mfld_simps at hp, simp only [hp] with mfld_simps } }, have B : tangent_map_within I I l.symm s'l (il.symm (Dl q)) = q, { have : tangent_map_within I I l.symm s'l (il.symm (Dl q)) = tangent_map I I l.symm (il.symm (Dl q)), { refine tangent_map_within_eq_tangent_map U'lq _, refine mdifferentiable_at_atlas_symm _ (chart_mem_atlas _ _) _, simp only [hq] with mfld_simps }, rw [this, tangent_map_chart_symm, hDl], { simp only [hq] with mfld_simps, have : q ∈ (chart_at (model_prod H E) p).source, by simp only [hq] with mfld_simps, exact (chart_at (model_prod H E) p).left_inv this }, { simp only [hq] with mfld_simps } }, have C : tangent_map_within I I' (r ∘ f) s' q = tangent_map_within I' I' r r.source (tangent_map_within I I' f s' q), { refine tangent_map_within_comp_at q _ _ (λr hr, _) U'q, { apply diff_r.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, { apply diff_f.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, { simp only [s'] with mfld_simps at hr, simp only [hr] with mfld_simps } }, have D : Dr.symm (ir (tangent_map_within I' I' r r.source (tangent_map_within I I' f s' q))) = tangent_map_within I I' f s' q, { have A : tangent_map_within I' I' r r.source (tangent_map_within I I' f s' q) = tangent_map I' I' r (tangent_map_within I I' f s' q), { apply tangent_map_within_eq_tangent_map, { apply is_open.unique_mdiff_within_at _ r.open_source, simp [hq] }, { refine mdifferentiable_at_atlas _ (chart_mem_atlas _ _) _, simp only [hq] with mfld_simps } }, have : f p.1 = (tangent_map_within I I' f s p).1 := rfl, rw [A], dsimp [r, Dr], rw [this, tangent_map_chart], { simp only [hq] with mfld_simps, have : tangent_map_within I I' f s' q ∈ (chart_at (model_prod H' E') (tangent_map_within I I' f s p)).source, by simp only [hq] with mfld_simps, exact (chart_at (model_prod H' E') (tangent_map_within I I' f s p)).left_inv this }, { simp only [hq] with mfld_simps } }, have E : tangent_map_within I I' f s' q = tangent_map_within I I' f s q, { refine tangent_map_within_subset (by mfld_set_tac) U'q _, apply hf.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, simp only [(∘), A, B, C, D, E.symm] }, exact diff_DrirrflilDl.congr eq_comp, end /-- If a function is `C^n` on a domain with unique derivatives, with `1 ≤ n`, then its bundled derivative is continuous there. -/ theorem times_cont_mdiff_on.continuous_on_tangent_map_within (hf : times_cont_mdiff_on I I' n f s) (hmn : 1 ≤ n) (hs : unique_mdiff_on I s) : continuous_on (tangent_map_within I I' f s) ((tangent_bundle.proj I M) ⁻¹' s) := begin have : times_cont_mdiff_on I.tangent I'.tangent 0 (tangent_map_within I I' f s) ((tangent_bundle.proj I M) ⁻¹' s) := hf.times_cont_mdiff_on_tangent_map_within hmn hs, exact this.continuous_on end /-- If a function is `C^n`, then its bundled derivative is `C^m` when `m+1 ≤ n`. -/ theorem times_cont_mdiff.times_cont_mdiff_tangent_map (hf : times_cont_mdiff I I' n f) (hmn : m + 1 ≤ n) : times_cont_mdiff I.tangent I'.tangent m (tangent_map I I' f) := begin rw ← times_cont_mdiff_on_univ at hf ⊢, convert hf.times_cont_mdiff_on_tangent_map_within hmn unique_mdiff_on_univ, rw tangent_map_within_univ end /-- If a function is `C^n`, with `1 ≤ n`, then its bundled derivative is continuous. -/ theorem times_cont_mdiff.continuous_tangent_map (hf : times_cont_mdiff I I' n f) (hmn : 1 ≤ n) : continuous (tangent_map I I' f) := begin rw ← times_cont_mdiff_on_univ at hf, rw continuous_iff_continuous_on_univ, convert hf.continuous_on_tangent_map_within hmn unique_mdiff_on_univ, rw tangent_map_within_univ end end tangent_map /-! ### Smoothness of the projection in a basic smooth bundle -/ namespace basic_smooth_bundle_core variables (Z : basic_smooth_bundle_core I M E') lemma times_cont_mdiff_proj : times_cont_mdiff ((I.prod 𝓘(𝕜, E'))) I n Z.to_topological_fiber_bundle_core.proj := begin assume x, rw [times_cont_mdiff_at, times_cont_mdiff_within_at_iff], refine ⟨Z.to_topological_fiber_bundle_core.continuous_proj.continuous_at.continuous_within_at, _⟩, simp only [(∘), chart_at, chart] with mfld_simps, apply times_cont_diff_within_at_fst.congr, { rintros ⟨a, b⟩ hab, simp only with mfld_simps at hab, simp only [hab] with mfld_simps }, { simp only with mfld_simps } end lemma smooth_proj : smooth ((I.prod 𝓘(𝕜, E'))) I Z.to_topological_fiber_bundle_core.proj := times_cont_mdiff_proj Z lemma times_cont_mdiff_on_proj {s : set (Z.to_topological_fiber_bundle_core.total_space)} : times_cont_mdiff_on ((I.prod 𝓘(𝕜, E'))) I n Z.to_topological_fiber_bundle_core.proj s := Z.times_cont_mdiff_proj.times_cont_mdiff_on lemma smooth_on_proj {s : set (Z.to_topological_fiber_bundle_core.total_space)} : smooth_on ((I.prod 𝓘(𝕜, E'))) I Z.to_topological_fiber_bundle_core.proj s := times_cont_mdiff_on_proj Z lemma times_cont_mdiff_at_proj {p : Z.to_topological_fiber_bundle_core.total_space} : times_cont_mdiff_at ((I.prod 𝓘(𝕜, E'))) I n Z.to_topological_fiber_bundle_core.proj p := Z.times_cont_mdiff_proj.times_cont_mdiff_at lemma smooth_at_proj {p : Z.to_topological_fiber_bundle_core.total_space} : smooth_at ((I.prod 𝓘(𝕜, E'))) I Z.to_topological_fiber_bundle_core.proj p := Z.times_cont_mdiff_at_proj lemma times_cont_mdiff_within_at_proj {s : set (Z.to_topological_fiber_bundle_core.total_space)} {p : Z.to_topological_fiber_bundle_core.total_space} : times_cont_mdiff_within_at ((I.prod 𝓘(𝕜, E'))) I n Z.to_topological_fiber_bundle_core.proj s p := Z.times_cont_mdiff_at_proj.times_cont_mdiff_within_at lemma smooth_within_at_proj {s : set (Z.to_topological_fiber_bundle_core.total_space)} {p : Z.to_topological_fiber_bundle_core.total_space} : smooth_within_at ((I.prod 𝓘(𝕜, E'))) I Z.to_topological_fiber_bundle_core.proj s p := Z.times_cont_mdiff_within_at_proj /-- If an element of `E'` is invariant under all coordinate changes, then one can define a corresponding section of the fiber bundle, which is smooth. This applies in particular to the zero section of a vector bundle. Another example (not yet defined) would be the identity section of the endomorphism bundle of a vector bundle. -/ lemma smooth_const_section (v : E') (h : ∀ (i j : atlas H M), ∀ x ∈ i.1.source ∩ j.1.source, Z.coord_change i j (i.1 x) v = v) : smooth I ((I.prod 𝓘(𝕜, E'))) (show M → Z.to_topological_fiber_bundle_core.total_space, from λ x, ⟨x, v⟩) := begin assume x, rw [times_cont_mdiff_at, times_cont_mdiff_within_at_iff], split, { apply continuous.continuous_within_at, apply topological_fiber_bundle_core.continuous_const_section, assume i j y hy, exact h _ _ _ hy }, { have : times_cont_diff 𝕜 ⊤ (λ (y : E), (y, v)) := times_cont_diff_id.prod times_cont_diff_const, apply this.times_cont_diff_within_at.congr, { assume y hy, simp only with mfld_simps at hy, simp only [chart, hy, chart_at, prod.mk.inj_iff, to_topological_fiber_bundle_core] with mfld_simps, apply h, simp only [hy] with mfld_simps }, { simp only [chart, chart_at, prod.mk.inj_iff, to_topological_fiber_bundle_core] with mfld_simps, apply h, simp only with mfld_simps } } end end basic_smooth_bundle_core /-! ### Smoothness of the tangent bundle projection -/ namespace tangent_bundle include Is lemma times_cont_mdiff_proj : times_cont_mdiff I.tangent I n (proj I M) := basic_smooth_bundle_core.times_cont_mdiff_proj _ lemma smooth_proj : smooth I.tangent I (proj I M) := basic_smooth_bundle_core.smooth_proj _ lemma times_cont_mdiff_on_proj {s : set (tangent_bundle I M)} : times_cont_mdiff_on I.tangent I n (proj I M) s := basic_smooth_bundle_core.times_cont_mdiff_on_proj _ lemma smooth_on_proj {s : set (tangent_bundle I M)} : smooth_on I.tangent I (proj I M) s := basic_smooth_bundle_core.smooth_on_proj _ lemma times_cont_mdiff_at_proj {p : tangent_bundle I M} : times_cont_mdiff_at I.tangent I n (proj I M) p := basic_smooth_bundle_core.times_cont_mdiff_at_proj _ lemma smooth_at_proj {p : tangent_bundle I M} : smooth_at I.tangent I (proj I M) p := basic_smooth_bundle_core.smooth_at_proj _ lemma times_cont_mdiff_within_at_proj {s : set (tangent_bundle I M)} {p : tangent_bundle I M} : times_cont_mdiff_within_at I.tangent I n (proj I M) s p := basic_smooth_bundle_core.times_cont_mdiff_within_at_proj _ lemma smooth_within_at_proj {s : set (tangent_bundle I M)} {p : tangent_bundle I M} : smooth_within_at I.tangent I (proj I M) s p := basic_smooth_bundle_core.smooth_within_at_proj _ variables (I M) /-- The zero section of the tangent bundle -/ def zero_section : M → tangent_bundle I M := λ x, ⟨x, 0⟩ variables {I M} lemma smooth_zero_section : smooth I I.tangent (zero_section I M) := begin apply basic_smooth_bundle_core.smooth_const_section (tangent_bundle_core I M) 0, assume i j x hx, simp only [tangent_bundle_core, continuous_linear_map.map_zero] with mfld_simps end /-- The derivative of the zero section of the tangent bundle maps `⟨x, v⟩` to `⟨⟨x, 0⟩, ⟨v, 0⟩⟩`. Note that, as currently framed, this is a statement in coordinates, thus reliant on the choice of the coordinate system we use on the tangent bundle. However, the result itself is coordinate-dependent only to the extent that the coordinates determine a splitting of the tangent bundle. Moreover, there is a canonical splitting at each point of the zero section (since there is a canonical horizontal space there, the tangent space to the zero section, in addition to the canonical vertical space which is the kernel of the derivative of the projection), and this canonical splitting is also the one that comes from the coordinates on the tangent bundle in our definitions. So this statement is not as crazy as it may seem. TODO define splittings of vector bundles; state this result invariantly. -/ lemma tangent_map_tangent_bundle_pure (p : tangent_bundle I M) : tangent_map I I.tangent (tangent_bundle.zero_section I M) p = ⟨⟨p.1, 0⟩, ⟨p.2, 0⟩⟩ := begin rcases p with ⟨x, v⟩, have N : I.symm ⁻¹' (chart_at H x).target ∈ 𝓝 (I ((chart_at H x) x)), { apply mem_nhds_sets, apply (local_homeomorph.open_target _).preimage I.continuous_inv_fun, simp only with mfld_simps }, have A : mdifferentiable_at I I.tangent (λ (x : M), (⟨x, 0⟩ : tangent_bundle I M)) x := tangent_bundle.smooth_zero_section.mdifferentiable_at, have B : fderiv_within 𝕜 (λ (x_1 : E), (x_1, (0 : E))) (set.range ⇑I) (I ((chart_at H x) x)) v = (v, 0), { rw [fderiv_within_eq_fderiv, differentiable_at.fderiv_prod], { simp }, { exact differentiable_at_id' }, { exact differentiable_at_const _ }, { exact model_with_corners.unique_diff_at_image I }, { exact differentiable_at_id'.prod (differentiable_at_const _) } }, simp only [tangent_bundle.zero_section, tangent_map, mfderiv, A, dif_pos, chart_at, basic_smooth_bundle_core.chart, basic_smooth_bundle_core.to_topological_fiber_bundle_core, tangent_bundle_core, function.comp, continuous_linear_map.map_zero] with mfld_simps, rw ← fderiv_within_inter N (I.unique_diff (I ((chart_at H x) x)) (set.mem_range_self _)) at B, rw [← fderiv_within_inter N (I.unique_diff (I ((chart_at H x) x)) (set.mem_range_self _)), ← B], congr' 1, apply fderiv_within_congr _ (λ y hy, _), { simp only with mfld_simps, }, { apply unique_diff_within_at.inter (I.unique_diff _ _) N, simp only with mfld_simps }, { simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, end end tangent_bundle /-! ### Smoothness of standard maps associated to the product of manifolds -/ section prod_mk lemma times_cont_mdiff_within_at.prod_mk {f : M → M'} {g : M → N'} (hf : times_cont_mdiff_within_at I I' n f s x) (hg : times_cont_mdiff_within_at I J' n g s x) : times_cont_mdiff_within_at I (I'.prod J') n (λ x, (f x, g x)) s x := begin rw times_cont_mdiff_within_at_iff'' at *, exact ⟨hf.1.prod hg.1, hf.2.prod hg.2⟩, end lemma times_cont_mdiff_within_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : times_cont_mdiff_within_at I 𝓘(𝕜, E') n f s x) (hg : times_cont_mdiff_within_at I 𝓘(𝕜, F') n g s x) : times_cont_mdiff_within_at I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) s x := begin rw times_cont_mdiff_within_at_iff'' at *, exact ⟨hf.1.prod hg.1, hf.2.prod hg.2⟩, end lemma times_cont_mdiff_at.prod_mk {f : M → M'} {g : M → N'} (hf : times_cont_mdiff_at I I' n f x) (hg : times_cont_mdiff_at I J' n g x) : times_cont_mdiff_at I (I'.prod J') n (λ x, (f x, g x)) x := hf.prod_mk hg lemma times_cont_mdiff_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : times_cont_mdiff_at I 𝓘(𝕜, E') n f x) (hg : times_cont_mdiff_at I 𝓘(𝕜, F') n g x) : times_cont_mdiff_at I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) x := hf.prod_mk_space hg lemma times_cont_mdiff_on.prod_mk {f : M → M'} {g : M → N'} (hf : times_cont_mdiff_on I I' n f s) (hg : times_cont_mdiff_on I J' n g s) : times_cont_mdiff_on I (I'.prod J') n (λ x, (f x, g x)) s := λ x hx, (hf x hx).prod_mk (hg x hx) lemma times_cont_mdiff_on.prod_mk_space {f : M → E'} {g : M → F'} (hf : times_cont_mdiff_on I 𝓘(𝕜, E') n f s) (hg : times_cont_mdiff_on I 𝓘(𝕜, F') n g s) : times_cont_mdiff_on I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) s := λ x hx, (hf x hx).prod_mk_space (hg x hx) lemma times_cont_mdiff.prod_mk {f : M → M'} {g : M → N'} (hf : times_cont_mdiff I I' n f) (hg : times_cont_mdiff I J' n g) : times_cont_mdiff I (I'.prod J') n (λ x, (f x, g x)) := λ x, (hf x).prod_mk (hg x) lemma times_cont_mdiff.prod_mk_space {f : M → E'} {g : M → F'} (hf : times_cont_mdiff I 𝓘(𝕜, E') n f) (hg : times_cont_mdiff I 𝓘(𝕜, F') n g) : times_cont_mdiff I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) := λ x, (hf x).prod_mk_space (hg x) lemma smooth_within_at.prod_mk {f : M → M'} {g : M → N'} (hf : smooth_within_at I I' f s x) (hg : smooth_within_at I J' g s x) : smooth_within_at I (I'.prod J') (λ x, (f x, g x)) s x := hf.prod_mk hg lemma smooth_within_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth_within_at I 𝓘(𝕜, E') f s x) (hg : smooth_within_at I 𝓘(𝕜, F') g s x) : smooth_within_at I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) s x := hf.prod_mk_space hg lemma smooth_at.prod_mk {f : M → M'} {g : M → N'} (hf : smooth_at I I' f x) (hg : smooth_at I J' g x) : smooth_at I (I'.prod J') (λ x, (f x, g x)) x := hf.prod_mk hg lemma smooth_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth_at I 𝓘(𝕜, E') f x) (hg : smooth_at I 𝓘(𝕜, F') g x) : smooth_at I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) x := hf.prod_mk_space hg lemma smooth_on.prod_mk {f : M → M'} {g : M → N'} (hf : smooth_on I I' f s) (hg : smooth_on I J' g s) : smooth_on I (I'.prod J') (λ x, (f x, g x)) s := hf.prod_mk hg lemma smooth_on.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth_on I 𝓘(𝕜, E') f s) (hg : smooth_on I 𝓘(𝕜, F') g s) : smooth_on I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) s := hf.prod_mk_space hg lemma smooth.prod_mk {f : M → M'} {g : M → N'} (hf : smooth I I' f) (hg : smooth I J' g) : smooth I (I'.prod J') (λ x, (f x, g x)) := hf.prod_mk hg lemma smooth.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth I 𝓘(𝕜, E') f) (hg : smooth I 𝓘(𝕜, F') g) : smooth I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) := hf.prod_mk_space hg end prod_mk section projections lemma times_cont_mdiff_within_at_fst {s : set (M × N)} {p : M × N} : times_cont_mdiff_within_at (I.prod J) I n prod.fst s p := begin rw times_cont_mdiff_within_at_iff, refine ⟨continuous_within_at_fst, _⟩, refine times_cont_diff_within_at_fst.congr (λ y hy, _) _, { simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, { simp only with mfld_simps } end lemma times_cont_mdiff_at_fst {p : M × N} : times_cont_mdiff_at (I.prod J) I n prod.fst p := times_cont_mdiff_within_at_fst lemma times_cont_mdiff_on_fst {s : set (M × N)} : times_cont_mdiff_on (I.prod J) I n prod.fst s := λ x hx, times_cont_mdiff_within_at_fst lemma times_cont_mdiff_fst : times_cont_mdiff (I.prod J) I n (@prod.fst M N) := λ x, times_cont_mdiff_at_fst lemma smooth_within_at_fst {s : set (M × N)} {p : M × N} : smooth_within_at (I.prod J) I prod.fst s p := times_cont_mdiff_within_at_fst lemma smooth_at_fst {p : M × N} : smooth_at (I.prod J) I prod.fst p := times_cont_mdiff_at_fst lemma smooth_on_fst {s : set (M × N)} : smooth_on (I.prod J) I prod.fst s := times_cont_mdiff_on_fst lemma smooth_fst : smooth (I.prod J) I (@prod.fst M N) := times_cont_mdiff_fst lemma times_cont_mdiff_within_at_snd {s : set (M × N)} {p : M × N} : times_cont_mdiff_within_at (I.prod J) J n prod.snd s p := begin rw times_cont_mdiff_within_at_iff, refine ⟨continuous_within_at_snd, _⟩, refine times_cont_diff_within_at_snd.congr (λ y hy, _) _, { simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, { simp only with mfld_simps } end lemma times_cont_mdiff_at_snd {p : M × N} : times_cont_mdiff_at (I.prod J) J n prod.snd p := times_cont_mdiff_within_at_snd lemma times_cont_mdiff_on_snd {s : set (M × N)} : times_cont_mdiff_on (I.prod J) J n prod.snd s := λ x hx, times_cont_mdiff_within_at_snd lemma times_cont_mdiff_snd : times_cont_mdiff (I.prod J) J n (@prod.snd M N) := λ x, times_cont_mdiff_at_snd lemma smooth_within_at_snd {s : set (M × N)} {p : M × N} : smooth_within_at (I.prod J) J prod.snd s p := times_cont_mdiff_within_at_snd lemma smooth_at_snd {p : M × N} : smooth_at (I.prod J) J prod.snd p := times_cont_mdiff_at_snd lemma smooth_on_snd {s : set (M × N)} : smooth_on (I.prod J) J prod.snd s := times_cont_mdiff_on_snd lemma smooth_snd : smooth (I.prod J) J (@prod.snd M N) := times_cont_mdiff_snd lemma smooth_iff_proj_smooth {f : M → M' × N'} : (smooth I (I'.prod J') f) ↔ (smooth I I' (prod.fst ∘ f)) ∧ (smooth I J' (prod.snd ∘ f)) := begin split, { intro h, exact ⟨smooth_fst.comp h, smooth_snd.comp h⟩ }, { rintro ⟨h_fst, h_snd⟩, simpa only [prod.mk.eta] using h_fst.prod_mk h_snd, } end end projections section prod_map variables {g : N → N'} {r : set N} {y : N} /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_mdiff_within_at.prod_map' {p : M × N} (hf : times_cont_mdiff_within_at I I' n f s p.1) (hg : times_cont_mdiff_within_at J J' n g r p.2) : times_cont_mdiff_within_at (I.prod J) (I'.prod J') n (prod.map f g) (s.prod r) p := (hf.comp p times_cont_mdiff_within_at_fst (prod_subset_preimage_fst _ _)).prod_mk $ hg.comp p times_cont_mdiff_within_at_snd (prod_subset_preimage_snd _ _) lemma times_cont_mdiff_within_at.prod_map (hf : times_cont_mdiff_within_at I I' n f s x) (hg : times_cont_mdiff_within_at J J' n g r y) : times_cont_mdiff_within_at (I.prod J) (I'.prod J') n (prod.map f g) (s.prod r) (x, y) := times_cont_mdiff_within_at.prod_map' hf hg lemma times_cont_mdiff_at.prod_map (hf : times_cont_mdiff_at I I' n f x) (hg : times_cont_mdiff_at J J' n g y) : times_cont_mdiff_at (I.prod J) (I'.prod J') n (prod.map f g) (x, y) := begin rw ← times_cont_mdiff_within_at_univ at *, convert hf.prod_map hg, exact univ_prod_univ.symm end lemma times_cont_mdiff_at.prod_map' {p : M × N} (hf : times_cont_mdiff_at I I' n f p.1) (hg : times_cont_mdiff_at J J' n g p.2) : times_cont_mdiff_at (I.prod J) (I'.prod J') n (prod.map f g) p := begin rcases p, exact hf.prod_map hg end lemma times_cont_mdiff_on.prod_map (hf : times_cont_mdiff_on I I' n f s) (hg : times_cont_mdiff_on J J' n g r) : times_cont_mdiff_on (I.prod J) (I'.prod J') n (prod.map f g) (s.prod r) := (hf.comp times_cont_mdiff_on_fst (prod_subset_preimage_fst _ _)).prod_mk $ hg.comp (times_cont_mdiff_on_snd) (prod_subset_preimage_snd _ _) lemma times_cont_mdiff.prod_map (hf : times_cont_mdiff I I' n f) (hg : times_cont_mdiff J J' n g) : times_cont_mdiff (I.prod J) (I'.prod J') n (prod.map f g) := begin assume p, exact (hf p.1).prod_map' (hg p.2) end lemma smooth_within_at.prod_map (hf : smooth_within_at I I' f s x) (hg : smooth_within_at J J' g r y) : smooth_within_at (I.prod J) (I'.prod J') (prod.map f g) (s.prod r) (x, y) := hf.prod_map hg lemma smooth_at.prod_map (hf : smooth_at I I' f x) (hg : smooth_at J J' g y) : smooth_at (I.prod J) (I'.prod J') (prod.map f g) (x, y) := hf.prod_map hg lemma smooth_on.prod_map (hf : smooth_on I I' f s) (hg : smooth_on J J' g r) : smooth_on (I.prod J) (I'.prod J') (prod.map f g) (s.prod r) := hf.prod_map hg lemma smooth.prod_map (hf : smooth I I' f) (hg : smooth J J' g) : smooth (I.prod J) (I'.prod J') (prod.map f g) := hf.prod_map hg end prod_map section pi_space /-! ### Smoothness of functions with codomain `Π i, F i` We have no `model_with_corners.pi` yet, so we prove lemmas about functions `f : M → Π i, F i` and use `𝓘(𝕜, Π i, F i)` as the model space. -/ variables {ι : Type*} [fintype ι] {Fi : ι → Type*} [Π i, normed_group (Fi i)] [Π i, normed_space 𝕜 (Fi i)] {φ : M → Π i, Fi i} lemma times_cont_mdiff_within_at_pi_space : times_cont_mdiff_within_at I (𝓘(𝕜, Π i, Fi i)) n φ s x ↔ ∀ i, times_cont_mdiff_within_at I (𝓘(𝕜, Fi i)) n (λ x, φ x i) s x := by simp only [times_cont_mdiff_within_at_iff'', continuous_within_at_pi, times_cont_diff_within_at_pi, forall_and_distrib, written_in_ext_chart_at, ext_chart_model_space_eq_id, (∘), local_equiv.refl_coe, id] lemma times_cont_mdiff_on_pi_space : times_cont_mdiff_on I (𝓘(𝕜, Π i, Fi i)) n φ s ↔ ∀ i, times_cont_mdiff_on I (𝓘(𝕜, Fi i)) n (λ x, φ x i) s := ⟨λ h i x hx, times_cont_mdiff_within_at_pi_space.1 (h x hx) i, λ h x hx, times_cont_mdiff_within_at_pi_space.2 (λ i, h i x hx)⟩ lemma times_cont_mdiff_at_pi_space : times_cont_mdiff_at I (𝓘(𝕜, Π i, Fi i)) n φ x ↔ ∀ i, times_cont_mdiff_at I (𝓘(𝕜, Fi i)) n (λ x, φ x i) x := times_cont_mdiff_within_at_pi_space lemma times_cont_mdiff_pi_space : times_cont_mdiff I (𝓘(𝕜, Π i, Fi i)) n φ ↔ ∀ i, times_cont_mdiff I (𝓘(𝕜, Fi i)) n (λ x, φ x i) := ⟨λ h i x, times_cont_mdiff_at_pi_space.1 (h x) i, λ h x, times_cont_mdiff_at_pi_space.2 (λ i, h i x)⟩ lemma smooth_within_at_pi_space : smooth_within_at I (𝓘(𝕜, Π i, Fi i)) φ s x ↔ ∀ i, smooth_within_at I (𝓘(𝕜, Fi i)) (λ x, φ x i) s x := times_cont_mdiff_within_at_pi_space lemma smooth_on_pi_space : smooth_on I (𝓘(𝕜, Π i, Fi i)) φ s ↔ ∀ i, smooth_on I (𝓘(𝕜, Fi i)) (λ x, φ x i) s := times_cont_mdiff_on_pi_space lemma smooth_at_pi_space : smooth_at I (𝓘(𝕜, Π i, Fi i)) φ x ↔ ∀ i, smooth_at I (𝓘(𝕜, Fi i)) (λ x, φ x i) x := times_cont_mdiff_at_pi_space lemma smooth_pi_space : smooth I (𝓘(𝕜, Π i, Fi i)) φ ↔ ∀ i, smooth I (𝓘(𝕜, Fi i)) (λ x, φ x i) := times_cont_mdiff_pi_space end pi_space /-! ### Linear maps between normed spaces are smooth -/ lemma continuous_linear_map.times_cont_mdiff (L : E →L[𝕜] F) : times_cont_mdiff 𝓘(𝕜, E) 𝓘(𝕜, F) n L := L.times_cont_diff.times_cont_mdiff /-! ### Smoothness of standard operations -/ variables {V : Type*} [normed_group V] [normed_space 𝕜 V] /-- On any vector space, multiplication by a scalar is a smooth operation. -/ lemma smooth_smul : smooth (𝓘(𝕜).prod 𝓘(𝕜, V)) 𝓘(𝕜, V) (λp : 𝕜 × V, p.1 • p.2) := smooth_iff.2 ⟨continuous_smul, λ x y, times_cont_diff_smul.times_cont_diff_on⟩ lemma smooth.smul {N : Type*} [topological_space N] [charted_space H N] {f : N → 𝕜} {g : N → V} (hf : smooth I 𝓘(𝕜) f) (hg : smooth I 𝓘(𝕜, V) g) : smooth I 𝓘(𝕜, V) (λ p, f p • g p) := smooth_smul.comp (hf.prod_mk hg) lemma smooth_on.smul {N : Type*} [topological_space N] [charted_space H N] {f : N → 𝕜} {g : N → V} {s : set N} (hf : smooth_on I 𝓘(𝕜) f s) (hg : smooth_on I 𝓘(𝕜, V) g s) : smooth_on I 𝓘(𝕜, V) (λ p, f p • g p) s := smooth_smul.comp_smooth_on (hf.prod_mk hg) lemma smooth_at.smul {N : Type*} [topological_space N] [charted_space H N] {f : N → 𝕜} {g : N → V} {x : N} (hf : smooth_at I 𝓘(𝕜) f x) (hg : smooth_at I 𝓘(𝕜, V) g x) : smooth_at I 𝓘(𝕜, V) (λ p, f p • g p) x := smooth_smul.smooth_at.comp _ (hf.prod_mk hg)
5e2d4212a6f2ae2c8c9a116a253277239f33a24e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/star_subalgebra.lean
de1d13425fc142a73f660d7528a82c8f67f60f84
[ "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
9,154
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.star.subalgebra import topology.algebra.algebra import topology.algebra.star /-! # Topological star (sub)algebras A topological star algebra over a topological semiring `R` is a topological semiring with a compatible continuous scalar multiplication by elements of `R` and a continuous star operation. We reuse typeclass `has_continuous_smul` for topological algebras. ## Results This is just a minimal stub for now! The topological closure of a star subalgebra is still a star subalgebra, which as a star algebra is a topological star algebra. -/ open classical set topological_space open_locale classical namespace star_subalgebra section topological_star_algebra variables {R A B : Type*} [comm_semiring R] [star_ring R] variables [topological_space A] [semiring A] [algebra R A] [star_ring A] [star_module R A] instance [topological_space R] [has_continuous_smul R A] (s : star_subalgebra R A) : has_continuous_smul R s := s.to_subalgebra.has_continuous_smul instance [topological_semiring A] (s : star_subalgebra R A) : topological_semiring s := s.to_subalgebra.topological_semiring /-- The `star_subalgebra.inclusion` of a star subalgebra is an `embedding`. -/ lemma embedding_inclusion {S₁ S₂ : star_subalgebra R A} (h : S₁ ≤ S₂) : embedding (inclusion h) := { induced := eq.symm induced_compose, inj := subtype.map_injective h function.injective_id } /-- The `star_subalgebra.inclusion` of a closed star subalgebra is a `closed_embedding`. -/ lemma closed_embedding_inclusion {S₁ S₂ : star_subalgebra R A} (h : S₁ ≤ S₂) (hS₁ : is_closed (S₁ : set A)) : closed_embedding (inclusion h) := { closed_range := is_closed_induced_iff.2 ⟨S₁, hS₁, by { convert (set.range_subtype_map id _).symm, rw set.image_id, refl }⟩, .. embedding_inclusion h } variables [topological_semiring A] [has_continuous_star A] variables [topological_space B] [semiring B] [algebra R B] [star_ring B ] /-- The closure of a star subalgebra in a topological star algebra as a star subalgebra. -/ def topological_closure (s : star_subalgebra R A) : star_subalgebra R A := { carrier := closure (s : set A), star_mem' := λ a ha, map_mem_closure continuous_star ha (λ x, (star_mem : x ∈ s → star x ∈ s)), .. s.to_subalgebra.topological_closure } @[simp] lemma topological_closure_coe (s : star_subalgebra R A) : (s.topological_closure : set A) = closure (s : set A) := rfl lemma le_topological_closure (s : star_subalgebra R A) : s ≤ s.topological_closure := subset_closure lemma is_closed_topological_closure (s : star_subalgebra R A) : is_closed (s.topological_closure : set A) := is_closed_closure instance {A : Type*} [uniform_space A] [complete_space A] [semiring A] [star_ring A] [topological_semiring A] [has_continuous_star A] [algebra R A] [star_module R A] {S : star_subalgebra R A} : complete_space S.topological_closure := is_closed_closure.complete_space_coe lemma topological_closure_minimal {s t : star_subalgebra R A} (h : s ≤ t) (ht : is_closed (t : set A)) : s.topological_closure ≤ t := closure_minimal h ht lemma topological_closure_mono : monotone (topological_closure : _ → star_subalgebra R A) := λ S₁ S₂ h, topological_closure_minimal (h.trans $ le_topological_closure S₂) (is_closed_topological_closure S₂) /-- If a star subalgebra of a topological star algebra is commutative, then so is its topological closure. See note [reducible non-instances]. -/ @[reducible] def comm_semiring_topological_closure [t2_space A] (s : star_subalgebra R A) (hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure := s.to_subalgebra.comm_semiring_topological_closure hs /-- If a star subalgebra of a topological star algebra is commutative, then so is its topological closure. See note [reducible non-instances]. -/ @[reducible] def comm_ring_topological_closure {R A} [comm_ring R] [star_ring R] [topological_space A] [ring A] [algebra R A] [star_ring A] [star_module R A] [topological_ring A] [has_continuous_star A] [t2_space A] (s : star_subalgebra R A) (hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure := s.to_subalgebra.comm_ring_topological_closure hs /-- Continuous `star_alg_hom`s from the the topological closure of a `star_subalgebra` whose compositions with the `star_subalgebra.inclusion` map agree are, in fact, equal. -/ lemma _root_.star_alg_hom.ext_topological_closure [t2_space B] {S : star_subalgebra R A} {φ ψ : S.topological_closure →⋆ₐ[R] B} (hφ : continuous φ) (hψ : continuous ψ) (h : φ.comp (inclusion (le_topological_closure S)) = ψ.comp (inclusion (le_topological_closure S))) : φ = ψ := begin rw fun_like.ext'_iff, have : dense (set.range $ inclusion (le_topological_closure S)), { refine embedding_subtype_coe.to_inducing.dense_iff.2 (λ x, _), convert (show ↑x ∈ closure (S : set A), from x.prop), rw ←set.range_comp, exact set.ext (λ y, ⟨by { rintro ⟨y, rfl⟩, exact y.prop }, λ hy, ⟨⟨y, hy⟩, rfl⟩⟩), }, refine continuous.ext_on this hφ hψ _, rintro _ ⟨x, rfl⟩, simpa only using fun_like.congr_fun h x, end lemma _root_.star_alg_hom_class.ext_topological_closure [t2_space B] {F : Type*} {S : star_subalgebra R A} [star_alg_hom_class F R S.topological_closure B] {φ ψ : F} (hφ : continuous φ) (hψ : continuous ψ) (h : ∀ x : S, φ ((inclusion (le_topological_closure S) x)) = ψ ((inclusion (le_topological_closure S)) x)) : φ = ψ := begin have : (φ : S.topological_closure →⋆ₐ[R] B) = (ψ : S.topological_closure →⋆ₐ[R] B), { refine star_alg_hom.ext_topological_closure hφ hψ (star_alg_hom.ext _); simpa only [star_alg_hom.coe_comp, star_alg_hom.coe_coe] using h }, simpa only [fun_like.ext'_iff, star_alg_hom.coe_coe], end end topological_star_algebra end star_subalgebra section elemental open star_subalgebra variables (R : Type*) {A B : Type*} [comm_semiring R] [star_ring R] variables [topological_space A] [semiring A] [star_ring A] [topological_semiring A] variables [has_continuous_star A] [algebra R A] [star_module R A] variables [topological_space B] [semiring B] [star_ring B] [algebra R B] /-- The topological closure of the subalgebra generated by a single element. -/ def elemental_star_algebra (x : A) : star_subalgebra R A := (adjoin R ({x} : set A)).topological_closure namespace elemental_star_algebra lemma self_mem (x : A) : x ∈ elemental_star_algebra R x := set_like.le_def.mp (le_topological_closure _) (self_mem_adjoin_singleton R x) lemma star_self_mem (x : A) : star x ∈ elemental_star_algebra R x := star_mem $ self_mem R x /-- The `elemental_star_algebra` generated by a normal element is commutative. -/ instance [t2_space A] {x : A} [is_star_normal x] : comm_semiring (elemental_star_algebra R x) := star_subalgebra.comm_semiring_topological_closure _ mul_comm /-- The `elemental_star_algebra` generated by a normal element is commutative. -/ instance {R A} [comm_ring R] [star_ring R] [topological_space A] [ring A] [algebra R A] [star_ring A] [star_module R A] [topological_ring A] [has_continuous_star A] [t2_space A] {x : A} [is_star_normal x] : comm_ring (elemental_star_algebra R x) := star_subalgebra.comm_ring_topological_closure _ mul_comm protected lemma is_closed (x : A) : is_closed (elemental_star_algebra R x : set A) := is_closed_closure instance {A : Type*} [uniform_space A] [complete_space A] [semiring A] [star_ring A] [topological_semiring A] [has_continuous_star A] [algebra R A] [star_module R A] (x : A) : complete_space (elemental_star_algebra R x) := is_closed_closure.complete_space_coe lemma le_of_is_closed_of_mem {S : star_subalgebra R A} (hS : is_closed (S : set A)) {x : A} (hx : x ∈ S) : elemental_star_algebra R x ≤ S := topological_closure_minimal (adjoin_le $ set.singleton_subset_iff.2 hx) hS /-- The coercion from an elemental algebra to the full algebra as a `closed_embedding`. -/ lemma closed_embedding_coe (x : A) : closed_embedding (coe : elemental_star_algebra R x → A) := { induced := rfl, inj := subtype.coe_injective, closed_range := begin convert elemental_star_algebra.is_closed R x, exact set.ext (λ y, ⟨by {rintro ⟨y, rfl⟩, exact y.prop}, λ hy, ⟨⟨y, hy⟩, rfl⟩⟩), end } lemma star_alg_hom_class_ext [t2_space B] {F : Type*} {a : A} [star_alg_hom_class F R (elemental_star_algebra R a) B] {φ ψ : F} (hφ : continuous φ) (hψ : continuous ψ) (h : φ ⟨a, self_mem R a⟩ = ψ ⟨a, self_mem R a⟩) : φ = ψ := begin refine star_alg_hom_class.ext_topological_closure hφ hψ (λ x, adjoin_induction' x _ _ _ _ _), exacts [λ y hy, by simpa only [set.mem_singleton_iff.mp hy] using h, λ r, by simp only [alg_hom_class.commutes], λ x y hx hy, by simp only [map_add, hx, hy], λ x y hx hy, by simp only [map_mul, hx, hy], λ x hx, by simp only [map_star, hx]], end end elemental_star_algebra end elemental
0a7f0f4e47fe25837fb7f4be3616c6c3051ebb28
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/strong_law.lean
53020a09142fa828eb30f86ca8a99ac6d47154d5
[ "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
37,089
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 probability.ident_distrib import measure_theory.integral.interval_integral import analysis.specific_limits.floor_pow import analysis.p_series import analysis.asymptotics.specific_asymptotics /-! # The strong law of large numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We prove the strong law of large numbers, in `probability_theory.strong_law_ae`: If `X n` is a sequence of independent identically distributed integrable real-valued random variables, then `∑ i in range n, X i / n` converges almost surely to `𝔼[X 0]`. We give here the strong version, due to Etemadi, that only requires pairwise independence. This file also contains the Lᵖ version of the strong law of large numbers provided by `probability_theory.strong_law_Lp` which shows `∑ i in range n, X i / n` converges in Lᵖ to `𝔼[X 0]` provided `X n` is independent identically distributed and is Lᵖ. ## Implementation We follow the proof by Etemadi [Etemadi, *An elementary proof of the strong law of large numbers*][etemadi_strong_law], which goes as follows. It suffices to prove the result for nonnegative `X`, as one can prove the general result by splitting a general `X` into its positive part and negative part. Consider `Xₙ` a sequence of nonnegative integrable identically distributed pairwise independent random variables. Let `Yₙ` be the truncation of `Xₙ` up to `n`. We claim that * Almost surely, `Xₙ = Yₙ` for all but finitely many indices. Indeed, `∑ ℙ (Xₙ ≠ Yₙ)` is bounded by `1 + 𝔼[X]` (see `sum_prob_mem_Ioc_le` and `tsum_prob_mem_Ioi_lt_top`). * Let `c > 1`. Along the sequence `n = c ^ k`, then `(∑_{i=0}^{n-1} Yᵢ - 𝔼[Yᵢ])/n` converges almost surely to `0`. This follows from a variance control, as ``` ∑_k ℙ (|∑_{i=0}^{c^k - 1} Yᵢ - 𝔼[Yᵢ]| > c^k ε) ≤ ∑_k (c^k ε)^{-2} ∑_{i=0}^{c^k - 1} Var[Yᵢ] (by Markov inequality) ≤ ∑_i (C/i^2) Var[Yᵢ] (as ∑_{c^k > i} 1/(c^k)^2 ≤ C/i^2) ≤ ∑_i (C/i^2) 𝔼[Yᵢ^2] ≤ 2C 𝔼[X^2] (see `sum_variance_truncation_le`) ``` * As `𝔼[Yᵢ]` converges to `𝔼[X]`, it follows from the two previous items and Cesaro that, along the sequence `n = c^k`, one has `(∑_{i=0}^{n-1} Xᵢ) / n → 𝔼[X]` almost surely. * To generalize it to all indices, we use the fact that `∑_{i=0}^{n-1} Xᵢ` is nondecreasing and that, if `c` is close enough to `1`, the gap between `c^k` and `c^(k+1)` is small. -/ noncomputable theory open measure_theory filter finset asymptotics open set (indicator) open_locale topology big_operators measure_theory probability_theory ennreal nnreal namespace probability_theory /-! ### Prerequisites on truncations -/ section truncation variables {α : Type*} /-- Truncating a real-valued function to the interval `(-A, A]`. -/ def truncation (f : α → ℝ) (A : ℝ) := (indicator (set.Ioc (-A) A) id) ∘ f variables {m : measurable_space α} {μ : measure α} {f : α → ℝ} lemma _root_.measure_theory.ae_strongly_measurable.truncation (hf : ae_strongly_measurable f μ) {A : ℝ} : ae_strongly_measurable (truncation f A) μ := begin apply ae_strongly_measurable.comp_ae_measurable _ hf.ae_measurable, exact (strongly_measurable_id.indicator measurable_set_Ioc).ae_strongly_measurable, end lemma abs_truncation_le_bound (f : α → ℝ) (A : ℝ) (x : α) : |truncation f A x| ≤ |A| := begin simp only [truncation, set.indicator, set.mem_Icc, id.def, function.comp_app], split_ifs, { exact abs_le_abs h.2 (neg_le.2 h.1.le) }, { simp [abs_nonneg] } end @[simp] lemma truncation_zero (f : α → ℝ) : truncation f 0 = 0 := by simp [truncation] lemma abs_truncation_le_abs_self (f : α → ℝ) (A : ℝ) (x : α) : |truncation f A x| ≤ |f x| := begin simp only [truncation, indicator, set.mem_Icc, id.def, function.comp_app], split_ifs, { exact le_rfl }, { simp [abs_nonneg] }, end lemma truncation_eq_self {f : α → ℝ} {A : ℝ} {x : α} (h : |f x| < A) : truncation f A x = f x := begin simp only [truncation, indicator, set.mem_Icc, id.def, function.comp_app, ite_eq_left_iff], assume H, apply H.elim, simp [(abs_lt.1 h).1, (abs_lt.1 h).2.le], end lemma truncation_eq_of_nonneg {f : α → ℝ} {A : ℝ} (h : ∀ x, 0 ≤ f x) : truncation f A = (indicator (set.Ioc 0 A) id) ∘ f := begin ext x, rcases (h x).lt_or_eq with hx|hx, { simp only [truncation, indicator, hx, set.mem_Ioc, id.def, function.comp_app, true_and], by_cases h'x : f x ≤ A, { have : - A < f x, by linarith [h x], simp only [this, true_and] }, { simp only [h'x, and_false] } }, { simp only [truncation, indicator, hx, id.def, function.comp_app, if_t_t]}, end lemma truncation_nonneg {f : α → ℝ} (A : ℝ) {x : α} (h : 0 ≤ f x) : 0 ≤ truncation f A x := set.indicator_apply_nonneg $ λ _, h lemma _root_.measure_theory.ae_strongly_measurable.mem_ℒp_truncation [is_finite_measure μ] (hf : ae_strongly_measurable f μ) {A : ℝ} {p : ℝ≥0∞} : mem_ℒp (truncation f A) p μ := mem_ℒp.of_bound hf.truncation (|A|) (eventually_of_forall (λ x, abs_truncation_le_bound _ _ _)) lemma _root_.measure_theory.ae_strongly_measurable.integrable_truncation [is_finite_measure μ] (hf : ae_strongly_measurable f μ) {A : ℝ} : integrable (truncation f A) μ := by { rw ← mem_ℒp_one_iff_integrable, exact hf.mem_ℒp_truncation } lemma moment_truncation_eq_interval_integral (hf : ae_strongly_measurable f μ) {A : ℝ} (hA : 0 ≤ A) {n : ℕ} (hn : n ≠ 0) : ∫ x, (truncation f A x) ^ n ∂μ = ∫ y in (-A)..A, y ^ n ∂(measure.map f μ) := begin have M : measurable_set (set.Ioc (-A) A) := measurable_set_Ioc, change ∫ x, (λ z, (indicator (set.Ioc (-A) A) id z) ^ n) (f x) ∂μ = _, rw [← integral_map hf.ae_measurable, interval_integral.integral_of_le, ← integral_indicator M], { simp only [indicator, zero_pow' _ hn, id.def, ite_pow] }, { linarith }, { exact ((measurable_id.indicator M).pow_const n).ae_strongly_measurable } end lemma moment_truncation_eq_interval_integral_of_nonneg (hf : ae_strongly_measurable f μ) {A : ℝ} {n : ℕ} (hn : n ≠ 0) (h'f : 0 ≤ f) : ∫ x, (truncation f A x) ^ n ∂μ = ∫ y in 0..A, y ^ n ∂(measure.map f μ) := begin have M : measurable_set (set.Ioc 0 A) := measurable_set_Ioc, have M' : measurable_set (set.Ioc A 0) := measurable_set_Ioc, rw truncation_eq_of_nonneg h'f, change ∫ x, (λ z, (indicator (set.Ioc 0 A) id z) ^ n) (f x) ∂μ = _, rcases le_or_lt 0 A with hA | hA, { rw [← integral_map hf.ae_measurable, interval_integral.integral_of_le hA, ← integral_indicator M], { simp only [indicator, zero_pow' _ hn, id.def, ite_pow] }, { exact ((measurable_id.indicator M).pow_const n).ae_strongly_measurable } }, { rw [← integral_map hf.ae_measurable, interval_integral.integral_of_ge hA.le, ← integral_indicator M'], { simp only [set.Ioc_eq_empty_of_le hA.le, zero_pow' _ hn, set.indicator_empty, integral_zero, zero_eq_neg], apply integral_eq_zero_of_ae, have : ∀ᵐ x ∂(measure.map f μ), (0 : ℝ) ≤ x := (ae_map_iff hf.ae_measurable measurable_set_Ici).2 (eventually_of_forall h'f), filter_upwards [this] with x hx, simp only [indicator, set.mem_Ioc, pi.zero_apply, ite_eq_right_iff, and_imp], assume h'x h''x, have : x = 0, by linarith, simp [this, zero_pow' _ hn] }, { exact ((measurable_id.indicator M).pow_const n).ae_strongly_measurable } } end lemma integral_truncation_eq_interval_integral (hf : ae_strongly_measurable f μ) {A : ℝ} (hA : 0 ≤ A) : ∫ x, truncation f A x ∂μ = ∫ y in (-A)..A, y ∂(measure.map f μ) := by simpa using moment_truncation_eq_interval_integral hf hA one_ne_zero lemma integral_truncation_eq_interval_integral_of_nonneg (hf : ae_strongly_measurable f μ) {A : ℝ} (h'f : 0 ≤ f) : ∫ x, truncation f A x ∂μ = ∫ y in 0..A, y ∂(measure.map f μ) := by simpa using moment_truncation_eq_interval_integral_of_nonneg hf one_ne_zero h'f lemma integral_truncation_le_integral_of_nonneg (hf : integrable f μ) (h'f : 0 ≤ f) {A : ℝ} : ∫ x, truncation f A x ∂μ ≤ ∫ x, f x ∂μ := begin apply integral_mono_of_nonneg (eventually_of_forall (λ x, _)) hf (eventually_of_forall (λ x, _)), { exact truncation_nonneg _ (h'f x) }, { calc truncation f A x ≤ |truncation f A x| : le_abs_self _ ... ≤ |f x| : abs_truncation_le_abs_self _ _ _ ... = f x : abs_of_nonneg (h'f x) } end /-- If a function is integrable, then the integral of its truncated versions converges to the integral of the whole function. -/ lemma tendsto_integral_truncation {f : α → ℝ} (hf : integrable f μ) : tendsto (λ A, ∫ x, truncation f A x ∂μ) at_top (𝓝 (∫ x, f x ∂μ)) := begin refine tendsto_integral_filter_of_dominated_convergence (λ x, abs (f x)) _ _ _ _, { exact eventually_of_forall (λ A, hf.ae_strongly_measurable.truncation) }, { apply eventually_of_forall (λ A, _), apply eventually_of_forall (λ x, _), rw real.norm_eq_abs, exact abs_truncation_le_abs_self _ _ _ }, { apply hf.abs }, { apply eventually_of_forall (λ x, _), apply tendsto_const_nhds.congr' _, filter_upwards [Ioi_mem_at_top (abs (f x))] with A hA, exact (truncation_eq_self hA).symm }, end lemma ident_distrib.truncation {β : Type*} [measurable_space β] {ν : measure β} {f : α → ℝ} {g : β → ℝ} (h : ident_distrib f g μ ν) {A : ℝ} : ident_distrib (truncation f A) (truncation g A) μ ν := h.comp (measurable_id.indicator measurable_set_Ioc) end truncation section strong_law_ae variables {Ω : Type*} [measure_space Ω] [is_probability_measure (ℙ : measure Ω)] section moment_estimates lemma sum_prob_mem_Ioc_le {X : Ω → ℝ} (hint : integrable X) (hnonneg : 0 ≤ X) {K : ℕ} {N : ℕ} (hKN : K ≤ N) : ∑ j in range K, ℙ {ω | X ω ∈ set.Ioc (j : ℝ) N} ≤ ennreal.of_real (𝔼[X] + 1) := begin let ρ : measure ℝ := measure.map X ℙ, haveI : is_probability_measure ρ := is_probability_measure_map hint.ae_measurable, have A : ∑ j in range K, ∫ x in j..N, (1 : ℝ) ∂ρ ≤ 𝔼[X] + 1, from calc ∑ j in range K, ∫ x in j..N, (1 : ℝ) ∂ρ = ∑ j in range K, ∑ i in Ico j N, ∫ x in i..(i+1 : ℕ), (1 : ℝ) ∂ρ : begin apply sum_congr rfl (λ j hj, _), rw interval_integral.sum_integral_adjacent_intervals_Ico ((mem_range.1 hj).le.trans hKN), assume k hk, exact continuous_const.interval_integrable _ _, end ... = ∑ i in range N, ∑ j in range (min (i+1) K), ∫ x in i..(i+1 : ℕ), (1 : ℝ) ∂ρ : begin simp_rw [sum_sigma'], refine sum_bij' (λ (p : (Σ (i : ℕ), ℕ)) hp, (⟨p.2, p.1⟩ : (Σ (i : ℕ), ℕ))) _ (λ a ha, rfl) (λ (p : (Σ (i : ℕ), ℕ)) hp, (⟨p.2, p.1⟩ : (Σ (i : ℕ), ℕ))) _ _ _, { rintros ⟨i, j⟩ hij, simp only [mem_sigma, mem_range, mem_Ico] at hij, simp only [hij, nat.lt_succ_iff.2 hij.2.1, mem_sigma, mem_range, lt_min_iff, and_self] }, { rintros ⟨i, j⟩ hij, simp only [mem_sigma, mem_range, lt_min_iff] at hij, simp only [hij, nat.lt_succ_iff.1 hij.2.1, mem_sigma, mem_range, mem_Ico, and_self] }, { rintros ⟨i, j⟩ hij, refl }, { rintros ⟨i, j⟩ hij, refl }, end ... ≤ ∑ i in range N, (i + 1) * ∫ x in i..(i+1 : ℕ), (1 : ℝ) ∂ρ : begin apply sum_le_sum (λ i hi, _), simp only [nat.cast_add, nat.cast_one, sum_const, card_range, nsmul_eq_mul, nat.cast_min], refine mul_le_mul_of_nonneg_right (min_le_left _ _) _, apply interval_integral.integral_nonneg, { simp only [le_add_iff_nonneg_right, zero_le_one] }, { simp only [zero_le_one, implies_true_iff], } end ... ≤ ∑ i in range N, ∫ x in i..(i+1 : ℕ), (x + 1) ∂ρ : begin apply sum_le_sum (λ i hi, _), have I : (i : ℝ) ≤ (i + 1 : ℕ), by simp only [nat.cast_add, nat.cast_one, le_add_iff_nonneg_right, zero_le_one], simp_rw [interval_integral.integral_of_le I, ← integral_mul_left], apply set_integral_mono_on, { exact continuous_const.integrable_on_Ioc }, { exact (continuous_id.add continuous_const).integrable_on_Ioc }, { exact measurable_set_Ioc }, { assume x hx, simp only [nat.cast_add, nat.cast_one, set.mem_Ioc] at hx, simp [hx.1.le] } end ... = ∫ x in 0..N, x + 1 ∂ρ : begin rw interval_integral.sum_integral_adjacent_intervals (λ k hk, _), { norm_cast }, { exact (continuous_id.add continuous_const).interval_integrable _ _ } end ... = ∫ x in 0..N, x ∂ρ + ∫ x in 0..N, 1 ∂ρ : begin rw interval_integral.integral_add, { exact continuous_id.interval_integrable _ _ }, { exact continuous_const.interval_integrable _ _ }, end ... = 𝔼[truncation X N] + ∫ x in 0..N, 1 ∂ρ : by rw integral_truncation_eq_interval_integral_of_nonneg hint.1 hnonneg ... ≤ 𝔼[X] + ∫ x in 0..N, 1 ∂ρ : add_le_add_right (integral_truncation_le_integral_of_nonneg hint hnonneg) _ ... ≤ 𝔼[X] + 1 : begin refine add_le_add le_rfl _, rw interval_integral.integral_of_le (nat.cast_nonneg _), simp only [integral_const, measure.restrict_apply', measurable_set_Ioc, set.univ_inter, algebra.id.smul_eq_mul, mul_one], rw ← ennreal.one_to_real, exact ennreal.to_real_mono ennreal.one_ne_top prob_le_one, end, have B : ∀ a b, ℙ {ω | X ω ∈ set.Ioc a b} = ennreal.of_real (∫ x in set.Ioc a b, (1 : ℝ) ∂ρ), { assume a b, rw [of_real_set_integral_one ρ _, measure.map_apply_of_ae_measurable hint.ae_measurable measurable_set_Ioc], refl }, calc ∑ j in range K, ℙ {ω | X ω ∈ set.Ioc (j : ℝ) N} = ∑ j in range K, ennreal.of_real (∫ x in set.Ioc (j : ℝ) N, (1 : ℝ) ∂ρ) : by simp_rw B ... = ennreal.of_real (∑ j in range K, ∫ x in set.Ioc (j : ℝ) N, (1 : ℝ) ∂ρ) : begin rw ennreal.of_real_sum_of_nonneg, simp only [integral_const, algebra.id.smul_eq_mul, mul_one, ennreal.to_real_nonneg, implies_true_iff], end ... = ennreal.of_real (∑ j in range K, ∫ x in (j : ℝ)..N, (1 : ℝ) ∂ρ) : begin congr' 1, refine sum_congr rfl (λ j hj, _), rw interval_integral.integral_of_le (nat.cast_le.2 ((mem_range.1 hj).le.trans hKN)), end ... ≤ ennreal.of_real (𝔼[X] + 1) : ennreal.of_real_le_of_real A end lemma tsum_prob_mem_Ioi_lt_top {X : Ω → ℝ} (hint : integrable X) (hnonneg : 0 ≤ X) : ∑' (j : ℕ), ℙ {ω | X ω ∈ set.Ioi (j : ℝ)} < ∞ := begin suffices : ∀ (K : ℕ), ∑ j in range K, ℙ {ω | X ω ∈ set.Ioi (j : ℝ)} ≤ ennreal.of_real (𝔼[X] + 1), from (le_of_tendsto_of_tendsto (ennreal.tendsto_nat_tsum _) tendsto_const_nhds (eventually_of_forall this)).trans_lt ennreal.of_real_lt_top, assume K, have A : tendsto (λ (N : ℕ), ∑ j in range K, ℙ {ω | X ω ∈ set.Ioc (j : ℝ) N}) at_top (𝓝 (∑ j in range K, ℙ {ω | X ω ∈ set.Ioi (j : ℝ)})), { refine tendsto_finset_sum _ (λ i hi, _), have : {ω | X ω ∈ set.Ioi (i : ℝ)} = ⋃ (N : ℕ), {ω | X ω ∈ set.Ioc (i : ℝ) N}, { apply set.subset.antisymm _ _, { assume ω hω, obtain ⟨N, hN⟩ : ∃ (N : ℕ), X ω ≤ N := exists_nat_ge (X ω), exact set.mem_Union.2 ⟨N, hω, hN⟩ }, { simp only [set.mem_Ioc, set.mem_Ioi, set.Union_subset_iff, set.set_of_subset_set_of, implies_true_iff] {contextual := tt} } }, rw this, apply tendsto_measure_Union, assume m n hmn x hx, exact ⟨hx.1, hx.2.trans (nat.cast_le.2 hmn)⟩ }, apply le_of_tendsto_of_tendsto A tendsto_const_nhds, filter_upwards [Ici_mem_at_top K] with N hN, exact sum_prob_mem_Ioc_le hint hnonneg hN end lemma sum_variance_truncation_le {X : Ω → ℝ} (hint : integrable X) (hnonneg : 0 ≤ X) (K : ℕ) : ∑ j in range K, ((j : ℝ) ^ 2) ⁻¹ * 𝔼[(truncation X j) ^ 2] ≤ 2 * 𝔼[X] := begin set Y := λ (n : ℕ), truncation X n, let ρ : measure ℝ := measure.map X ℙ, have Y2 : ∀ n, 𝔼[Y n ^ 2] = ∫ x in 0..n, x ^ 2 ∂ρ, { assume n, change 𝔼[λ x, (Y n x)^2] = _, rw [moment_truncation_eq_interval_integral_of_nonneg hint.1 two_ne_zero hnonneg] }, calc ∑ j in range K, ((j : ℝ) ^ 2) ⁻¹ * 𝔼[Y j ^ 2] = ∑ j in range K, ((j : ℝ) ^ 2) ⁻¹ * ∫ x in 0..j, x ^ 2 ∂ρ : by simp_rw [Y2] ... = ∑ j in range K, ((j : ℝ) ^ 2) ⁻¹ * ∑ k in range j, ∫ x in k..(k+1 : ℕ), x ^ 2 ∂ρ : begin congr' 1 with j, congr' 1, rw interval_integral.sum_integral_adjacent_intervals, { norm_cast }, assume k hk, exact (continuous_id.pow _).interval_integrable _ _, end ... = ∑ k in range K, (∑ j in Ioo k K, ((j : ℝ) ^ 2) ⁻¹) * ∫ x in k..(k+1 : ℕ), x ^ 2 ∂ρ : begin simp_rw [mul_sum, sum_mul, sum_sigma'], refine sum_bij' (λ (p : (Σ (i : ℕ), ℕ)) hp, (⟨p.2, p.1⟩ : (Σ (i : ℕ), ℕ))) _ (λ a ha, rfl) (λ (p : (Σ (i : ℕ), ℕ)) hp, (⟨p.2, p.1⟩ : (Σ (i : ℕ), ℕ))) _ _ _, { rintros ⟨i, j⟩ hij, simp only [mem_sigma, mem_range, mem_filter] at hij, simp [hij, mem_sigma, mem_range, and_self, hij.2.trans hij.1], }, { rintros ⟨i, j⟩ hij, simp only [mem_sigma, mem_range, mem_Ioo] at hij, simp only [hij, mem_sigma, mem_range, and_self], }, { rintros ⟨i, j⟩ hij, refl }, { rintros ⟨i, j⟩ hij, refl }, end ... ≤ ∑ k in range K, (2/ (k+1)) * ∫ x in k..(k+1 : ℕ), x ^ 2 ∂ρ : begin apply sum_le_sum (λ k hk, _), refine mul_le_mul_of_nonneg_right (sum_Ioo_inv_sq_le _ _) _, refine interval_integral.integral_nonneg_of_forall _ (λ u, sq_nonneg _), simp only [nat.cast_add, nat.cast_one, le_add_iff_nonneg_right, zero_le_one], end ... ≤ ∑ k in range K, ∫ x in k..(k+1 : ℕ), 2 * x ∂ρ : begin apply sum_le_sum (λ k hk, _), have Ik : (k : ℝ) ≤ (k + 1 : ℕ), by simp, rw [← interval_integral.integral_const_mul, interval_integral.integral_of_le Ik, interval_integral.integral_of_le Ik], refine set_integral_mono_on _ _ measurable_set_Ioc (λ x hx, _), { apply continuous.integrable_on_Ioc, exact continuous_const.mul (continuous_pow 2) }, { apply continuous.integrable_on_Ioc, exact continuous_const.mul continuous_id' }, { calc 2 / (↑k + 1) * x ^ 2 = (x / (k+1)) * (2 * x) : by ring_exp ... ≤ 1 * (2 * x) : mul_le_mul_of_nonneg_right begin apply_mod_cast (div_le_one _).2 hx.2, simp only [nat.cast_add, nat.cast_one], linarith only [show (0 : ℝ) ≤ k, from nat.cast_nonneg k], end (mul_nonneg zero_le_two ((nat.cast_nonneg k).trans hx.1.le)) ... = 2 * x : by rw one_mul } end ... = 2 * ∫ x in (0 : ℝ)..K, x ∂ρ : begin rw interval_integral.sum_integral_adjacent_intervals (λ k hk, _), swap, { exact (continuous_const.mul continuous_id').interval_integrable _ _ }, rw interval_integral.integral_const_mul, norm_cast end ... ≤ 2 * 𝔼[X] : mul_le_mul_of_nonneg_left begin rw ← integral_truncation_eq_interval_integral_of_nonneg hint.1 hnonneg, exact integral_truncation_le_integral_of_nonneg hint hnonneg, end zero_le_two end end moment_estimates section strong_law_nonneg /- This paragraph proves the strong law of large numbers (almost sure version, assuming only pairwise independence) for nonnegative random variables, following Etemadi's proof. -/ variables (X : ℕ → Ω → ℝ) (hint : integrable (X 0)) (hindep : pairwise (λ i j, indep_fun (X i) (X j))) (hident : ∀ i, ident_distrib (X i) (X 0)) (hnonneg : ∀ i ω, 0 ≤ X i ω) include X hint hindep hident hnonneg /- The truncation of `Xᵢ` up to `i` satisfies the strong law of large numbers (with respect to the truncated expectation) along the sequence `c^n`, for any `c > 1`, up to a given `ε > 0`. This follows from a variance control. -/ lemma strong_law_aux1 {c : ℝ} (c_one : 1 < c) {ε : ℝ} (εpos : 0 < ε) : ∀ᵐ ω, ∀ᶠ (n : ℕ) in at_top, |∑ i in range ⌊c^n⌋₊, truncation (X i) i ω - 𝔼[∑ i in range ⌊c^n⌋₊, truncation (X i) i]| < ε * ⌊c^n⌋₊ := begin /- Let `S n = ∑ i in range n, Y i` where `Y i = truncation (X i) i`. We should show that `|S k - 𝔼[S k]| / k ≤ ε` along the sequence of powers of `c`. For this, we apply Borel-Cantelli: it suffices to show that the converse probabilites are summable. From Chebyshev inequality, this will follow from a variance control `∑' Var[S (c^i)] / (c^i)^2 < ∞`. This is checked in `I2` using pairwise independence to expand the variance of the sum as the sum of the variances, and then a straightforward but tedious computation (essentially boiling down to the fact that the sum of `1/(c ^ i)^2` beyong a threshold `j` is comparable to `1/j^2`). Note that we have written `c^i` in the above proof sketch, but rigorously one should put integer parts everywhere, making things more painful. We write `u i = ⌊c^i⌋₊` for brevity. -/ have c_pos : 0 < c := zero_lt_one.trans c_one, let ρ : measure ℝ := measure.map (X 0) ℙ, have hX : ∀ i, ae_strongly_measurable (X i) ℙ := λ i, (hident i).symm.ae_strongly_measurable_snd hint.1, have A : ∀ i, strongly_measurable (indicator (set.Ioc (-i : ℝ) i) id) := λ i, strongly_measurable_id.indicator measurable_set_Ioc, set Y := λ (n : ℕ), truncation (X n) n with hY, set S := λ n, ∑ i in range n, Y i with hS, let u : ℕ → ℕ := λ n, ⌊c ^ n⌋₊, have u_mono : monotone u := λ i j hij, nat.floor_mono (pow_le_pow c_one.le hij), have I1 : ∀ K, ∑ j in range K, ((j : ℝ) ^ 2) ⁻¹ * Var[Y j] ≤ 2 * 𝔼[X 0], { assume K, calc ∑ j in range K, ((j : ℝ) ^ 2) ⁻¹ * Var[Y j] ≤ ∑ j in range K, ((j : ℝ) ^ 2) ⁻¹ * 𝔼[(truncation (X 0) j)^2] : begin apply sum_le_sum (λ j hj, _), refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 (sq_nonneg _)), rw (hident j).truncation.variance_eq, exact variance_le_expectation_sq (hX 0).truncation, end ... ≤ 2 * 𝔼[X 0] : sum_variance_truncation_le hint (hnonneg 0) K }, let C := (c ^ 5 * (c - 1) ⁻¹ ^ 3) * (2 * 𝔼[X 0]), have I2 : ∀ N, ∑ i in range N, ((u i : ℝ) ^ 2) ⁻¹ * Var[S (u i)] ≤ C, { assume N, calc ∑ i in range N, ((u i : ℝ) ^ 2) ⁻¹ * Var[S (u i)] = ∑ i in range N, ((u i : ℝ) ^ 2) ⁻¹ * (∑ j in range (u i), Var[Y j]) : begin congr' 1 with i, congr' 1, rw [hS, indep_fun.variance_sum], { assume j hj, exact (hident j).ae_strongly_measurable_fst.mem_ℒp_truncation }, { assume k hk l hl hkl, exact (hindep hkl).comp (A k).measurable (A l).measurable } end ... = ∑ j in range (u (N - 1)), (∑ i in (range N).filter (λ i, j < u i), ((u i : ℝ) ^ 2) ⁻¹) * Var[Y j] : begin simp_rw [mul_sum, sum_mul, sum_sigma'], refine sum_bij' (λ (p : (Σ (i : ℕ), ℕ)) hp, (⟨p.2, p.1⟩ : (Σ (i : ℕ), ℕ))) _ (λ a ha, rfl) (λ (p : (Σ (i : ℕ), ℕ)) hp, (⟨p.2, p.1⟩ : (Σ (i : ℕ), ℕ))) _ _ _, { rintros ⟨i, j⟩ hij, simp only [mem_sigma, mem_range] at hij, simp only [hij.1, hij.2, mem_sigma, mem_range, mem_filter, and_true], exact hij.2.trans_le (u_mono (nat.le_pred_of_lt hij.1)) }, { rintros ⟨i, j⟩ hij, simp only [mem_sigma, mem_range, mem_filter] at hij, simp only [hij.2.1, hij.2.2, mem_sigma, mem_range, and_self] }, { rintros ⟨i, j⟩ hij, refl }, { rintros ⟨i, j⟩ hij, refl }, end ... ≤ ∑ j in range (u (N - 1)), (c ^ 5 * (c - 1) ⁻¹ ^ 3 / j ^ 2) * Var[Y j] : begin apply sum_le_sum (λ j hj, _), rcases @eq_zero_or_pos _ _ j with rfl|hj, { simp only [Y, nat.cast_zero, zero_pow', ne.def, bit0_eq_zero, nat.one_ne_zero, not_false_iff, div_zero, zero_mul], simp only [nat.cast_zero, truncation_zero, variance_zero, mul_zero] }, apply mul_le_mul_of_nonneg_right _ (variance_nonneg _ _), convert sum_div_nat_floor_pow_sq_le_div_sq N (nat.cast_pos.2 hj) c_one, { simp only [nat.cast_lt] }, { simp only [one_div] } end ... = (c ^ 5 * (c - 1) ⁻¹ ^ 3) * ∑ j in range (u (N - 1)), ((j : ℝ) ^ 2) ⁻¹ * Var[Y j] : by { simp_rw [mul_sum, div_eq_mul_inv], ring_nf } ... ≤ (c ^ 5 * (c - 1) ⁻¹ ^ 3) * (2 * 𝔼[X 0]) : begin apply mul_le_mul_of_nonneg_left (I1 _), apply mul_nonneg (pow_nonneg c_pos.le _), exact pow_nonneg (inv_nonneg.2 (sub_nonneg.2 c_one.le)) _ end }, have I3 : ∀ N, ∑ i in range N, ℙ {ω | (u i * ε : ℝ) ≤ |S (u i) ω - 𝔼[S (u i)]|} ≤ ennreal.of_real (ε ⁻¹ ^ 2 * C), { assume N, calc ∑ i in range N, ℙ {ω | (u i * ε : ℝ) ≤ |S (u i) ω - 𝔼[S (u i)]|} ≤ ∑ i in range N, ennreal.of_real (Var[S (u i)] / (u i * ε) ^ 2) : begin refine sum_le_sum (λ i hi, _), apply meas_ge_le_variance_div_sq, { exact mem_ℒp_finset_sum' _ (λ j hj, (hident j).ae_strongly_measurable_fst.mem_ℒp_truncation) }, { apply mul_pos (nat.cast_pos.2 _) εpos, refine zero_lt_one.trans_le _, apply nat.le_floor, rw nat.cast_one, apply one_le_pow_of_one_le c_one.le } end ... = ennreal.of_real (∑ i in range N, Var[S (u i)] / (u i * ε) ^ 2) : begin rw ennreal.of_real_sum_of_nonneg (λ i hi, _), exact div_nonneg (variance_nonneg _ _) (sq_nonneg _), end ... ≤ ennreal.of_real (ε ⁻¹ ^ 2 * C) : begin apply ennreal.of_real_le_of_real, simp_rw [div_eq_inv_mul, ← inv_pow, mul_inv, mul_comm _ (ε⁻¹), mul_pow, mul_assoc, ← mul_sum], refine mul_le_mul_of_nonneg_left _ (sq_nonneg _), simp_rw [inv_pow], exact I2 N end }, have I4 : ∑' i, ℙ {ω | (u i * ε : ℝ) ≤ |S (u i) ω - 𝔼[S (u i)]|} < ∞ := (le_of_tendsto_of_tendsto' (ennreal.tendsto_nat_tsum _) tendsto_const_nhds I3).trans_lt ennreal.of_real_lt_top, filter_upwards [ae_eventually_not_mem I4.ne] with ω hω, simp_rw [not_le, mul_comm, S, sum_apply] at hω, exact hω, end /- The truncation of `Xᵢ` up to `i` satisfies the strong law of large numbers (with respect to the truncated expectation) along the sequence `c^n`, for any `c > 1`. This follows from `strong_law_aux1` by varying `ε`. -/ lemma strong_law_aux2 {c : ℝ} (c_one : 1 < c) : ∀ᵐ ω, (λ (n : ℕ), ∑ i in range ⌊c^n⌋₊, truncation (X i) i ω - 𝔼[∑ i in range ⌊c^n⌋₊, truncation (X i) i]) =o[at_top] (λ (n : ℕ), (⌊c^n⌋₊ : ℝ)) := begin obtain ⟨v, -, v_pos, v_lim⟩ : ∃ (v : ℕ → ℝ), strict_anti v ∧ (∀ (n : ℕ), 0 < v n) ∧ tendsto v at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), have := λ i, strong_law_aux1 X hint hindep hident hnonneg c_one (v_pos i), filter_upwards [ae_all_iff.2 this] with ω hω, apply asymptotics.is_o_iff.2 (λ ε εpos, _), obtain ⟨i, hi⟩ : ∃ i, v i < ε := ((tendsto_order.1 v_lim).2 ε εpos).exists, filter_upwards [hω i] with n hn, simp only [real.norm_eq_abs, lattice_ordered_comm_group.abs_abs, nat.abs_cast], exact hn.le.trans (mul_le_mul_of_nonneg_right hi.le (nat.cast_nonneg _)), end omit hindep hnonneg /-- The expectation of the truncated version of `Xᵢ` behaves asymptotically like the whole expectation. This follows from convergence and Cesaro averaging. -/ lemma strong_law_aux3 : (λ n, 𝔼[∑ i in range n, truncation (X i) i] - n * 𝔼[X 0]) =o[at_top] (coe : ℕ → ℝ) := begin have A : tendsto (λ i, 𝔼[truncation (X i) i]) at_top (𝓝 (𝔼[X 0])), { convert (tendsto_integral_truncation hint).comp tendsto_coe_nat_at_top_at_top, ext i, exact (hident i).truncation.integral_eq }, convert asymptotics.is_o_sum_range_of_tendsto_zero (tendsto_sub_nhds_zero_iff.2 A), ext1 n, simp only [sum_sub_distrib, sum_const, card_range, nsmul_eq_mul, sum_apply, sub_left_inj], rw integral_finset_sum _ (λ i hi, _), exact ((hident i).symm.integrable_snd hint).1.integrable_truncation, end include hindep hnonneg /- The truncation of `Xᵢ` up to `i` satisfies the strong law of large numbers (with respect to the original expectation) along the sequence `c^n`, for any `c > 1`. This follows from the version from the truncated expectation, and the fact that the truncated and the original expectations have the same asymptotic behavior. -/ lemma strong_law_aux4 {c : ℝ} (c_one : 1 < c) : ∀ᵐ ω, (λ (n : ℕ), ∑ i in range ⌊c^n⌋₊, truncation (X i) i ω - ⌊c^n⌋₊ * 𝔼[X 0]) =o[at_top] (λ (n : ℕ), (⌊c^n⌋₊ : ℝ)) := begin filter_upwards [strong_law_aux2 X hint hindep hident hnonneg c_one] with ω hω, have A : tendsto (λ (n : ℕ), ⌊c ^ n⌋₊) at_top at_top := tendsto_nat_floor_at_top.comp (tendsto_pow_at_top_at_top_of_one_lt c_one), convert hω.add ((strong_law_aux3 X hint hident).comp_tendsto A), ext1 n, simp, end omit hindep /-- The truncated and non-truncated versions of `Xᵢ` have the same asymptotic behavior, as they almost surely coincide at all but finitely many steps. This follows from a probability computation and Borel-Cantelli. -/ lemma strong_law_aux5 : ∀ᵐ ω, (λ (n : ℕ), ∑ i in range n, truncation (X i) i ω - ∑ i in range n, X i ω) =o[at_top] (λ (n : ℕ), (n : ℝ)) := begin have A : ∑' (j : ℕ), ℙ {ω | X j ω ∈ set.Ioi (j : ℝ)} < ∞, { convert tsum_prob_mem_Ioi_lt_top hint (hnonneg 0), ext1 j, exact (hident j).measure_mem_eq measurable_set_Ioi }, have B : ∀ᵐ ω, tendsto (λ (n : ℕ), truncation (X n) n ω - X n ω) at_top (𝓝 0), { filter_upwards [ae_eventually_not_mem A.ne] with ω hω, apply tendsto_const_nhds.congr' _, filter_upwards [hω, Ioi_mem_at_top 0] with n hn npos, simp only [truncation, indicator, set.mem_Ioc, id.def, function.comp_app], split_ifs, { exact (sub_self _).symm }, { have : - (n : ℝ) < X n ω, { apply lt_of_lt_of_le _ (hnonneg n ω), simpa only [right.neg_neg_iff, nat.cast_pos] using npos }, simp only [this, true_and, not_le] at h, exact (hn h).elim } }, filter_upwards [B] with ω hω, convert is_o_sum_range_of_tendsto_zero hω, ext n, rw sum_sub_distrib, end include hindep /- `Xᵢ` satisfies the strong law of large numbers along the sequence `c^n`, for any `c > 1`. This follows from the version for the truncated `Xᵢ`, and the fact that `Xᵢ` and its truncated version have the same asymptotic behavior. -/ lemma strong_law_aux6 {c : ℝ} (c_one : 1 < c) : ∀ᵐ ω, tendsto (λ (n : ℕ), (∑ i in range ⌊c^n⌋₊, X i ω) / ⌊c^n⌋₊) at_top (𝓝 (𝔼[X 0])) := begin have H : ∀ (n : ℕ), (0 : ℝ) < ⌊c ^ n⌋₊, { assume n, refine zero_lt_one.trans_le _, simp only [nat.one_le_cast, nat.one_le_floor_iff, one_le_pow_of_one_le c_one.le n] }, filter_upwards [strong_law_aux4 X hint hindep hident hnonneg c_one, strong_law_aux5 X hint hident hnonneg] with ω hω h'ω, rw [← tendsto_sub_nhds_zero_iff, ← asymptotics.is_o_one_iff ℝ], have L : (λ n : ℕ, ∑ i in range ⌊c^n⌋₊, X i ω - ⌊c^n⌋₊ * 𝔼[X 0]) =o[at_top] (λ n, (⌊c^n⌋₊ : ℝ)), { have A : tendsto (λ (n : ℕ), ⌊c ^ n⌋₊) at_top at_top := tendsto_nat_floor_at_top.comp (tendsto_pow_at_top_at_top_of_one_lt c_one), convert hω.sub (h'ω.comp_tendsto A), ext1 n, simp only [sub_sub_sub_cancel_left] }, convert L.mul_is_O (is_O_refl (λ (n : ℕ), (⌊c ^ n⌋₊ : ℝ) ⁻¹) at_top); { ext1 n, field_simp [(H n).ne'] }, end /-- `Xᵢ` satisfies the strong law of large numbers along all integers. This follows from the corresponding fact along the sequences `c^n`, and the fact that any integer can be sandwiched between `c^n` and `c^(n+1)` with comparably small error if `c` is close enough to `1` (which is formalized in `tendsto_div_of_monotone_of_tendsto_div_floor_pow`). -/ lemma strong_law_aux7 : ∀ᵐ ω, tendsto (λ (n : ℕ), (∑ i in range n, X i ω) / n) at_top (𝓝 (𝔼[X 0])) := begin obtain ⟨c, -, cone, clim⟩ : ∃ (c : ℕ → ℝ), strict_anti c ∧ (∀ (n : ℕ), 1 < c n) ∧ tendsto c at_top (𝓝 1) := exists_seq_strict_anti_tendsto (1 : ℝ), have : ∀ k, ∀ᵐ ω, tendsto (λ (n : ℕ), (∑ i in range ⌊c k ^ n⌋₊, X i ω) / ⌊c k ^ n⌋₊) at_top (𝓝 (𝔼[X 0])) := λ k, strong_law_aux6 X hint hindep hident hnonneg (cone k), filter_upwards [ae_all_iff.2 this] with ω hω, apply tendsto_div_of_monotone_of_tendsto_div_floor_pow _ _ _ c cone clim _, { assume m n hmn, exact sum_le_sum_of_subset_of_nonneg (range_mono hmn) (λ i hi h'i, hnonneg i ω) }, { exact hω } end end strong_law_nonneg /-- *Strong law of large numbers*, almost sure version: if `X n` is a sequence of independent identically distributed integrable real-valued random variables, then `∑ i in range n, X i / n` converges almost surely to `𝔼[X 0]`. We give here the strong version, due to Etemadi, that only requires pairwise independence. -/ theorem strong_law_ae (X : ℕ → Ω → ℝ) (hint : integrable (X 0)) (hindep : pairwise (λ i j, indep_fun (X i) (X j))) (hident : ∀ i, ident_distrib (X i) (X 0)) : ∀ᵐ ω, tendsto (λ (n : ℕ), (∑ i in range n, X i ω) / n) at_top (𝓝 (𝔼[X 0])) := begin let pos : ℝ → ℝ := (λ x, max x 0), let neg : ℝ → ℝ := (λ x, max (-x) 0), have posm : measurable pos := measurable_id'.max measurable_const, have negm : measurable neg := measurable_id'.neg.max measurable_const, have A : ∀ᵐ ω, tendsto (λ (n : ℕ), (∑ i in range n, (pos ∘ (X i)) ω) / n) at_top (𝓝 (𝔼[pos ∘ (X 0)])) := strong_law_aux7 _ hint.pos_part (λ i j hij, (hindep hij).comp posm posm) (λ i, (hident i).comp posm) (λ i ω, le_max_right _ _), have B : ∀ᵐ ω, tendsto (λ (n : ℕ), (∑ i in range n, (neg ∘ (X i)) ω) / n) at_top (𝓝 (𝔼[neg ∘ (X 0)])) := strong_law_aux7 _ hint.neg_part (λ i j hij, (hindep hij).comp negm negm) (λ i, (hident i).comp negm) (λ i ω, le_max_right _ _), filter_upwards [A, B] with ω hωpos hωneg, convert hωpos.sub hωneg, { simp only [← sub_div, ← sum_sub_distrib, max_zero_sub_max_neg_zero_eq_self] }, { simp only [←integral_sub hint.pos_part hint.neg_part, max_zero_sub_max_neg_zero_eq_self] } end end strong_law_ae section strong_law_Lp variables {Ω : Type*} [measure_space Ω] [is_probability_measure (ℙ : measure Ω)] /-- *Strong law of large numbers*, Lᵖ version: if `X n` is a sequence of independent identically distributed real-valued random variables in Lᵖ, then `∑ i in range n, X i / n` converges in Lᵖ to `𝔼[X 0]`. -/ theorem strong_law_Lp {p : ℝ≥0∞} (hp : 1 ≤ p) (hp' : p ≠ ∞) (X : ℕ → Ω → ℝ) (hℒp : mem_ℒp (X 0) p) (hindep : pairwise (λ i j, indep_fun (X i) (X j))) (hident : ∀ i, ident_distrib (X i) (X 0)) : tendsto (λ n, snorm (λ ω, (∑ i in range n, X i ω) / n - 𝔼[X 0]) p ℙ) at_top (𝓝 0) := begin have hmeas : ∀ i, ae_strongly_measurable (X i) ℙ := λ i, (hident i).ae_strongly_measurable_iff.2 hℒp.1, have hint : integrable (X 0) ℙ := hℒp.integrable hp, have havg : ∀ n, ae_strongly_measurable (λ ω, (∑ i in range n, X i ω) / n) ℙ, { intro n, simp_rw div_eq_mul_inv, exact ae_strongly_measurable.mul_const (ae_strongly_measurable_sum _ (λ i _, hmeas i)) _ }, refine tendsto_Lp_of_tendsto_in_measure _ hp hp' havg (mem_ℒp_const _) _ (tendsto_in_measure_of_tendsto_ae havg (strong_law_ae _ hint hindep hident)), rw (_ : (λ n ω, (∑ i in range n, X i ω) / ↑n) = λ n, (∑ i in range n, X i) / ↑n), { exact (uniform_integrable_average hp $ mem_ℒp.uniform_integrable_of_ident_distrib hp hp' hℒp hident).2.1 }, { ext n ω, simp only [pi.coe_nat, pi.div_apply, sum_apply] } end end strong_law_Lp end probability_theory
6b698b5583dc1eecb2e29583dc4d3b6a3e6401f1
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/let1.lean
0631cc8d0839643e366d6352a7dcfa2d25762213
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,149
lean
prelude -- Correct version check let bool := Sort 0, and (p q : bool) := ∀ c : bool, (p → q → c) → c, infixl `∧`:25 := and, and_intro (p q : bool) (H1 : p) (H2 : q) : p ∧ q := λ (c : bool) (H : p → q → c), H H1 H2, and_elim_left (p q : bool) (H : p ∧ q) : p := H p (λ (H1 : p) (H2 : q), H1), and_elim_right (p q : bool) (H : p ∧ q) : q := H q (λ (H1 : p) (H2 : q), H2) in and_intro -- TODO(Leo): fix expected output as soon as elaborator starts checking let-expression type again check let bool := Sort 0, and (p q : bool) := ∀ c : bool, (p → q → c) → c, infixl `∧`:25 := and, and_intro (p q : bool) (H1 : p) (H2 : q) : q ∧ p := λ (c : bool) (H : p → q → c), H H1 H2, and_elim_left (p q : bool) (H : p ∧ q) : p := H p (λ (H1 : p) (H2 : q), H1), and_elim_right (p q : bool) (H : p ∧ q) : q := H q (λ (H1 : p) (H2 : q), H2) in and_intro
5b5ad927de1e5eca7a2464ae7e6998765a82db8f
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/group_theory/group_action.lean
f935cc23e18c92debc0babe77d428b2666b78828
[ "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
15,740
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.coset universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale big_operators open function /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[protect_proj] class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) section variables [monoid α] [mul_action α β] theorem mul_smul (a₁ a₂ : α) (b : β) : (a₁ * a₂) • b = a₁ • a₂ • b := mul_action.mul_smul _ _ _ lemma smul_smul (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm lemma smul_comm {α : Type u} {β : Type v} [comm_monoid α] [mul_action α β] (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = a₂ • a₁ • b := by rw [←mul_smul, ←mul_smul, mul_comm] variable (α) @[simp] theorem one_smul (b : β) : (1 : α) • b = b := mul_action.one_smul _ variables {α} @[simp] lemma units.inv_smul_smul (u : units α) (x : β) : (↑u⁻¹:α) • (u:α) • x = x := by rw [smul_smul, u.inv_mul, one_smul] @[simp] lemma units.smul_inv_smul (u : units α) (x : β) : (u:α) • (↑u⁻¹:α) • x = x := by rw [smul_smul, u.mul_inv, one_smul] /-- Pullback a multiplicative action along an injective map respecting `•`. -/ protected def function.injective.mul_action [has_scalar α γ] (f : γ → β) (hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : mul_action α γ := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. -/ protected def function.surjective.mul_action [has_scalar α γ] (f : β → γ) (hf : surjective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : mul_action α γ := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } section gwz variables {G : Type*} [group_with_zero G] [mul_action G β] lemma inv_smul_smul' {c : G} (hc : c ≠ 0) (x : β) : c⁻¹ • c • x = x := (units.mk0 c hc).inv_smul_smul x lemma smul_inv_smul' {c : G} (hc : c ≠ 0) (x : β) : c • c⁻¹ • x = x := (units.mk0 c hc).smul_inv_smul x lemma inv_smul_eq_iff {a : G} (ha : a ≠ 0) {x y : β} : a⁻¹ • x = y ↔ x = a • y := by { split; intro h, rw [← h, smul_inv_smul' ha], rw [h, inv_smul_smul' ha] } lemma eq_inv_smul_iff {a : G} (ha : a ≠ 0) {x y : β} : x = a⁻¹ • y ↔ a • x = y := by { split; intro h, rw [h, smul_inv_smul' ha], rw [← h, inv_smul_smul' ha] } end gwz variables (p : Prop) [decidable p] lemma ite_smul (a₁ a₂ : α) (b : β) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl lemma smul_ite (a : α) (b₁ b₂ : β) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end section compatible_scalar variables (R M N : Type*) [has_scalar R M] [has_scalar M N] [has_scalar R N] /-- An instance of `is_scalar_tower R M N` states that the multiplicative action of `R` on `N` is determined by the multiplicative actions of `R` on `M` and `M` on `N`. -/ class is_scalar_tower : Prop := (smul_assoc : ∀ (x : R) (y : M) (z : N), (x • y) • z = x • (y • z)) variables {R M N} @[simp] lemma smul_assoc [is_scalar_tower R M N] (x : R) (y : M) (z : N) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z end compatible_scalar namespace mul_action variables (α) [monoid α] /-- The regular action of a monoid on itself by left multiplication. -/ def regular : mul_action α α := { smul := λ a₁ a₂, a₁ * a₂, one_smul := λ a, one_mul a, mul_smul := λ a₁ a₂ a₃, mul_assoc _ _ _, } variables [mul_action α β] section regular local attribute [instance] regular instance is_scalar_tower.left : is_scalar_tower α α β := ⟨λ x y z, mul_smul x y z⟩ end regular /-- The orbit of an element under an action. -/ def orbit (b : β) := set.range (λ x : α, x • b) variable {α} lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ variable (α) /-- The stabilizer of an element under an action, i.e. what sends the element to itself. Note that this is a set: for the group stabilizer see `stabilizer`. -/ def stabilizer_carrier (b : β) : set α := {x : α | x • b = b} variable {α} @[simp] lemma mem_stabilizer_iff {b : β} {x : α} : x ∈ stabilizer_carrier α b ↔ x • b = b := iff.rfl variables (α) (β) /-- The set of elements fixed under the whole action. -/ def fixed_points : set β := {b : β | ∀ x : α, x • b = b} /-- `fixed_by g` is the subfield of elements fixed by `g`. -/ def fixed_by (g : α) : set β := { x | g • x = x } theorem fixed_eq_Inter_fixed_by : fixed_points α β = ⋂ g : α, fixed_by α β g := set.ext $ λ x, ⟨λ hx, set.mem_Inter.2 $ λ g, hx g, λ hx g, by exact (set.mem_Inter.1 hx g : _)⟩ variables {α} (β) @[simp] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl @[simp] lemma mem_fixed_by {g : α} {b : β} : b ∈ fixed_by α β g ↔ g • b = b := iff.rfl lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _))⟩ /-- An action of `α` on `β` and a monoid homomorphism `γ → α` induce an action of `γ` on `β`. -/ def comp_hom [monoid γ] (g : γ →* α) : mul_action γ β := { smul := λ x b, (g x) • b, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } variables (α) {β} /-- The stabilizer of a point `b` as a submonoid of `α`. -/ def stabilizer.submonoid (b : β) : submonoid α := { carrier := stabilizer_carrier α b, one_mem' := one_smul _ b, mul_mem' := λ a a' (ha : a • b = b) (hb : a' • b = b), by rw [mem_stabilizer_iff, ←smul_smul, hb, ha] } variables (α β) /-- Embedding induced by action. -/ def to_fun : β ↪ (α → β) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul α y₁ ▸ one_smul α y₂ ▸ by convert congr_fun H 1⟩ variables {α β} @[simp] lemma to_fun_apply (x : α) (y : β) : mul_action.to_fun α β y x = x • y := rfl end mul_action namespace mul_action variables [group α] [mul_action α β] section open mul_action quotient_group @[simp] lemma inv_smul_smul (c : α) (x : β) : c⁻¹ • c • x = x := (to_units c).inv_smul_smul x @[simp] lemma smul_inv_smul (c : α) (x : β) : c • c⁻¹ • x = x := (to_units c).smul_inv_smul x lemma inv_smul_eq_iff {a : α} {x y : β} : a⁻¹ • x = y ↔ x = a • y := begin split; rintro rfl, {rw smul_inv_smul}, {rw inv_smul_smul}, end lemma eq_inv_smul_iff {a : α} {x y : β} : x = a⁻¹ • y ↔ a • x = y := begin split; rintro rfl, {rw smul_inv_smul}, {rw inv_smul_smul}, end variable (α) /-- The stabilizer of an element under an action, i.e. what sends the element to itself. A subgroup.-/ def stabilizer (b : β) : subgroup α := { inv_mem' := λ a (ha : a • b = b), show a⁻¹ • b = b, by rw [inv_smul_eq_iff, ha] ..stabilizer.submonoid α b } variable (β) /-- Given an action of a group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/ def to_perm (g : α) : equiv.perm β := { to_fun := (•) g, inv_fun := (•) g⁻¹, left_inv := inv_smul_smul g, right_inv := smul_inv_smul g } variables {α} {β} instance : is_group_hom (to_perm α β) := { map_mul := λ x y, equiv.ext (λ a, mul_action.mul_smul x y a) } protected lemma bijective (g : α) : bijective (λ b : β, g • b) := (to_perm α β g).bijective lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x, show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩, λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹, show (y * x⁻¹) • a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_action.mul_smul, hx]}⟩⟩)⟩ variables (α) {β} /-- The stabilizer of a point `b` as a subgroup of `α`. -/ def stabilizer.subgroup (b : β) : subgroup α := { inv_mem' := λ x (hx : x • b = b), show x⁻¹ • b = b, by rw [← hx, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul, hx], ..stabilizer.submonoid α b } variables {β} @[simp] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) := ⟨g⁻¹, by simp⟩ @[simp] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) := ⟨g * h⁻¹, by simp [mul_smul]⟩ variables (α) (β) /-- The relation "in the same orbit". -/ def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } variables {α β} open quotient_group mul_action /-- Action on left cosets. -/ def mul_left_cosets (H : subgroup α) (x : α) (y : quotient H) : quotient H := quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y)) (λ a b (hab : _ ∈ H), quotient_group.eq.2 (by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance (H : subgroup α) : mul_action α (quotient H) := { smul := mul_left_cosets H, one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [subgroup.one_mem])), mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [mul_inv_rev, subgroup.one_mem, mul_assoc])) } instance mul_left_cosets_comp_subtype_val (H I : subgroup α) : mul_action I (quotient H) := mul_action.comp_hom (quotient H) (subgroup.subtype I) variables (α) {β} (x : β) /-- The canonical map from the quotient of the stabilizer to the set. -/ def of_quotient_stabilizer (g : quotient (mul_action.stabilizer α x)) : β := quotient.lift_on' g (•x) $ λ g1 g2 H, calc g1 • x = g1 • (g1⁻¹ * g2) • x : congr_arg _ H.symm ... = g2 • x : by rw [smul_smul, mul_inv_cancel_left] @[simp] theorem of_quotient_stabilizer_mk (g : α) : of_quotient_stabilizer α x (quotient_group.mk g) = g • x := rfl theorem of_quotient_stabilizer_mem_orbit (g) : of_quotient_stabilizer α x g ∈ orbit α x := quotient.induction_on' g $ λ g, ⟨g, rfl⟩ theorem of_quotient_stabilizer_smul (g : α) (g' : quotient (mul_action.stabilizer α x)) : of_quotient_stabilizer α x (g • g') = g • of_quotient_stabilizer α x g' := quotient.induction_on' g' $ λ _, mul_smul _ _ _ theorem injective_of_quotient_stabilizer : function.injective (of_quotient_stabilizer α x) := λ y₁ y₂, quotient.induction_on₂' y₁ y₂ $ λ g₁ g₂ (H : g₁ • x = g₂ • x), quotient.sound' $ show (g₁⁻¹ * g₂) • x = x, by rw [mul_smul, ← H, mul_action.inv_smul_smul] /-- Orbit-stabilizer theorem. -/ noncomputable def orbit_equiv_quotient_stabilizer (b : β) : orbit α b ≃ quotient (stabilizer α b) := equiv.symm $ equiv.of_bijective (λ g, ⟨of_quotient_stabilizer α b g, of_quotient_stabilizer_mem_orbit α b g⟩) ⟨λ x y hxy, injective_of_quotient_stabilizer α b (by convert congr_arg subtype.val hxy), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩ @[simp] theorem orbit_equiv_quotient_stabilizer_symm_apply (b : β) (a : α) : ((orbit_equiv_quotient_stabilizer α b).symm a : β) = a • b := rfl end end mul_action /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : α), r • (0 : β) = 0) section variables [monoid α] [add_monoid β] [distrib_mul_action α β] theorem smul_add (a : α) (b₁ b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : α) : a • (0 : β) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. -/ protected def function.injective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : γ →+ β) (hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : distrib_mul_action α γ := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism.-/ protected def function.surjective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : β →+ γ) (hf : surjective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : distrib_mul_action α γ := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } theorem units.smul_eq_zero (u : units α) {x : β} : (u : α) • x = 0 ↔ x = 0 := ⟨λ h, by rw [← u.inv_smul_smul x, h, smul_zero], λ h, h.symm ▸ smul_zero _⟩ theorem units.smul_ne_zero (u : units α) {x : β} : (u : α) • x ≠ 0 ↔ x ≠ 0 := not_congr u.smul_eq_zero @[simp] theorem is_unit.smul_eq_zero {u : α} (hu : is_unit u) {x : β} : u • x = 0 ↔ x = 0 := exists.elim hu $ λ u hu, hu ▸ u.smul_eq_zero variable (β) /-- Scalar multiplication by `r` as an `add_monoid_hom`. -/ def const_smul_hom (r : α) : β →+ β := { to_fun := (•) r, map_zero' := smul_zero r, map_add' := smul_add r } variable {β} @[simp] lemma const_smul_hom_apply (r : α) (x : β) : const_smul_hom β r x = r • x := rfl lemma list.smul_sum {r : α} {l : list β} : r • l.sum = (l.map ((•) r)).sum := (const_smul_hom β r).map_list_sum l end section variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β] lemma multiset.smul_sum {r : α} {s : multiset β} : r • s.sum = (s.map ((•) r)).sum := (const_smul_hom β r).map_multiset_sum s lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} : r • ∑ x in s, f x = ∑ x in s, r • f x := (const_smul_hom β r).map_sum f s end section variables [monoid α] [add_group β] [distrib_mul_action α β] @[simp] theorem smul_neg (r : α) (x : β) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end
12b9ad9bf203b79a97fe9d784a7d389f86445335
43390109ab88557e6090f3245c47479c123ee500
/src/xenalib/nat_stuff.lean
67e9a4413a93c3ec1220ddb41b1b4e645a755ae4
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,113
lean
import algebra.group_power theorem nat.cast_pow {α : Type*} [semiring α] (n : ℕ) : ∀ m : ℕ, (n : α) ^ m = (n ^ m : ℕ) | 0 := nat.cast_one.symm | (d+1) := show ↑n * ↑n ^ d = ↑(n ^ d * n), by rw [nat.cast_pow d,mul_comm,nat.cast_mul] theorem int.cast_pow {α : Type*} [ring α] (n : ℤ) : ∀ m : ℕ, (n : α) ^ m = (n ^ m : ℤ) | 0 := nat.cast_one.symm | (d+1) := show ↑n * ↑n ^ d = ↑(n * n ^ d), by rw [int.cast_pow d,int.cast_mul] theorem nat.cast_pow' (n : ℕ) : ∀ m : ℕ, (n : ℤ) ^ m = (n ^ m : ℕ) | 0 := nat.cast_one.symm | (d+1) := show ↑n * ↑n ^ d = ↑(n ^ d * n), by rw [nat.cast_pow',mul_comm,int.coe_nat_mul] theorem nat.pow_pow (n a : ℕ) : ∀ b : ℕ, (n ^ a) ^ b = n ^ (a * b) | 0 := by rw mul_zero;refl | (d+1) := show (n^a)^d * n^a = _, by rw [mul_add,mul_one,nat.pow_add,nat.pow_pow] theorem nat.mul_div {a b : ℕ} (Ha : a ≠ 0) (Hd : a ∣ b) : a * (b / a) = b := by rw nat.dvd_iff_mod_eq_zero at Hd;exact zero_add (a * (b / a)) ▸ (Hd ▸ nat.mod_add_div b a) theorem nat.pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul
4bc9a9aec14270b5375dcd187a3069eafb034b5a
e09201d437062e1f95e6e5360aab0c9f947901aa
/src/regular/nonregular.lean
2dfc9f0bd8f1c2035ce99811a8603d1ab3ff7510
[]
no_license
VArtem/lean-regular-languages
34f4b093f28ef2f09ba7e684e642a0f97c901560
e877243188253d0ac17ccf0ae2da7bf608686ff0
refs/heads/master
1,683,590,111,306
1,622,307,234,000
1,622,307,234,000
284,232,653
7
0
null
null
null
null
UTF-8
Lean
false
false
1,134
lean
import automata.dfa import data.list.basic import regular.regex import regular.list_lemmas import regular.pumping_lemma open DFA list pumping def L0ⁿ1ⁿ := {w | ∃ n, w = (repeat bool.ff n) ++ (repeat bool.tt n)} @[simp] lemma mem_L0ⁿ1ⁿ_iff {w} : w ∈ L0ⁿ1ⁿ ↔ ∃ n, w = (repeat bool.ff n) ++ (repeat bool.tt n) := iff.rfl theorem not_regular_0ⁿ1ⁿ : ¬dfa_lang L0ⁿ1ⁿ := begin apply pumping_lemma_negation, intro n, use [(repeat bool.ff n) ++ (repeat bool.tt n), n], simp only [not_exists, true_and, length_repeat, zero_le, le_add_iff_nonneg_left, mem_L0ⁿ1ⁿ_iff, length_append], rintro x y z hxyz ynil hpref, use 0, simp only [join, repeat, append_nil], rintro l hl, rw [← length_repeat ff n, ← length_append] at hpref, have tt_n_suffix := suffix_of_append_eq_append hpref hxyz, have tt_eq_ff := repeat_suffix_of_append_repeat _ (is_suffix.trans tt_n_suffix ⟨x, hl⟩), contradiction, apply_fun length at hxyz hl, simp only [length_repeat, length_append] at hpref hl hxyz, rw [← length_pos_iff_ne_nil] at ynil, linarith, end
0cf9dc24df5d9078c7d1f019ce2b9fad43a0654c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/locally_convex/basic.lean
9ae5564e54d2e40840e89bcb9110b292e2356659
[ "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,069
lean
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo, Bhavik Mehta, Yaël Dillies -/ import analysis.convex.basic import analysis.convex.hull import analysis.normed_space.basic /-! # Local convexity This file defines absorbent and balanced sets. An absorbent set is one that "surrounds" the origin. The idea is made precise by requiring that any point belongs to all large enough scalings of the set. This is the vector world analog of a topological neighborhood of the origin. A balanced set is one that is everywhere around the origin. This means that `a • s ⊆ s` for all `a` of norm less than `1`. ## Main declarations For a module over a normed ring: * `absorbs`: A set `s` absorbs a set `t` if all large scalings of `s` contain `t`. * `absorbent`: A set `s` is absorbent if every point eventually belongs to all large scalings of `s`. * `balanced`: A set `s` is balanced if `a • s ⊆ s` for all `a` of norm less than `1`. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags absorbent, balanced, locally convex, LCTVS -/ open set open_locale pointwise topological_space variables {𝕜 𝕝 E : Type*} {ι : Sort*} {κ : ι → Sort*} section semi_normed_ring variables [semi_normed_ring 𝕜] section has_smul variables (𝕜) [has_smul 𝕜 E] /-- A set `A` absorbs another set `B` if `B` is contained in all scalings of `A` by elements of sufficiently large norm. -/ def absorbs (A B : set E) := ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ‖a‖ → B ⊆ a • A variables {𝕜} {s t u v A B : set E} @[simp] lemma absorbs_empty {s : set E}: absorbs 𝕜 s (∅ : set E) := ⟨1, one_pos, λ a ha, set.empty_subset _⟩ lemma absorbs.mono (hs : absorbs 𝕜 s u) (hst : s ⊆ t) (hvu : v ⊆ u) : absorbs 𝕜 t v := let ⟨r, hr, h⟩ := hs in ⟨r, hr, λ a ha, hvu.trans $ (h _ ha).trans $ smul_set_mono hst⟩ lemma absorbs.mono_left (hs : absorbs 𝕜 s u) (h : s ⊆ t) : absorbs 𝕜 t u := hs.mono h subset.rfl lemma absorbs.mono_right (hs : absorbs 𝕜 s u) (h : v ⊆ u) : absorbs 𝕜 s v := hs.mono subset.rfl h lemma absorbs.union (hu : absorbs 𝕜 s u) (hv : absorbs 𝕜 s v) : absorbs 𝕜 s (u ∪ v) := begin obtain ⟨a, ha, hu⟩ := hu, obtain ⟨b, hb, hv⟩ := hv, exact ⟨max a b, lt_max_of_lt_left ha, λ c hc, union_subset (hu _ $ le_of_max_le_left hc) (hv _ $ le_of_max_le_right hc)⟩, end @[simp] lemma absorbs_union : absorbs 𝕜 s (u ∪ v) ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 s v := ⟨λ h, ⟨h.mono_right $ subset_union_left _ _, h.mono_right $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ lemma absorbs_Union_finset {ι : Type*} {t : finset ι} {f : ι → set E} : absorbs 𝕜 s (⋃ i ∈ t, f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin classical, induction t using finset.induction_on with i t ht hi, { simp only [finset.not_mem_empty, set.Union_false, set.Union_empty, absorbs_empty, is_empty.forall_iff, implies_true_iff] }, rw [finset.set_bUnion_insert, absorbs_union, hi], split; intro h, { refine λ _ hi', (finset.mem_insert.mp hi').elim _ (h.2 _), exact (λ hi'', by { rw hi'', exact h.1 }) }, exact ⟨h i (finset.mem_insert_self i t), λ i' hi', h i' (finset.mem_insert_of_mem hi')⟩, end lemma set.finite.absorbs_Union {ι : Type*} {s : set E} {t : set ι} {f : ι → set E} (hi : t.finite) : absorbs 𝕜 s (⋃ i ∈ t, f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin lift t to finset ι using hi, simp only [finset.mem_coe], exact absorbs_Union_finset, end variables (𝕜) /-- A set is absorbent if it absorbs every singleton. -/ def absorbent (A : set E) := ∀ x, ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ‖a‖ → x ∈ a • A variables {𝕜} lemma absorbent.subset (hA : absorbent 𝕜 A) (hAB : A ⊆ B) : absorbent 𝕜 B := begin refine forall_imp (λ x, _) hA, exact Exists.imp (λ r, and.imp_right $ forall₂_imp $ λ a ha hx, set.smul_set_mono hAB hx), end lemma absorbent_iff_forall_absorbs_singleton : absorbent 𝕜 A ↔ ∀ x, absorbs 𝕜 A {x} := by simp_rw [absorbs, absorbent, singleton_subset_iff] lemma absorbent.absorbs (hs : absorbent 𝕜 s) {x : E} : absorbs 𝕜 s {x} := absorbent_iff_forall_absorbs_singleton.1 hs _ lemma absorbent_iff_nonneg_lt : absorbent 𝕜 A ↔ ∀ x, ∃ r, 0 ≤ r ∧ ∀ ⦃a : 𝕜⦄, r < ‖a‖ → x ∈ a • A := forall_congr $ λ x, ⟨λ ⟨r, hr, hx⟩, ⟨r, hr.le, λ a ha, hx a ha.le⟩, λ ⟨r, hr, hx⟩, ⟨r + 1, add_pos_of_nonneg_of_pos hr zero_lt_one, λ a ha, hx ((lt_add_of_pos_right r zero_lt_one).trans_le ha)⟩⟩ lemma absorbent.absorbs_finite {s : set E} (hs : absorbent 𝕜 s) {v : set E} (hv : v.finite) : absorbs 𝕜 s v := begin rw ←set.bUnion_of_singleton v, exact hv.absorbs_Union.mpr (λ _ _, hs.absorbs), end variables (𝕜) /-- A set `A` is balanced if `a • A` is contained in `A` whenever `a` has norm at most `1`. -/ def balanced (A : set E) := ∀ a : 𝕜, ‖a‖ ≤ 1 → a • A ⊆ A variables {𝕜} lemma balanced_iff_smul_mem : balanced 𝕜 s ↔ ∀ ⦃a : 𝕜⦄, ‖a‖ ≤ 1 → ∀ ⦃x : E⦄, x ∈ s → a • x ∈ s := forall₂_congr $ λ a ha, smul_set_subset_iff alias balanced_iff_smul_mem ↔ balanced.smul_mem _ @[simp] lemma balanced_empty : balanced 𝕜 (∅ : set E) := λ _ _, by { rw smul_set_empty } @[simp] lemma balanced_univ : balanced 𝕜 (univ : set E) := λ a ha, subset_univ _ lemma balanced.union (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∪ B) := λ a ha, smul_set_union.subset.trans $ union_subset_union (hA _ ha) $ hB _ ha lemma balanced.inter (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∩ B) := λ a ha, smul_set_inter_subset.trans $ inter_subset_inter (hA _ ha) $ hB _ ha lemma balanced_Union {f : ι → set E} (h : ∀ i, balanced 𝕜 (f i)) : balanced 𝕜 (⋃ i, f i) := λ a ha, (smul_set_Union _ _).subset.trans $ Union_mono $ λ _, h _ _ ha lemma balanced_Union₂ {f : Π i, κ i → set E} (h : ∀ i j, balanced 𝕜 (f i j)) : balanced 𝕜 (⋃ i j, f i j) := balanced_Union $ λ _, balanced_Union $ h _ lemma balanced_Inter {f : ι → set E} (h : ∀ i, balanced 𝕜 (f i)) : balanced 𝕜 (⋂ i, f i) := λ a ha, (smul_set_Inter_subset _ _).trans $ Inter_mono $ λ _, h _ _ ha lemma balanced_Inter₂ {f : Π i, κ i → set E} (h : ∀ i j, balanced 𝕜 (f i j)) : balanced 𝕜 (⋂ i j, f i j) := balanced_Inter $ λ _, balanced_Inter $ h _ variables [has_smul 𝕝 E] [smul_comm_class 𝕜 𝕝 E] lemma balanced.smul (a : 𝕝) (hs : balanced 𝕜 s) : balanced 𝕜 (a • s) := λ b hb, (smul_comm _ _ _).subset.trans $ smul_set_mono $ hs _ hb end has_smul section module variables [add_comm_group E] [module 𝕜 E] {s s₁ s₂ t t₁ t₂ : set E} lemma absorbs.neg : absorbs 𝕜 s t → absorbs 𝕜 (-s) (-t) := Exists.imp $ λ r, and.imp_right $ forall₂_imp $ λ _ _ h, (neg_subset_neg.2 h).trans (smul_set_neg _ _).superset lemma balanced.neg : balanced 𝕜 s → balanced 𝕜 (-s) := forall₂_imp $ λ _ _ h, (smul_set_neg _ _).subset.trans $ neg_subset_neg.2 h lemma absorbs.add : absorbs 𝕜 s₁ t₁ → absorbs 𝕜 s₂ t₂ → absorbs 𝕜 (s₁ + s₂) (t₁ + t₂) := λ ⟨r₁, hr₁, h₁⟩ ⟨r₂, hr₂, h₂⟩, ⟨max r₁ r₂, lt_max_of_lt_left hr₁, λ a ha, (add_subset_add (h₁ _ $ le_of_max_le_left ha) $ h₂ _ $ le_of_max_le_right ha).trans (smul_add _ _ _).superset⟩ lemma balanced.add (hs : balanced 𝕜 s) (ht : balanced 𝕜 t) : balanced 𝕜 (s + t) := λ a ha, (smul_add _ _ _).subset.trans $ add_subset_add (hs _ ha) $ ht _ ha lemma absorbs.sub (h₁ : absorbs 𝕜 s₁ t₁) (h₂ : absorbs 𝕜 s₂ t₂) : absorbs 𝕜 (s₁ - s₂) (t₁ - t₂) := by { simp_rw sub_eq_add_neg, exact h₁.add h₂.neg } lemma balanced.sub (hs : balanced 𝕜 s) (ht : balanced 𝕜 t) : balanced 𝕜 (s - t) := by { simp_rw sub_eq_add_neg, exact hs.add ht.neg } lemma balanced_zero : balanced 𝕜 (0 : set E) := λ a ha, (smul_zero _).subset end module end semi_normed_ring section normed_field variables [normed_field 𝕜] [normed_ring 𝕝] [normed_space 𝕜 𝕝] [add_comm_group E] [module 𝕜 E] [smul_with_zero 𝕝 E] [is_scalar_tower 𝕜 𝕝 E] {s t u v A B : set E} {x : E} {a b : 𝕜} /-- Scalar multiplication (by possibly different types) of a balanced set is monotone. -/ lemma balanced.smul_mono (hs : balanced 𝕝 s) {a : 𝕝} {b : 𝕜} (h : ‖a‖ ≤ ‖b‖) : a • s ⊆ b • s := begin obtain rfl | hb := eq_or_ne b 0, { rw norm_zero at h, rw norm_eq_zero.1 (h.antisymm $ norm_nonneg _), obtain rfl | h := s.eq_empty_or_nonempty, { simp_rw [smul_set_empty] }, { simp_rw [zero_smul_set h] } }, rintro _ ⟨x, hx, rfl⟩, refine ⟨b⁻¹ • a • x, _, smul_inv_smul₀ hb _⟩, rw ←smul_assoc, refine hs _ _ (smul_mem_smul_set hx), rw [norm_smul, norm_inv, ←div_eq_inv_mul], exact div_le_one_of_le h (norm_nonneg _), end /-- A balanced set absorbs itself. -/ lemma balanced.absorbs_self (hA : balanced 𝕜 A) : absorbs 𝕜 A A := begin refine ⟨1, zero_lt_one, λ a ha x hx, _⟩, rw mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), refine hA a⁻¹ _ (smul_mem_smul_set hx), rw norm_inv, exact inv_le_one ha, end lemma balanced.subset_smul (hA : balanced 𝕜 A) (ha : 1 ≤ ‖a‖) : A ⊆ a • A := begin refine (subset_set_smul_iff₀ _).2 (hA (a⁻¹) _), { rintro rfl, rw norm_zero at ha, exact zero_lt_one.not_le ha }, { rw norm_inv, exact inv_le_one ha } end lemma balanced.smul_eq (hA : balanced 𝕜 A) (ha : ‖a‖ = 1) : a • A = A := (hA _ ha.le).antisymm $ hA.subset_smul ha.ge lemma balanced.mem_smul_iff (hs : balanced 𝕜 s) (h : ‖a‖ = ‖b‖) : a • x ∈ s ↔ b • x ∈ s := begin obtain rfl | hb := eq_or_ne b 0, { rw [norm_zero, norm_eq_zero] at h, rw h }, have ha : a ≠ 0 := norm_ne_zero_iff.1 (ne_of_eq_of_ne h $ norm_ne_zero_iff.2 hb), split; intro h'; [rw ←inv_mul_cancel_right₀ ha b, rw ←inv_mul_cancel_right₀ hb a]; { rw [←smul_eq_mul, smul_assoc], refine hs.smul_mem _ h', simp [←h, ha] } end lemma balanced.neg_mem_iff (hs : balanced 𝕜 s) : -x ∈ s ↔ x ∈ s := by convert hs.mem_smul_iff (norm_neg 1); simp only [neg_smul, one_smul] lemma absorbs.inter (hs : absorbs 𝕜 s u) (ht : absorbs 𝕜 t u) : absorbs 𝕜 (s ∩ t) u := begin obtain ⟨a, ha, hs⟩ := hs, obtain ⟨b, hb, ht⟩ := ht, have h : 0 < max a b := lt_max_of_lt_left ha, refine ⟨max a b, lt_max_of_lt_left ha, λ c hc, _⟩, rw smul_set_inter₀ (norm_pos_iff.1 $ h.trans_le hc), exact subset_inter (hs _ $ le_of_max_le_left hc) (ht _ $ le_of_max_le_right hc), end @[simp] lemma absorbs_inter : absorbs 𝕜 (s ∩ t) u ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 t u := ⟨λ h, ⟨h.mono_left $ inter_subset_left _ _, h.mono_left $ inter_subset_right _ _⟩, λ h, h.1.inter h.2⟩ lemma absorbent_univ : absorbent 𝕜 (univ : set E) := begin refine λ x, ⟨1, zero_lt_one, λ a ha, _⟩, rw smul_set_univ₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), exact trivial, end variables [topological_space E] [has_continuous_smul 𝕜 E] /-- Every neighbourhood of the origin is absorbent. -/ lemma absorbent_nhds_zero (hA : A ∈ 𝓝 (0 : E)) : absorbent 𝕜 A := begin intro x, obtain ⟨w, hw₁, hw₂, hw₃⟩ := mem_nhds_iff.mp hA, have hc : continuous (λ t : 𝕜, t • x) := continuous_id.smul continuous_const, obtain ⟨r, hr₁, hr₂⟩ := metric.is_open_iff.mp (hw₂.preimage hc) 0 (by rwa [mem_preimage, zero_smul]), have hr₃ := inv_pos.mpr (half_pos hr₁), refine ⟨(r / 2)⁻¹, hr₃, λ a ha₁, _⟩, have ha₂ : 0 < ‖a‖ := hr₃.trans_le ha₁, refine (mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.mp ha₂) _ _).2 (hw₁ $ hr₂ _), rw [metric.mem_ball, dist_zero_right, norm_inv], calc ‖a‖⁻¹ ≤ r/2 : (inv_le (half_pos hr₁) ha₂).mp ha₁ ... < r : half_lt_self hr₁, end /-- The union of `{0}` with the interior of a balanced set is balanced. -/ lemma balanced_zero_union_interior (hA : balanced 𝕜 A) : balanced 𝕜 ((0 : set E) ∪ interior A) := begin intros a ha, obtain rfl | h := eq_or_ne a 0, { rw zero_smul_set, exacts [subset_union_left _ _, ⟨0, or.inl rfl⟩] }, { rw [←image_smul, image_union], apply union_subset_union, { rw [image_zero, smul_zero], refl }, { calc a • interior A ⊆ interior (a • A) : (is_open_map_smul₀ h).image_interior_subset A ... ⊆ interior A : interior_mono (hA _ ha) } } end /-- The interior of a balanced set is balanced if it contains the origin. -/ lemma balanced.interior (hA : balanced 𝕜 A) (h : (0 : E) ∈ interior A) : balanced 𝕜 (interior A) := begin rw ←union_eq_self_of_subset_left (singleton_subset_iff.2 h), exact balanced_zero_union_interior hA, end lemma balanced.closure (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) := λ a ha, (image_closure_subset_closure_image $ continuous_id.const_smul _).trans $ closure_mono $ hA _ ha end normed_field section nontrivially_normed_field variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {s : set E} lemma absorbs_zero_iff : absorbs 𝕜 s 0 ↔ (0 : E) ∈ s := begin refine ⟨_, λ h, ⟨1, zero_lt_one, λ a _, zero_subset.2 $ zero_mem_smul_set h⟩⟩, rintro ⟨r, hr, h⟩, obtain ⟨a, ha⟩ := normed_space.exists_lt_norm 𝕜 𝕜 r, have := h _ ha.le, rwa [zero_subset, zero_mem_smul_set_iff] at this, exact norm_ne_zero_iff.1 (hr.trans ha).ne', end lemma absorbent.zero_mem (hs : absorbent 𝕜 s) : (0 : E) ∈ s := absorbs_zero_iff.1 $ absorbent_iff_forall_absorbs_singleton.1 hs _ variables [module ℝ E] [smul_comm_class ℝ 𝕜 E] lemma balanced_convex_hull_of_balanced (hs : balanced 𝕜 s) : balanced 𝕜 (convex_hull ℝ s) := begin suffices : convex ℝ {x | ∀ a : 𝕜, ‖a‖ ≤ 1 → a • x ∈ convex_hull ℝ s}, { rw balanced_iff_smul_mem at hs ⊢, refine λ a ha x hx, convex_hull_min _ this hx a ha, exact λ y hy a ha, subset_convex_hull ℝ s (hs ha hy) }, intros x hx y hy u v hu hv huv a ha, simp only [smul_add, ← smul_comm], exact convex_convex_hull ℝ s (hx a ha) (hy a ha) hu hv huv end end nontrivially_normed_field section real variables [add_comm_group E] [module ℝ E] {s : set E} lemma balanced_iff_neg_mem (hs : convex ℝ s) : balanced ℝ s ↔ ∀ ⦃x⦄, x ∈ s → -x ∈ s := begin refine ⟨λ h x, h.neg_mem_iff.2, λ h a ha, smul_set_subset_iff.2 $ λ x hx, _⟩, rw [real.norm_eq_abs, abs_le] at ha, rw [show a = -((1 - a) / 2) + (a - -1)/2, by ring, add_smul, neg_smul, ←smul_neg], exact hs (h hx) hx (div_nonneg (sub_nonneg_of_le ha.2) zero_le_two) (div_nonneg (sub_nonneg_of_le ha.1) zero_le_two) (by ring), end end real
a1a84352e49b3a5f80424b83c4d7ab39261afb5c
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/sheaves/presheaf_of_topological_rings.lean
06707bd988acf1cbe567a51f695c1363fc6518c7
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
2,043
lean
/- Presheaf of toplogical rings. -/ import topology.algebra.ring import for_mathlib.sheaves.presheaf_of_rings universes u v open topological_space -- Definition of a presheaf of topological rings. structure presheaf_of_topological_rings (α : Type u) [topological_space α] extends presheaf_of_rings α := (Ftop : ∀ (U), topological_space (F U)) (Ftop_ring : ∀ (U), topological_ring (F U)) (res_continuous : ∀ (U V) (HVU : V ⊆ U), continuous (res U V HVU)) instance presheaf_of_topological_rings.has_coe {α : Type u} [topological_space α] : has_coe (presheaf_of_topological_rings α) (presheaf α) := ⟨λ F, F.to_presheaf⟩ instance presheaf_of_topological_rings.topological_space_sections {α : Type u} [topological_space α] (F : presheaf_of_topological_rings α) (U : opens α) : topological_space (F U) := F.Ftop U attribute [instance] presheaf_of_topological_rings.Ftop attribute [instance] presheaf_of_topological_rings.Ftop_ring instance presheaf_of_topological_rings.comm_ring {X : Type u} [topological_space X] (F : presheaf_of_topological_rings X) (U : opens X) : comm_ring (F U) := F.Fring U namespace presheaf_of_topological_rings variables {α : Type u} {β : Type v} [topological_space α] [topological_space β] -- Morphism of presheaf of topological rings. structure morphism (F G : presheaf_of_topological_rings α) extends presheaf.morphism F.to_presheaf G.to_presheaf := (ring_homs : ∀ (U), is_ring_hom (map U)) (continuous_homs : ∀ (U), continuous (map U)) infix `⟶`:80 := morphism def identity (F : presheaf_of_topological_rings α) : F ⟶ F := { ring_homs := λ U, is_ring_hom.id, continuous_homs := λ U, continuous_id, ..presheaf.id F.to_presheaf } -- Isomorphic presheaves of rings. structure iso (F G : presheaf_of_topological_rings α) := (mor : F ⟶ G) (inv : G ⟶ F) (mor_inv_id : mor.to_morphism ⊚ inv.to_morphism = presheaf.id F.to_presheaf) (inv_mor_id : inv.to_morphism ⊚ mor.to_morphism = presheaf.id G.to_presheaf) end presheaf_of_topological_rings
62e859a2b408e9ab1cd70b5d8391fd4c30446bc5
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world8/level9.lean
deba29b3ac6c9023bcd58d16a6c20172e1ebbbe7
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
187
lean
import mynat.definition import mynat.add namespace mynat theorem succ_ne_zero (a : mynat) : succ(a) ≠ 0 := begin [nat_num_game] symmetry, exact zero_ne_succ a, end end mynat
9f489731fcd01965608c42996f6110adc8c3ccb8
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/tactic/default.lean
611ec94c7e02d802b2ddf427b19444b09eec1b8c
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
141
lean
import tactic.interactive tactic.alias tactic.finish tactic.mk_iff_of_inductive_prop tactic.wlog tactic.monotonicity.interactive
3be483d301cb41b48aa4d68a5dac1d273668329c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/interactive_auto.lean
fdc1e008d11797c4013641345fb55c2f42b5748c
[]
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
33,034
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jannis Limperg -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.type_context import Mathlib.Lean3Lib.init.meta.rewrite_tactic import Mathlib.Lean3Lib.init.meta.simp_tactic import Mathlib.Lean3Lib.init.meta.smt.congruence_closure import Mathlib.Lean3Lib.init.control.combinators import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.meta.derive import Mathlib.Lean3Lib.init.meta.match_tactic import Mathlib.Lean3Lib.init.meta.congr_tactic import Mathlib.Lean3Lib.init.meta.case_tag universes l u v namespace Mathlib namespace tactic /- allows metavars -/ /- allow metavars and no subgoals -/ /- doesn't allows metavars -/ /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ namespace interactive /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. -/ /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ /-- The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ /-- Parse a current name and new name for `rename`. -/ /-- Parse the arguments of `rename`. -/ /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename x y -- rename x to y rename x → y -- ditto rename [x y, a b] -- rename x to y and a to b rename [x → y, a → b] -- ditto ``` Note that if there are multiple hypotheses called `x` in the context, then `rename x y` will rename *all* of them. If you want to rename only one, use `dedup` first. -/ /-- The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. 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. -/ /-- Similar to the `apply` tactic, but does not reorder goals. -/ /-- Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ /-- Similar to the `apply` tactic, but uses matching instead of unification. `apply_match t` is equivalent to `apply_with t {unify := ff}` -/ /-- This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution. -/ /-- This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes. Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`. -/ /-- This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails. -/ /-- Try to apply `assumption` to all goals. -/ /-- `change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal. `change u at h` will change a local hypothesis to `u`. `change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal. -/ /-- This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified. -/ /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ /-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode. -/ /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`. -/ /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations /-- `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 lemmas 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. -/ /-- An abbreviation for `rewrite`. -/ /-- `rewrite` followed by `assumption`. -/ /-- A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions. -/ /-- An abbreviation for `erewrite`. -/ /-- Returns the unique names of all hypotheses (local constants) in the context. -/ /-- Returns all hypotheses (local constants) from the context except those whose unique names are in `hyp_uids`. -/ /-- Apply `t` to the main goal and revert any new hypothesis in the generated goals. If `t` is a supported tactic or chain of supported tactics (e.g. `induction`, `cases`, `apply`, `constructor`), the generated goals are also tagged with case tags. You can then use `case` to focus such tagged goals. Two typical uses of `with_cases`: 1. Applying a custom eliminator: ``` lemma my_nat_rec : ∀ n {P : ℕ → Prop} (zero : P 0) (succ : ∀ n, P n → P (n + 1)), P n := ... example (n : ℕ) : n = n := begin with_cases { apply my_nat_rec n }, case zero { refl }, case succ : m ih { refl } end ``` 2. Enabling the use of `case` after a chain of case-splitting tactics: ``` example (n m : ℕ) : unit := begin with_cases { cases n; induction m }, case nat.zero nat.zero { exact () }, case nat.zero nat.succ : k { exact () }, case nat.succ nat.zero : i { exact () }, case nat.succ nat.succ : k i ih_i { exact () } end ``` -/ /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ /-- Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag` is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was applied. `rs` should contain, for each subgoal, the constructor name associated with that goal and the hypotheses that were introduced. -/ /-- 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₁` ire chosen automatically. `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 with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism. `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. `induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context. -/ /-- Focuses on a goal ('case') generated by `induction`, `cases` or `with_cases`. The goal is selected by giving one or more names which must match exactly one goal. A goal is matched if the given names are a suffix of its goal tag. Additionally, each name in the sequence can be abbreviated to a suffix of the corresponding name in the goal tag. Thus, a goal with tag ``` nat.zero, list.nil ``` can be selected with any of these invocations (among others): ``` case nat.zero list.nil {...} case nat.zero nil {...} case zero nil {...} case nil {...} ``` Additionally, the form ``` case C : N₀ ... Nₙ {...} ``` can be used to rename hypotheses introduced by the preceding `cases`/`induction`/`with_cases`, using the names `Nᵢ`. For example: ``` example (xs : list ℕ) : xs = xs := begin induction xs, case nil { reflexivity }, case cons : x xs ih { -- x : ℕ, xs : list ℕ, ih : xs = xs reflexivity } end ``` Note that this renaming functionality only work reliably *directly after* an `induction`/`cases`/`with_cases`. If you need to perform additional work after an `induction` or `cases` (e.g. introduce hypotheses in all goals), use `with_cases`. -/ /- TODO `case` could be generalised to work with zero names as well. The form case : x y z { ... } would select the first goal (or the first goal with a case tag), renaming hypotheses to `x, y, z`. The renaming functionality would be available only if the goal has a case tag. -/ /-- Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically. -/ /-- 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. 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. `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. `cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. `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. -/ /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ /-- Shorthand for `cases_matching` -/ /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_type* or and ``` -/ /-- Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic. -/ /-- Closes the main goal using `sorry`. -/ /-- Closes the main goal using `sorry`. -/ /-- The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ /-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds. `iterate n { t }` applies `t` `n` times. -/ /-- `repeat { t }` applies `t` to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat { t }` never fails. -/ /-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds. -/ /-- A do-nothing tactic that always succeeds. -/ /-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved. -/ /-- `abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically. -/ /-- `all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds. -/ /-- `any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds. -/ /-- `focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals. -/ /-- Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred. `assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present. -/ /-- `have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ /-- `suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. -/ /-- This tactic displays the current state in the tracing buffer. -/ /-- `trace a` displays `a` in the tracing buffer. -/ /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. -/ /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ /-- Similar to `constructor`, but only non-dependent premises are added as new goals. -/ /-- Applies the first constructor when the type of the target is an inductive data type with two constructors. -/ /-- Applies the second constructor when the type of the target is an inductive data type with two constructors. -/ /-- Applies the constructor when the type of the target is an inductive data type with one constructor. -/ /-- Replaces the target of the main goal by `false`. -/ /-- 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. -/ /-- `injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`. -/ end interactive /-- Decode a list of `simp_arg_type` into lists for each type. This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`. This version fails when an argument of the form `simp_arg_type.symm_expr` is included, so that `simp`-like tactics that do not (yet) support backwards rewriting should properly report an error but function normally on other inputs. -/ /-- Decode a list of `simp_arg_type` into lists for each type. This is the newer version of `decode_simp_arg_list`, and has a new name for backwards compatibility. This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`. -/ namespace interactive /-- 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 `hᵢ` is preceded by left arrow (`←` or `<-`), the simplification is performed in the reverse direction. 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 *` is a shorthand for `simp [*]`. `simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas `simp [-id_1, ... -id_n]` 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 non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target. `simp at *` simplifies all the hypotheses and the target. `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. `simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`. -/ /-- Just construct the simp set and trace it. Used for debugging. -/ /-- `simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target. As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`. -/ /-- `dsimp` is similar to `simp`, except that it only uses definitional equalities. -/ /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ /-- Shorter name for the tactic `reflexivity`. -/ /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`. -/ /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`. `transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead. -/ /-- Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations. -/ /-- An abbreviation for `ac_reflexivity`. -/ /-- Tries to prove the main goal using congruence closure. -/ /-- Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. -/ /-- Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`. -/ /-- `clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context. -/ /-- Similar to `unfold`, but only uses definitional equalities. -/ /-- Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants. -/ /-- This tactic unfolds all structure projections. -/ end interactive structure unfold_config extends simp_config where namespace interactive /-- Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions. As with `simp`, the `at` modifier can be used to specify locations for the unfolding. -/ /-- Similar to `unfold`, but does not iterate the unfolding. -/ /-- If the target of the main goal is an `opt_param`, assigns the default value. -/ /-- If the target of the main goal is an `auto_param`, executes the associated tactic. -/ /-- Fails if the given tactic succeeds. -/ /-- Succeeds if the given tactic fails. -/ /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ /-- `guard_hyp h : t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. -/ /-- `match_target t` fails if target does not match pattern `t`. -/ /-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`. -/ /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. -/ /-- If the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contradiction h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ /-- If the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contra h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ /-- Type check the given expression, and trace its type. -/ /-- Fail if there are unsolved goals. -/ /-- `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`. -/ /-- 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 either 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. -/ end interactive end tactic /- See add_interactive -/ /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ /-- Renames hypotheses with the same name. -/ namespace tactic /- Helper tactic for `mk_inj_eq -/ /- Auxiliary tactic for proving `I.C.inj_eq` lemmas. These lemmas are automatically generated by the equation compiler. Example: ``` list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) := by mk_inj_eq ``` -/ end tactic /- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/ theorem sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ : α) (a₂ : α) : sum.inl a₁ = sum.inl a₂ = (a₁ = a₂) := propext { mp := fun (h : sum.inl a₁ = sum.inl a₂) => sum.inl.inj h, mpr := fun (ᾰ : a₁ = a₂) => (fun (val val_1 : α) (e_2 : val = val_1) => congr_arg sum.inl e_2) a₁ a₂ ᾰ } theorem sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ : β) (b₂ : β) : sum.inr b₁ = sum.inr b₂ = (b₁ = b₂) := sorry theorem psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ : α) (a₂ : α) : psum.inl a₁ = psum.inl a₂ = (a₁ = a₂) := propext { mp := fun (h : psum.inl a₁ = psum.inl a₂) => psum.inl.inj h, mpr := fun (ᾰ : a₁ = a₂) => (fun (val val_1 : α) (e_2 : val = val_1) => congr_arg psum.inl e_2) a₁ a₂ ᾰ } theorem psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ : β) (b₂ : β) : psum.inr b₁ = psum.inr b₂ = (b₁ = b₂) := sorry theorem sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : sigma.mk a₁ b₁ = sigma.mk a₂ b₂ = (a₁ = a₂ ∧ b₁ == b₂) := sorry theorem psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : psigma.mk a₁ b₁ = psigma.mk a₂ b₂ = (a₁ = a₂ ∧ b₁ == b₂) := sorry theorem subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : { val := a₁, property := h₁ } = { val := a₂, property := h₂ } = (a₁ = a₂) := sorry theorem option.some.inj_eq {α : Type u} (a₁ : α) (a₂ : α) : some a₁ = some a₂ = (a₁ = a₂) := propext { mp := fun (h : some a₁ = some a₂) => option.some.inj h, mpr := fun (ᾰ : a₁ = a₂) => (fun (val val_1 : α) (e_1 : val = val_1) => congr_arg some e_1) a₁ a₂ ᾰ } theorem list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : List α) (h₂ : α) (t₂ : List α) : h₁ :: t₁ = h₂ :: t₂ = (h₁ = h₂ ∧ t₁ = t₂) := sorry theorem nat.succ.inj_eq (n₁ : ℕ) (n₂ : ℕ) : Nat.succ n₁ = Nat.succ n₂ = (n₁ = n₂) := propext { mp := fun (h : Nat.succ n₁ = Nat.succ n₂) => nat.succ.inj h, mpr := fun (ᾰ : n₁ = n₂) => (fun (n n_1 : ℕ) (e_1 : n = n_1) => congr_arg Nat.succ e_1) n₁ n₂ ᾰ } end Mathlib
ccd61f4983960644b0101f54b2ee21ea2a5d0ab6
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/bench/binarytrees.lean
d4e07e1f5be36324b197aab464cb97b1e3bb9d22
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
1,691
lean
inductive Tree | Nil | Node (l r : Tree) : Tree open Tree instance : Inhabited Tree := ⟨Nil⟩ -- This Function has an extra argument to suppress the -- common sub-expression elimination optimization partial def make' : UInt32 -> UInt32 -> Tree | n d := if d = 0 then Node Nil Nil else Node (make' n (d - 1)) (make' (n + 1) (d - 1)) -- build a tree def make (d : UInt32) := make' d d def check : Tree → UInt32 | Nil := 0 | (Node l r) := 1 + check l + check r def minN := 4 def out (s) (n : Nat) (t : UInt32) : IO Unit := IO.println (s ++ " of depth " ++ toString n ++ "\t check: " ++ toString t) -- allocate and check lots of trees partial def sumT : UInt32 -> UInt32 -> UInt32 -> UInt32 | d i t := if i = 0 then t else let a := check (make d); sumT d (i-1) (t + a) -- generate many trees partial def depth : Nat -> Nat -> List (Nat × Nat × Task UInt32) | d m := if d ≤ m then let n := 2 ^ (m - d + minN); (n, d, Task.mk (fun _ => sumT (UInt32.ofNat d) (UInt32.ofNat n) 0)) :: depth (d+2) m else [] def main : List String → IO UInt32 | [s] := do let n := s.toNat; let maxN := Nat.max (minN + 2) n; let stretchN := maxN + 1; -- stretch memory tree let c := check (make $ UInt32.ofNat stretchN); out "stretch tree" stretchN c; -- allocate a long lived tree let long := make $ UInt32.ofNat maxN; -- allocate, walk, and deallocate many bottom-up binary trees let vs := (depth minN maxN), -- `using` (parList $ evalTuple3 r0 r0 rseq) vs.mmap (fun ⟨m,d,i⟩ => out (toString m ++ "\t trees") d i.get); -- confirm the the long-lived binary tree still exists out "long lived tree" maxN (check long); pure 0 | _ := pure 1
ef56fc66afcaf0ebb85ebfae18d16f5a2e05a3e5
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/constructions/limits_of_products_and_equalizers.lean
a5acd213bbb0816b530af7603fe99f57e110ab2b
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
18,121
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.finite_products import category_theory.limits.preserves.shapes.products import category_theory.limits.preserves.shapes.equalizers import category_theory.limits.preserves.finite import category_theory.limits.constructions.finite_products_of_binary_products import category_theory.limits.constructions.equalizers import category_theory.limits.constructions.binary_products /-! # Constructing limits from products and equalizers. If a category has all products, and all equalizers, then it has all limits. Similarly, if it has all finite products, and all equalizers, then it has all finite limits. If a functor preserves all products and equalizers, then it preserves all limits. Similarly, if it preserves all finite products and equalizers, then it preserves all finite limits. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ open category_theory open opposite namespace category_theory.limits universes w v v₂ u u₂ variables {C : Type u} [category.{v} C] variables {J : Type w} [small_category J] -- We hide the "implementation details" inside a namespace namespace has_limit_of_has_products_of_has_equalizers variables {F : J ⥤ C} {c₁ : fan F.obj} {c₂ : fan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2)} (s t : c₁.X ⟶ c₂.X) (hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), s ≫ c₂.π.app ⟨f⟩ = c₁.π.app ⟨f.1.1⟩ ≫ F.map f.2) (ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), t ≫ c₂.π.app ⟨f⟩ = c₁.π.app ⟨f.1.2⟩) (i : fork s t) include hs ht /-- (Implementation) Given the appropriate product and equalizer cones, build the cone for `F` which is limiting if the given cones are also. -/ @[simps] def build_limit : cone F := { X := i.X, π := { app := λ j, i.ι ≫ c₁.π.app ⟨_⟩, naturality' := λ j₁ j₂ f, begin dsimp, rw [category.id_comp, category.assoc, ← hs ⟨⟨_, _⟩, f⟩, i.condition_assoc, ht], end} } variable {i} /-- (Implementation) Show the cone constructed in `build_limit` is limiting, provided the cones used in its construction are. -/ def build_is_limit (t₁ : is_limit c₁) (t₂ : is_limit c₂) (hi : is_limit i) : is_limit (build_limit s t hs ht i) := { lift := λ q, begin refine hi.lift (fork.of_ι _ _), { refine t₁.lift (fan.mk _ (λ j, _)), apply q.π.app j }, { apply t₂.hom_ext, intro j, discrete_cases, simp [hs, ht] }, end, uniq' := λ q m w, hi.hom_ext (i.equalizer_ext (t₁.hom_ext (λ j, by { cases j, simpa using w j }))) } end has_limit_of_has_products_of_has_equalizers open has_limit_of_has_products_of_has_equalizers /-- Given the existence of the appropriate (possibly finite) products and equalizers, we can construct a limit cone for `F`. (This assumes the existence of all equalizers, which is technically stronger than needed.) -/ noncomputable def limit_cone_of_equalizer_and_product (F : J ⥤ C) [has_limit (discrete.functor F.obj)] [has_limit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))] [has_equalizers C] : limit_cone F := { cone := _, is_limit := build_is_limit (pi.lift (λ f, limit.π (discrete.functor F.obj) ⟨_⟩ ≫ F.map f.2)) (pi.lift (λ f, limit.π (discrete.functor F.obj) ⟨f.1.2⟩)) (by simp) (by simp) (limit.is_limit _) (limit.is_limit _) (limit.is_limit _) } /-- Given the existence of the appropriate (possibly finite) products and equalizers, we know a limit of `F` exists. (This assumes the existence of all equalizers, which is technically stronger than needed.) -/ lemma has_limit_of_equalizer_and_product (F : J ⥤ C) [has_limit (discrete.functor F.obj)] [has_limit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))] [has_equalizers C] : has_limit F := has_limit.mk (limit_cone_of_equalizer_and_product F) /-- A limit can be realised as a subobject of a product. -/ noncomputable def limit_subobject_product [has_limits_of_size.{w w} C] (F : J ⥤ C) : limit F ⟶ ∏ (λ j, F.obj j) := (limit.iso_limit_cone (limit_cone_of_equalizer_and_product F)).hom ≫ equalizer.ι _ _ instance limit_subobject_product_mono [has_limits_of_size.{w w} C] (F : J ⥤ C) : mono (limit_subobject_product F) := mono_comp _ _ /-- Any category with products and equalizers has all limits. See <https://stacks.math.columbia.edu/tag/002N>. -/ lemma has_limits_of_has_equalizers_and_products [has_products.{w} C] [has_equalizers C] : has_limits_of_size.{w w} C := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F } } /-- Any category with finite products and equalizers has all finite limits. See <https://stacks.math.columbia.edu/tag/002O>. -/ lemma has_finite_limits_of_has_equalizers_and_finite_products [has_finite_products C] [has_equalizers C] : has_finite_limits C := ⟨λ J _ _, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F }⟩ variables {D : Type u₂} [category.{v₂} D] noncomputable theory section variables [has_limits_of_shape (discrete J) C] [has_limits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) C] [has_equalizers C] variables (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [preserves_limits_of_shape (discrete.{w} J) G] [preserves_limits_of_shape (discrete.{w} (Σ p : J × J, p.1 ⟶ p.2)) G] /-- If a functor preserves equalizers and the appropriate products, it preserves limits. -/ def preserves_limit_of_preserves_equalizers_and_product : preserves_limits_of_shape J G := { preserves_limit := λ K, begin let P := ∏ K.obj, let Q := ∏ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.2), let s : P ⟶ Q := pi.lift (λ f, limit.π (discrete.functor K.obj) ⟨_⟩ ≫ K.map f.2), let t : P ⟶ Q := pi.lift (λ f, limit.π (discrete.functor K.obj) ⟨f.1.2⟩), let I := equalizer s t, let i : I ⟶ P := equalizer.ι s t, apply preserves_limit_of_preserves_limit_cone (build_is_limit s t (by simp) (by simp) (limit.is_limit _) (limit.is_limit _) (limit.is_limit _)), refine is_limit.of_iso_limit (build_is_limit _ _ _ _ _ _ _) _, { exact fan.mk _ (λ j, G.map (pi.π _ j)) }, { exact fan.mk (G.obj Q) (λ f, G.map (pi.π _ f)) }, { apply G.map s }, { apply G.map t }, { intro f, dsimp, simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] }, { intro f, dsimp, simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] }, { apply fork.of_ι (G.map i) _, simp only [← G.map_comp, equalizer.condition] }, { apply is_limit_of_has_product_of_preserves_limit }, { apply is_limit_of_has_product_of_preserves_limit }, { apply is_limit_fork_map_of_is_limit, apply equalizer_is_equalizer }, refine cones.ext (iso.refl _) _, intro j, dsimp, simp, -- See note [dsimp, simp]. end } end /-- If G preserves equalizers and finite products, it preserves finite limits. -/ def preserves_finite_limits_of_preserves_equalizers_and_finite_products [has_equalizers C] [has_finite_products C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [∀ (J : Type) [fintype J], preserves_limits_of_shape (discrete J) G] : preserves_finite_limits G := ⟨λ _ _ _, by exactI preserves_limit_of_preserves_equalizers_and_product G⟩ /-- If G preserves equalizers and products, it preserves all limits. -/ def preserves_limits_of_preserves_equalizers_and_products [has_equalizers C] [has_products.{w} C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [∀ J, preserves_limits_of_shape (discrete.{w} J) G] : preserves_limits_of_size.{w w} G := { preserves_limits_of_shape := λ J 𝒥, by exactI preserves_limit_of_preserves_equalizers_and_product G } lemma has_finite_limits_of_has_terminal_and_pullbacks [has_terminal C] [has_pullbacks C] : has_finite_limits C := @@has_finite_limits_of_has_equalizers_and_finite_products _ (@@has_finite_products_of_has_binary_and_terminal _ (has_binary_products_of_has_terminal_and_pullbacks C) infer_instance) (@@has_equalizers_of_has_pullbacks_and_binary_products _ (has_binary_products_of_has_terminal_and_pullbacks C) infer_instance) /-- If G preserves terminal objects and pullbacks, it preserves all finite limits. -/ def preserves_finite_limits_of_preserves_terminal_and_pullbacks [has_terminal C] [has_pullbacks C] (G : C ⥤ D) [preserves_limits_of_shape (discrete.{0} pempty) G] [preserves_limits_of_shape walking_cospan G] : preserves_finite_limits G := begin haveI : has_finite_limits C := has_finite_limits_of_has_terminal_and_pullbacks, haveI : preserves_limits_of_shape (discrete walking_pair) G := preserves_binary_products_of_preserves_terminal_and_pullbacks G, exact @@preserves_finite_limits_of_preserves_equalizers_and_finite_products _ _ _ _ G (preserves_equalizers_of_preserves_pullbacks_and_binary_products G) (preserves_finite_products_of_preserves_binary_and_terminal G), end /-! We now dualize the above constructions, resorting to copy-paste. -/ -- We hide the "implementation details" inside a namespace namespace has_colimit_of_has_coproducts_of_has_coequalizers variables {F : J ⥤ C} {c₁ : cofan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1)} {c₂ : cofan F.obj} (s t : c₁.X ⟶ c₂.X) (hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app ⟨f⟩ ≫ s = F.map f.2 ≫ c₂.ι.app ⟨f.1.2⟩) (ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app ⟨f⟩ ≫ t = c₂.ι.app ⟨f.1.1⟩) (i : cofork s t) include hs ht /-- (Implementation) Given the appropriate coproduct and coequalizer cocones, build the cocone for `F` which is colimiting if the given cocones are also. -/ @[simps] def build_colimit : cocone F := { X := i.X, ι := { app := λ j, c₂.ι.app ⟨_⟩ ≫ i.π, naturality' := λ j₁ j₂ f, begin dsimp, rw [category.comp_id, ←reassoc_of (hs ⟨⟨_, _⟩, f⟩), i.condition, ←category.assoc, ht], end} } variable {i} /-- (Implementation) Show the cocone constructed in `build_colimit` is colimiting, provided the cocones used in its construction are. -/ def build_is_colimit (t₁ : is_colimit c₁) (t₂ : is_colimit c₂) (hi : is_colimit i) : is_colimit (build_colimit s t hs ht i) := { desc := λ q, begin refine hi.desc (cofork.of_π _ _), { refine t₂.desc (cofan.mk _ (λ j, _)), apply q.ι.app j }, { apply t₁.hom_ext, intro j, discrete_cases, simp [reassoc_of hs, reassoc_of ht] }, end, uniq' := λ q m w, hi.hom_ext (i.coequalizer_ext (t₂.hom_ext (λ j, by { cases j, simpa using w j }))) } end has_colimit_of_has_coproducts_of_has_coequalizers open has_colimit_of_has_coproducts_of_has_coequalizers /-- Given the existence of the appropriate (possibly finite) coproducts and coequalizers, we can construct a colimit cocone for `F`. (This assumes the existence of all coequalizers, which is technically stronger than needed.) -/ noncomputable def colimit_cocone_of_coequalizer_and_coproduct (F : J ⥤ C) [has_colimit (discrete.functor F.obj)] [has_colimit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1))] [has_coequalizers C] : colimit_cocone F := { cocone := _, is_colimit := build_is_colimit (sigma.desc (λ f, F.map f.2 ≫ colimit.ι (discrete.functor F.obj) ⟨f.1.2⟩)) (sigma.desc (λ f, colimit.ι (discrete.functor F.obj) ⟨f.1.1⟩)) (by simp) (by simp) (colimit.is_colimit _) (colimit.is_colimit _) (colimit.is_colimit _) } /-- Given the existence of the appropriate (possibly finite) coproducts and coequalizers, we know a colimit of `F` exists. (This assumes the existence of all coequalizers, which is technically stronger than needed.) -/ lemma has_colimit_of_coequalizer_and_coproduct (F : J ⥤ C) [has_colimit (discrete.functor F.obj)] [has_colimit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1))] [has_coequalizers C] : has_colimit F := has_colimit.mk (colimit_cocone_of_coequalizer_and_coproduct F) /-- A colimit can be realised as a quotient of a coproduct. -/ noncomputable def colimit_quotient_coproduct [has_colimits_of_size.{w w} C] (F : J ⥤ C) : ∐ (λ j, F.obj j) ⟶ colimit F := coequalizer.π _ _ ≫ (colimit.iso_colimit_cocone (colimit_cocone_of_coequalizer_and_coproduct F)).inv instance colimit_quotient_coproduct_epi [has_colimits_of_size.{w w} C] (F : J ⥤ C) : epi (colimit_quotient_coproduct F) := epi_comp _ _ /-- Any category with coproducts and coequalizers has all colimits. See <https://stacks.math.columbia.edu/tag/002P>. -/ lemma has_colimits_of_has_coequalizers_and_coproducts [has_coproducts.{w} C] [has_coequalizers C] : has_colimits_of_size.{w w} C := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI has_colimit_of_coequalizer_and_coproduct F } } /-- Any category with finite coproducts and coequalizers has all finite colimits. See <https://stacks.math.columbia.edu/tag/002Q>. -/ lemma has_finite_colimits_of_has_coequalizers_and_finite_coproducts [has_finite_coproducts C] [has_coequalizers C] : has_finite_colimits C := ⟨λ J _ _, { has_colimit := λ F, by exactI has_colimit_of_coequalizer_and_coproduct F }⟩ noncomputable theory section variables [has_colimits_of_shape (discrete.{w} J) C] [has_colimits_of_shape (discrete.{w} (Σ p : J × J, p.1 ⟶ p.2)) C] [has_coequalizers C] variables (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [preserves_colimits_of_shape (discrete.{w} J) G] [preserves_colimits_of_shape (discrete.{w} (Σ p : J × J, p.1 ⟶ p.2)) G] /-- If a functor preserves coequalizers and the appropriate coproducts, it preserves colimits. -/ def preserves_colimit_of_preserves_coequalizers_and_coproduct : preserves_colimits_of_shape J G := { preserves_colimit := λ K, begin let P := ∐ K.obj, let Q := ∐ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.1), let s : Q ⟶ P := sigma.desc (λ f, K.map f.2 ≫ colimit.ι (discrete.functor K.obj) ⟨_⟩), let t : Q ⟶ P := sigma.desc (λ f, colimit.ι (discrete.functor K.obj) ⟨f.1.1⟩), let I := coequalizer s t, let i : P ⟶ I := coequalizer.π s t, apply preserves_colimit_of_preserves_colimit_cocone (build_is_colimit s t (by simp) (by simp) (colimit.is_colimit _) (colimit.is_colimit _) (colimit.is_colimit _)), refine is_colimit.of_iso_colimit (build_is_colimit _ _ _ _ _ _ _) _, { exact cofan.mk (G.obj Q) (λ j, G.map (sigma.ι _ j)) }, { exact cofan.mk _ (λ f, G.map (sigma.ι _ f)) }, { apply G.map s }, { apply G.map t }, { intro f, dsimp, simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] }, { intro f, dsimp, simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] }, { apply cofork.of_π (G.map i) _, simp only [← G.map_comp, coequalizer.condition] }, { apply is_colimit_of_has_coproduct_of_preserves_colimit }, { apply is_colimit_of_has_coproduct_of_preserves_colimit }, { apply is_colimit_cofork_map_of_is_colimit, apply coequalizer_is_coequalizer }, refine cocones.ext (iso.refl _) _, intro j, dsimp, simp, -- See note [dsimp, simp]. end } end /-- If G preserves coequalizers and finite coproducts, it preserves finite colimits. -/ def preserves_finite_colimits_of_preserves_coequalizers_and_finite_coproducts [has_coequalizers C] [has_finite_coproducts C] (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [∀ J [fintype J], preserves_colimits_of_shape (discrete.{0} J) G] : preserves_finite_colimits G := ⟨λ _ _ _, by exactI preserves_colimit_of_preserves_coequalizers_and_coproduct G⟩ /-- If G preserves coequalizers and coproducts, it preserves all colimits. -/ def preserves_colimits_of_preserves_coequalizers_and_coproducts [has_coequalizers C] [has_coproducts.{w} C] (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [∀ J, preserves_colimits_of_shape (discrete.{w} J) G] : preserves_colimits_of_size.{w} G := { preserves_colimits_of_shape := λ J 𝒥, by exactI preserves_colimit_of_preserves_coequalizers_and_coproduct G } lemma has_finite_colimits_of_has_initial_and_pushouts [has_initial C] [has_pushouts C] : has_finite_colimits C := @@has_finite_colimits_of_has_coequalizers_and_finite_coproducts _ (@@has_finite_coproducts_of_has_binary_and_initial _ (has_binary_coproducts_of_has_initial_and_pushouts C) infer_instance) (@@has_coequalizers_of_has_pushouts_and_binary_coproducts _ (has_binary_coproducts_of_has_initial_and_pushouts C) infer_instance) /-- If G preserves initial objects and pushouts, it preserves all finite colimits. -/ def preserves_finite_colimits_of_preserves_initial_and_pushouts [has_initial C] [has_pushouts C] (G : C ⥤ D) [preserves_colimits_of_shape (discrete.{0} pempty) G] [preserves_colimits_of_shape walking_span G] : preserves_finite_colimits G := begin haveI : has_finite_colimits C := has_finite_colimits_of_has_initial_and_pushouts, haveI : preserves_colimits_of_shape (discrete walking_pair) G := preserves_binary_coproducts_of_preserves_initial_and_pushouts G, exact @@preserves_finite_colimits_of_preserves_coequalizers_and_finite_coproducts _ _ _ _ G (preserves_coequalizers_of_preserves_pushouts_and_binary_coproducts G) (preserves_finite_coproducts_of_preserves_binary_and_initial G), end end category_theory.limits
631832fb3c65c6da05b8ae921c1557bdadebdcb7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/induction.lean
c00ea629e2a772ab0515fc9362caa8d2fe005e29
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,599
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.coeff import Mathlib.PostPort universes u namespace Mathlib /-! # Theory of univariate polynomials The main results are `induction_on` and `as_sum`. -/ namespace polynomial theorem sum_C_mul_X_eq {R : Type u} [semiring R] (p : polynomial R) : (finsupp.sum p fun (n : ℕ) (a : R) => coe_fn C a * X ^ n) = p := Eq.trans (finset.sum_congr rfl fun (n : ℕ) (hn : n ∈ finsupp.support p) => Eq.symm single_eq_C_mul_X) (finsupp.sum_single p) theorem sum_monomial_eq {R : Type u} [semiring R] (p : polynomial R) : (finsupp.sum p fun (n : ℕ) (a : R) => coe_fn (monomial n) a) = p := sorry protected theorem induction_on {R : Type u} [semiring R] {M : polynomial R → Prop} (p : polynomial R) (h_C : ∀ (a : R), M (coe_fn C a)) (h_add : ∀ (p q : polynomial R), M p → M q → M (p + q)) (h_monomial : ∀ (n : ℕ) (a : R), M (coe_fn C a * X ^ n) → M (coe_fn C a * X ^ (n + 1))) : M p := sorry /-- To prove something about polynomials, it suffices to show the condition is closed under taking sums, and it holds for monomials. -/ protected theorem induction_on' {R : Type u} [semiring R] {M : polynomial R → Prop} (p : polynomial R) (h_add : ∀ (p q : polynomial R), M p → M q → M (p + q)) (h_monomial : ∀ (n : ℕ) (a : R), M (coe_fn (monomial n) a)) : M p := polynomial.induction_on p (h_monomial 0) h_add fun (n : ℕ) (a : R) (h : M (coe_fn C a * X ^ n)) => eq.mpr (id (Eq._oldrec (Eq.refl (M (coe_fn C a * X ^ (n + 1)))) (Eq.symm single_eq_C_mul_X))) (h_monomial (n + 1) a) theorem coeff_mul_monomial {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) (d : ℕ) (r : R) : coeff (p * coe_fn (monomial n) r) (d + n) = coeff p d * r := sorry theorem coeff_monomial_mul {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) (d : ℕ) (r : R) : coeff (coe_fn (monomial n) r * p) (d + n) = r * coeff p d := sorry -- This can already be proved by `simp`. theorem coeff_mul_monomial_zero {R : Type u} [semiring R] (p : polynomial R) (d : ℕ) (r : R) : coeff (p * coe_fn (monomial 0) r) d = coeff p d * r := coeff_mul_monomial p 0 d r -- This can already be proved by `simp`. theorem coeff_monomial_zero_mul {R : Type u} [semiring R] (p : polynomial R) (d : ℕ) (r : R) : coeff (coe_fn (monomial 0) r * p) d = r * coeff p d := coeff_monomial_mul p 0 d r
6c344782fd1c50787a01f7e67e4b6e993b44bca7
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/list/comb.lean
402bb15c38fdc4071048d64297bda775da857493
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
24,593
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Haitao Zhang, Floris van Doorn List combinators. -/ import data.list.basic data.equiv open nat prod decidable function helper_tactics namespace list variables {A B C : Type} section replicate -- 'replicate i n' returns the list contain i copies of n. definition replicate : ℕ → A → list A | 0 a := [] | (succ n) a := a :: replicate n a theorem length_replicate : ∀ (i : ℕ) (a : A), length (replicate i a) = i | 0 a := rfl | (succ i) a := calc length (replicate (succ i) a) = length (replicate i a) + 1 : rfl ... = i + 1 : length_replicate end replicate /- map -/ 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 lemma map_concat (f : A → B) (a : A) : Πl, map f (concat a l) = concat (f a) (map f l) | nil := rfl | (b::l) := begin rewrite [concat_cons, +map_cons, concat_cons, map_concat] end lemma map_append (f : A → B) : ∀ l₁ l₂, map f (l₁++l₂) = (map f l₁)++(map f l₂) | nil := take l, rfl | (a::l) := take l', begin rewrite [append_cons, *map_cons, append_cons, map_append] end lemma map_reverse (f : A → B) : Πl, map f (reverse l) = reverse (map f l) | nil := rfl | (b::l) := begin rewrite [reverse_cons, +map_cons, reverse_cons, map_concat, map_reverse] end lemma map_singleton (f : A → B) (a : A) : map f [a] = [f a] := rfl theorem map_id [simp] : ∀ l : list A, map id l = l | [] := rfl | (x::xs) := begin rewrite [map_cons, map_id] end theorem map_id' {f : A → A} (H : ∀x, f x = x) : ∀ l : list A, map f l = l | [] := rfl | (x::xs) := begin rewrite [map_cons, H, map_id'] end theorem map_map [simp] (g : B → C) (f : A → B) : ∀ l, 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 length_map [simp] (f : A → B) : ∀ l : list A, length (map f l) = length l | [] := by esimp | (a :: l) := show length (map f l) + 1 = length l + 1, by rewrite (length_map l) theorem map_ne_nil_of_ne_nil (f : A → B) {l : list A} (H : l ≠ nil) : map f l ≠ nil := suppose map f l = nil, have length (map f l) = length l, from !length_map, have 0 = length l, from calc 0 = length nil : length_nil ... = length (map f l) : {eq.symm `map f l = nil`} ... = length l : this, have l = nil, from eq_nil_of_length_eq_zero (eq.symm this), H this theorem mem_map {A B : Type} (f : A → B) : ∀ {a l}, a ∈ l → f a ∈ map f l | a [] i := absurd i !not_mem_nil | a (x::xs) i := or.elim (eq_or_mem_of_mem_cons i) (suppose a = x, by rewrite [this, map_cons]; apply mem_cons) (suppose a ∈ xs, or.inr (mem_map this)) theorem exists_of_mem_map {A B : Type} {f : A → B} {b : B} : ∀{l}, b ∈ map f l → ∃a, a ∈ l ∧ f a = b | [] H := false.elim H | (c::l) H := or.elim (iff.mp !mem_cons_iff H) (suppose b = f c, exists.intro c (and.intro !mem_cons (eq.symm this))) (suppose b ∈ map f l, obtain a (Hl : a ∈ l) (Hr : f a = b), from exists_of_mem_map this, exists.intro a (and.intro (mem_cons_of_mem _ Hl) Hr)) theorem eq_of_map_const {A B : Type} {b₁ b₂ : B} : ∀ {l : list A}, b₁ ∈ map (const A b₂) l → b₁ = b₂ | [] h := absurd h !not_mem_nil | (a::l) h := or.elim (eq_or_mem_of_mem_cons h) (suppose b₁ = b₂, this) (suppose b₁ ∈ map (const A b₂) l, eq_of_map_const this) definition map₂ (f : A → B → C) : list A → list B → list C | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys theorem map₂_nil1 (f : A → B → C) : ∀ (l : list B), map₂ f [] l = [] | [] := rfl | (a::y) := rfl theorem map₂_nil2 (f : A → B → C) : ∀ (l : list A), map₂ f l [] = [] | [] := rfl | (a::y) := rfl theorem length_map₂ : ∀(f : A → B → C) x y, length (map₂ f x y) = min (length x) (length y) | f [] [] := rfl | f (xh::xr) [] := rfl | f [] (yh::yr) := rfl | f (xh::xr) (yh::yr) := calc length (map₂ f (xh::xr) (yh::yr)) = length (map₂ f xr yr) + 1 : rfl ... = min (length xr) (length yr) + 1 : length_map₂ ... = min (length (xh::xr)) (length (yh::yr)) : min_succ_succ /- filter -/ definition filter (p : A → Prop) [h : decidable_pred p] : list A → list A | [] := [] | (a::l) := if p a then a :: filter l else filter l theorem filter_nil [simp] (p : A → Prop) [h : decidable_pred p] : filter p [] = [] theorem filter_cons_of_pos [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa theorem filter_cons_of_neg [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa theorem of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain !not_mem_nil | (b::l) ain := by_cases (assume pb : p b, have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, by rewrite [-this at pb]; exact pb) (suppose a ∈ filter p l, of_mem_filter this)) (suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (of_mem_filter ain)) theorem mem_of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → a ∈ l | [] ain := absurd ain !not_mem_nil | (b::l) ain := by_cases (λ pb : p b, have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, by rewrite this; exact !mem_cons) (suppose a ∈ filter p l, mem_cons_of_mem _ (mem_of_mem_filter this))) (suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (mem_cons_of_mem _ (mem_of_mem_filter ain))) theorem mem_filter_of_mem {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | [] ain pa := absurd ain !not_mem_nil | (b::l) ain pa := by_cases (λ pb : p b, or.elim (eq_or_mem_of_mem_cons ain) (λ aeqb : a = b, by rewrite [filter_cons_of_pos _ pb, aeqb]; exact !mem_cons) (λ ainl : a ∈ l, by rewrite [filter_cons_of_pos _ pb]; exact (mem_cons_of_mem _ (mem_filter_of_mem ainl pa)))) (λ npb : ¬ p b, or.elim (eq_or_mem_of_mem_cons ain) (λ aeqb : a = b, absurd (eq.rec_on aeqb pa) npb) (λ ainl : a ∈ l, by rewrite [filter_cons_of_neg _ npb]; exact (mem_filter_of_mem ainl pa))) theorem filter_sub [simp] {p : A → Prop} [h : decidable_pred p] (l : list A) : filter p l ⊆ l := λ a ain, mem_of_mem_filter ain theorem filter_append {p : A → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list A), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := by_cases (suppose p a, by rewrite [append_cons, *filter_cons_of_pos _ this, filter_append]) (suppose ¬ p a, by rewrite [append_cons, *filter_cons_of_neg _ this, filter_append]) /- foldl & foldr -/ definition foldl (f : A → B → A) : A → list B → A | a [] := a | a (b :: l) := foldl (f a b) l theorem foldl_nil [simp] (f : A → B → A) (a : A) : foldl f a [] = a theorem foldl_cons [simp] (f : A → B → A) (a : A) (b : B) (l : list B) : foldl f a (b::l) = foldl f (f a b) l definition foldr (f : A → B → B) : B → list A → B | b [] := b | b (a :: l) := f a (foldr b l) theorem foldr_nil [simp] (f : A → B → B) (b : B) : foldr f b [] = b theorem foldr_cons [simp] (f : A → B → B) (b : B) (a : A) (l : list A) : foldr f b (a::l) = f a (foldr f 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 (f a b) c = f a (f 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 theorem foldl_append [simp] (f : B → A → B) : ∀ (b : B) (l₁ l₂ : list A), foldl f b (l₁++l₂) = foldl f (foldl f b l₁) l₂ | b [] l₂ := rfl | b (a::l₁) l₂ := by rewrite [append_cons, *foldl_cons, foldl_append] theorem foldr_append [simp] (f : A → B → B) : ∀ (b : B) (l₁ l₂ : list A), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by rewrite [append_cons, *foldr_cons, foldr_append] /- all & any -/ definition all (l : list A) (p : A → Prop) : Prop := foldr (λ a r, p a ∧ r) true l definition any (l : list A) (p : A → Prop) : Prop := foldr (λ a r, p a ∨ r) false l theorem all_nil_eq [simp] (p : A → Prop) : all [] p = true theorem all_nil (p : A → Prop) : all [] p := trivial theorem all_cons_eq (p : A → Prop) (a : A) (l : list A) : all (a::l) p = (p a ∧ all l p) theorem all_cons {p : A → Prop} {a : A} {l : list A} (H1 : p a) (H2 : all l p) : all (a::l) p := and.intro H1 H2 theorem all_of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → all l p := assume h, by rewrite [all_cons_eq at h]; exact (and.elim_right h) theorem of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → p a := assume h, by rewrite [all_cons_eq at h]; exact (and.elim_left h) theorem all_cons_of_all {p : A → Prop} {a : A} {l : list A} : p a → all l p → all (a::l) p := assume pa alllp, and.intro pa alllp theorem all_implies {p q : A → Prop} : ∀ {l}, all l p → (∀ x, p x → q x) → all l q | [] h₁ h₂ := trivial | (a::l) h₁ h₂ := have all l q, from all_implies (all_of_all_cons h₁) h₂, have q a, from h₂ a (of_all_cons h₁), all_cons_of_all this `all l q` theorem of_mem_of_all {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → all l p → p a | [] h₁ h₂ := absurd h₁ !not_mem_nil | (b::l) h₁ h₂ := or.elim (eq_or_mem_of_mem_cons h₁) (suppose a = b, by rewrite [all_cons_eq at h₂, -this at h₂]; exact (and.elim_left h₂)) (suppose a ∈ l, have all l p, by rewrite [all_cons_eq at h₂]; exact (and.elim_right h₂), of_mem_of_all `a ∈ l` this) theorem all_of_forall {p : A → Prop} : ∀ {l}, (∀a, a ∈ l → p a) → all l p | [] H := !all_nil | (a::l) H := all_cons (H a !mem_cons) (all_of_forall (λ a' H', H a' (mem_cons_of_mem _ H'))) theorem any_nil [simp] (p : A → Prop) : any [] p = false theorem any_cons [simp] (p : A → Prop) (a : A) (l : list A) : any (a::l) p = (p a ∨ any l p) theorem any_of_mem {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → p a → any l p | [] i h := absurd i !not_mem_nil | (b::l) i h := or.elim (eq_or_mem_of_mem_cons i) (suppose a = b, by rewrite [-this]; exact (or.inl h)) (suppose a ∈ l, have any l p, from any_of_mem this h, or.inr this) theorem exists_of_any {p : A → Prop} : ∀{l : list A}, any l p → ∃a, a ∈ l ∧ p a | [] H := false.elim H | (b::l) H := or.elim H (assume H1 : p b, exists.intro b (and.intro !mem_cons H1)) (assume H1 : any l p, obtain a (H2l : a ∈ l) (H2r : p a), from exists_of_any H1, exists.intro a (and.intro (mem_cons_of_mem b H2l) H2r)) definition decidable_all (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (all l p) | [] := 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 l p) Hn) end definition decidable_any (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (any l p) | [] := 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 /- zip & unzip -/ 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 [simp] : unzip (@nil (A × B)) = ([], []) theorem unzip_cons [simp] (a : A) (b : B) (l : list (A × B)) : unzip ((a, b) :: l) = match unzip l with (la, lb) := (a :: la, b :: lb) end := rfl 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, eapply prod.cases_on (unzip l), intro la lb r, rewrite -r end section mapAccumR variable {S : Type} -- This runs a function over a list returning the intermediate results and a -- a final result. definition mapAccumR : (A → S → S × B) → list A → S → (S × list B) | f [] c := (c, []) | f (y::yr) c := let r := mapAccumR f yr c in let z := f y (pr₁ r) in (pr₁ z, pr₂ z :: pr₂ r) theorem length_mapAccumR : ∀ (f : A → S → S × B) (x : list A) (s : S), length (pr₂ (mapAccumR f x s)) = length x | f (a::x) s := calc length (pr₂ (mapAccumR f (a::x) s)) = length x + 1 : { length_mapAccumR f x s } ... = length (a::x) : rfl | f [] s := calc length (pr₂ (mapAccumR f [] s)) = 0 : rfl end mapAccumR section mapAccumR₂ variable {S : Type} -- This runs a function over two lists returning the intermediate results and a -- a final result. definition mapAccumR₂ : (A → B → S → S × C) → list A → list B → S → S × list C | f [] _ c := (c,[]) | f _ [] c := (c,[]) | f (x::xr) (y::yr) c := let r := mapAccumR₂ f xr yr c in let q := f x y (pr₁ r) in (pr₁ q, pr₂ q :: (pr₂ r)) theorem length_mapAccumR₂ : ∀ (f : A → B → S → S × C) (x : list A) (y : list B) (c : S), length (pr₂ (mapAccumR₂ f x y c)) = min (length x) (length y) | f (a::x) (b::y) c := calc length (pr₂ (mapAccumR₂ f (a::x) (b::y) c)) = length (pr₂ (mapAccumR₂ f x y c)) + 1 : rfl ... = min (length x) (length y) + 1 : length_mapAccumR₂ f x y c ... = min (length (a::x)) (length (b::y)) : min_succ_succ | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end mapAccumR₂ /- flat -/ definition flat (l : list (list A)) : list A := foldl append nil l /- product -/ section product definition product : list A → list B → list (A × B) | [] l₂ := [] | (a::l₁) l₂ := map (λ b, (a, b)) l₂ ++ product l₁ l₂ theorem nil_product (l : list B) : product (@nil A) l = [] theorem product_cons (a : A) (l₁ : list A) (l₂ : list B) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ theorem product_nil : ∀ (l : list A), product l (@nil B) = [] | [] := rfl | (a::l) := by rewrite [product_cons, map_nil, product_nil] theorem eq_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → a₁ = a := assume ain, have pr1 (a₁, b₁) ∈ map pr1 (map (λ b, (a, b)) l), from mem_map pr1 ain, have a₁ ∈ map (λb, a) l, by revert this; rewrite [map_map, ↑pr1]; intro this; assumption, eq_of_map_const this theorem mem_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → b₁ ∈ l := assume ain, have pr2 (a₁, b₁) ∈ map pr2 (map (λ b, (a, b)) l), from mem_map pr2 ain, have b₁ ∈ map (λx, x) l, by rewrite [map_map at this, ↑pr2 at this]; exact this, by rewrite [map_id at this]; exact this theorem mem_product {a : A} {b : B} : ∀ {l₁ l₂}, a ∈ l₁ → b ∈ l₂ → (a, b) ∈ product l₁ l₂ | [] l₂ h₁ h₂ := absurd h₁ !not_mem_nil | (x::l₁) l₂ h₁ h₂ := or.elim (eq_or_mem_of_mem_cons h₁) (assume aeqx : a = x, have (a, b) ∈ map (λ b, (a, b)) l₂, from mem_map _ h₂, begin rewrite [-aeqx, product_cons], exact mem_append_left _ this end) (assume ainl₁ : a ∈ l₁, have (a, b) ∈ product l₁ l₂, from mem_product ainl₁ h₂, begin rewrite [product_cons], exact mem_append_right _ this end) theorem mem_of_mem_product_left {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → a ∈ l₁ | [] l₂ h := absurd h !not_mem_nil | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, have a = x, from eq_of_mem_map_pair₁ this, by rewrite this; exact !mem_cons) (suppose (a, b) ∈ product l₁ l₂, have a ∈ l₁, from mem_of_mem_product_left this, mem_cons_of_mem _ this) theorem mem_of_mem_product_right {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → b ∈ l₂ | [] l₂ h := absurd h !not_mem_nil | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, mem_of_mem_map_pair₁ this) (suppose (a, b) ∈ product l₁ l₂, mem_of_mem_product_right this) theorem length_product : ∀ (l₁ : list A) (l₂ : list B), length (product l₁ l₂) = length l₁ * length l₂ | [] l₂ := by rewrite [length_nil, zero_mul] | (x::l₁) l₂ := have length (product l₁ l₂) = length l₁ * length l₂, from length_product l₁ l₂, by rewrite [product_cons, length_append, length_cons, length_map, this, right_distrib, one_mul, add.comm] end product -- new for list/comb dependent map theory definition dinj₁ (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), a1 ≠ a2 → (f a1 h1) ≠ (f a2 h2) definition dinj (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), (f a1 h1) = (f a2 h2) → a1 = a2 definition dmap (p : A → Prop) [h : decidable_pred p] (f : Π a, p a → B) : list A → list B | [] := [] | (a::l) := if P : (p a) then cons (f a P) (dmap l) else (dmap l) -- properties of dmap section dmap variable {p : A → Prop} variable [h : decidable_pred p] include h variable {f : Π a, p a → B} lemma dmap_nil : dmap p f [] = [] := rfl lemma dmap_cons_of_pos {a : A} (P : p a) : ∀ l, dmap p f (a::l) = (f a P) :: dmap p f l := λ l, dif_pos P lemma dmap_cons_of_neg {a : A} (P : ¬ p a) : ∀ l, dmap p f (a::l) = dmap p f l := λ l, dif_neg P lemma mem_dmap : ∀ {l : list A} {a} (Pa : p a), a ∈ l → (f a Pa) ∈ dmap p f l | [] := take a Pa Pinnil, by contradiction | (a::l) := take b Pb Pbin, or.elim (eq_or_mem_of_mem_cons Pbin) (assume Pbeqa, begin rewrite [eq.symm Pbeqa, dmap_cons_of_pos Pb], exact !mem_cons end) (assume Pbinl, decidable.rec_on (h a) (assume Pa, begin rewrite [dmap_cons_of_pos Pa], apply mem_cons_of_mem, exact mem_dmap Pb Pbinl end) (assume nPa, begin rewrite [dmap_cons_of_neg nPa], exact mem_dmap Pb Pbinl end)) lemma exists_of_mem_dmap : ∀ {l : list A} {b : B}, b ∈ dmap p f l → ∃ a P, a ∈ l ∧ b = f a P | [] := take b, by rewrite dmap_nil; contradiction | (a::l) := take b, decidable.rec_on (h a) (assume Pa, begin rewrite [dmap_cons_of_pos Pa, mem_cons_iff], intro Pb, cases Pb with Peq Pin, exact exists.intro a (exists.intro Pa (and.intro !mem_cons Peq)), have Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, from exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end) (assume nPa, begin rewrite [dmap_cons_of_neg nPa], intro Pin, have Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, from exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end) lemma map_dmap_of_inv_of_pos {g : B → A} (Pinv : ∀ a (Pa : p a), g (f a Pa) = a) : ∀ {l : list A}, (∀ ⦃a⦄, a ∈ l → p a) → map g (dmap p f l) = l | [] := assume Pl, by rewrite [dmap_nil, map_nil] | (a::l) := assume Pal, have Pa : p a, from Pal a !mem_cons, have Pl : ∀ a, a ∈ l → p a, from take x Pxin, Pal x (mem_cons_of_mem a Pxin), by rewrite [dmap_cons_of_pos Pa, map_cons, Pinv, map_dmap_of_inv_of_pos Pl] lemma mem_of_dinj_of_mem_dmap (Pdi : dinj p f) : ∀ {l : list A} {a} (Pa : p a), (f a Pa) ∈ dmap p f l → a ∈ l | [] := take a Pa Pinnil, by contradiction | (b::l) := take a Pa Pmap, decidable.rec_on (h b) (λ Pb, begin rewrite (dmap_cons_of_pos Pb) at Pmap, rewrite mem_cons_iff at Pmap, rewrite mem_cons_iff, apply (or_of_or_of_imp_of_imp Pmap), apply Pdi, apply mem_of_dinj_of_mem_dmap Pa end) (λ nPb, begin rewrite (dmap_cons_of_neg nPb) at Pmap, apply mem_cons_of_mem, exact mem_of_dinj_of_mem_dmap Pa Pmap end) lemma not_mem_dmap_of_dinj_of_not_mem (Pdi : dinj p f) {l : list A} {a} (Pa : p a) : a ∉ l → (f a Pa) ∉ dmap p f l := not.mto (mem_of_dinj_of_mem_dmap Pdi Pa) end dmap section open equiv definition list_equiv_of_equiv {A B : Type} : A ≃ B → list A ≃ list B | (mk f g l r) := mk (map f) (map g) begin intros, rewrite [map_map, id_of_left_inverse l, map_id], try reflexivity end begin intros, rewrite [map_map, id_of_right_inverse r, map_id], try reflexivity end private definition to_nat : list nat → nat | [] := 0 | (x::xs) := succ (mkpair (to_nat xs) x) open prod.ops private definition of_nat.F : Π (n : nat), (Π m, m < n → list nat) → list nat | 0 f := [] | (succ n) f := (unpair n).2 :: f (unpair n).1 (unpair_lt n) private definition of_nat : nat → list nat := well_founded.fix of_nat.F private lemma of_nat_zero : of_nat 0 = [] := well_founded.fix_eq of_nat.F 0 private lemma of_nat_succ (n : nat) : of_nat (succ n) = (unpair n).2 :: of_nat (unpair n).1 := well_founded.fix_eq of_nat.F (succ n) private lemma to_nat_of_nat (n : nat) : to_nat (of_nat n) = n := nat.case_strong_induction_on n _ (λ n ih, begin rewrite of_nat_succ, unfold to_nat, have to_nat (of_nat (unpair n).1) = (unpair n).1, from ih _ (le_of_lt_succ (unpair_lt n)), rewrite this, rewrite mkpair_unpair end) private lemma of_nat_to_nat : ∀ (l : list nat), of_nat (to_nat l) = l | [] := rfl | (x::xs) := begin unfold to_nat, rewrite of_nat_succ, rewrite *unpair_mkpair, esimp, congruence, apply of_nat_to_nat end definition list_nat_equiv_nat : list nat ≃ nat := mk to_nat of_nat of_nat_to_nat to_nat_of_nat definition list_equiv_self_of_equiv_nat {A : Type} : A ≃ nat → list A ≃ A := suppose A ≃ nat, calc list A ≃ list nat : list_equiv_of_equiv this ... ≃ nat : list_nat_equiv_nat ... ≃ A : this end end list attribute list.decidable_any [instance] attribute list.decidable_all [instance]
5d2d6242eac6338e9b9bb7158378467aaa08dc98
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/pullConstantThroughUnion3.lean
678301a6ab107d312aa3b20e4241eb57c10c809a
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
1,985
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..UDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int constant integer_2: const int constant integer_3: const int theorem Rule: forall (Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL (((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (table rel_emp) )) :SQL Γ _) = denoteSQL ((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (((SELECT1 (e2p (constantExpr integer_2)) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (e2p (constantExpr integer_2)) FROM1 (table rel_emp) ))) ) : SQL Γ _):= begin intros, unfold_all_denotations, funext, simp, UDP, end
8d1f457deb3458e45cd05b672d0c08eb3e0dd712
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/ext.lean
80b621347b8b1af06dc5e9089c356d376b52cd43
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
10,371
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.rcases data.list.defs data.prod data.sum universes u₁ u₂ open interactive interactive.types open lean.parser nat tactic /-- `derive_struct_ext_lemma n` generates two extensionality lemmas based on the equality of all non-propositional projections. On the following: ``` @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` `derive_struct_lemma` generates: ``` lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ meta def derive_struct_ext_lemma (n : name) : tactic name := do e ← get_env, fs ← e.structure_fields n, d ← get_decl n, n ← resolve_constant n, let r := @expr.const tt n $ d.univ_params.map level.param, (args,_) ← infer_type r >>= mk_local_pis, let args := args.map expr.to_implicit_local_const, let t := r.mk_app args, x ← mk_local_def `x t, y ← mk_local_def `y t, let args_x := args ++ [x], let args_y := args ++ [y], bs ← fs.mmap $ λ f, do { d ← get_decl (n ++ f), let a := @expr.const tt (n ++ f) $ d.univ_params.map level.param, t ← infer_type a, s ← infer_type t, if s ≠ `(Prop) then do let x := a.mk_app args_x, let y := a.mk_app args_y, t ← infer_type x, t' ← infer_type y, some <$> if t = t' then mk_app `eq [x,y] >>= mk_local_def `h else mk_mapp `heq [none,x,none,y] >>= mk_local_def `h else pure none }, let bs := bs.filter_map id, eq_t ← mk_app `eq [x,y], t ← pis (args ++ [x,y] ++ bs) eq_t, pr ← run_async $ do { (_,pr) ← solve_aux t (do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, bs.mmap' (λ _, do e ← intro1, cases e), reflexivity }), instantiate_mvars pr }, let decl_n := n <.> "ext", add_decl (declaration.thm decl_n d.univ_params t pr), bs ← bs.mmap infer_type, let rhs := expr.mk_and_lst bs, iff_t ← mk_app `iff [eq_t,rhs], t ← pis (args ++ [x,y]) iff_t, pr ← run_async $ do { (_,pr) ← solve_aux t $ do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, split, solve1 $ do { h ← intro1, hs ← injection h, subst_vars, repeat (refine ``( and.intro _ _ ) >> reflexivity ), done <|> reflexivity }, solve1 $ do { repeat (do refine ``(and_imp.mpr _), h ← intro1, cases h, skip ), h ← intro1, cases h, reflexivity } }, instantiate_mvars pr }, add_decl (declaration.thm (n <.> "ext_iff") d.univ_params t pr), pure decl_n meta def get_ext_subject : expr → tactic name | (expr.pi n bi d b) := do v ← mk_local' n bi d, b' ← whnf $ b.instantiate_var v, get_ext_subject b' | (expr.app _ e) := do t ← infer_type e >>= instantiate_mvars >>= head_beta, if t.get_app_fn.is_constant then pure $ t.get_app_fn.const_name else if t.is_pi then pure $ name.mk_numeral 0 name.anonymous else if t.is_sort then pure $ name.mk_numeral 1 name.anonymous else do t ← pp t, fail format!"only constants and Pi types are supported: {t}" | e := fail format!"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}" open native @[reducible] def ext_param_type := option name ⊕ option name meta def opt_minus : lean.parser (option name → ext_param_type) := sum.inl <$ tk "-" <|> pure sum.inr meta def ext_param := opt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets "(" ")" (tk "→" <|> tk "->") <|> none <$ tk "*" <|> some <$> ident ) meta def saturate_fun : name → tactic expr | (name.mk_numeral 0 name.anonymous) := do v₀ ← mk_mvar, v₁ ← mk_mvar, return $ v₀.imp v₁ | (name.mk_numeral 1 name.anonymous) := do u ← mk_meta_univ, pure $ expr.sort u | n := do e ← resolve_constant n >>= mk_const, a ← get_arity e, e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar) meta def equiv_type_constr (n n' : name) : tactic unit := do e ← saturate_fun n, e' ← saturate_fun n', unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types" /-- Tag lemmas of the form: ``` @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The attribute indexes extensionality lemma using the type of the objects (i.e. `my_collection`) which it gets from the statement of the lemma. In some cases, the same lemma can be used to state the extensionality of multiple types that are definitionally equivalent. ``` attribute [ext [(→),thunk,stream]] funext ``` Those parameters are cumulative. The following are equivalent: ``` attribute [ext [(→),thunk]] funext attribute [ext [stream]] funext ``` and ``` attribute [ext [(→),thunk,stream]] funext ``` One removes type names from the list for one lemma with: ``` attribute [ext [-stream,-thunk]] funext ``` Also, the following: ``` @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` is equivalent to ``` @[ext *] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` This allows us specify type synonyms along with the type that referred to in the lemma statement. ``` @[ext [*,my_type_synonym]] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` Attribute `ext` can be applied to a structure to generate its extensionality lemma: ``` @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` will generate: ``` @[ext] lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute (name_map name) (bool × list ext_param_type × list name × list (name × name)) := { name := `ext, descr := "lemmas usable by `ext` tactic", cache_cfg := { mk_cache := λ ls, do { attrs ← ls.mmap $ λ l, do { ⟨_,_,ls,_⟩ ← extensional_attribute.get_param l, pure $ prod.mk <$> ls <*> pure l }, pure $ rb_map.of_list $ attrs.join }, dependencies := [] }, parser := do { ls ← pure <$> ext_param <|> list_of ext_param <|> pure [], m ← extensional_attribute.get_cache, pure $ (ff,ls,[],m.to_list) }, after_set := some $ λ n _ b, do (ff,ls,_,ls') ← extensional_attribute.get_param n | pure (), e ← get_env, n ← if (e.structure_fields n).is_some then derive_struct_ext_lemma n else pure n, s ← mk_const n >>= infer_type >>= get_ext_subject, let (rs,ls'') := if ls.empty then ([],[s]) else ls.partition_map (sum.map (flip option.get_or_else s) (flip option.get_or_else s)), ls''.mmap' (equiv_type_constr s), let l := ls'' ∪ (ls'.filter $ λ l, prod.snd l = n).map prod.fst \ rs, extensional_attribute.set n (tt,[],l,[]) b } attribute [ext] array.ext propext prod.ext attribute [ext [(→),thunk]] _root_.funext namespace ulift @[ext] lemma ext {α : Type u₁} (X Y : ulift.{u₂} α) (w : X.down = Y.down) : X = Y := begin cases X, cases Y, dsimp at w, rw w, end end ulift namespace plift @[ext] lemma ext {P : Prop} (a b : plift P) : a = b := begin cases a, cases b, refl end end plift namespace tactic meta def try_intros : ext_patt → tactic ext_patt | [] := try intros $> [] | (x::xs) := do tgt ← target >>= whnf, if tgt.is_pi then rintro [x] >> try_intros xs else pure (x :: xs) meta def ext1 (xs : ext_patt) (cfg : apply_cfg := {}) : tactic ext_patt := do subject ← target >>= get_ext_subject, m ← extensional_attribute.get_cache, do { rule ← m.find subject, applyc rule cfg } <|> do { ls ← attribute.get_instances `ext, ls.any_of (λ n, applyc n cfg) } <|> fail format!"no applicable extensionality rule found for {subject}", try_intros xs meta def ext : ext_patt → option ℕ → tactic unit | _ (some 0) := skip | xs n := focus1 $ do ys ← ext1 xs, try (ext ys (nat.pred <$> n)) local postfix `?`:9001 := optional local postfix *:9001 := many /-- `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. -/ meta def interactive.ext1 (xs : parse ext_parse) : tactic unit := ext1 xs $> () /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. When trying to prove: ``` α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ``` α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. A maximum depth can be provided with `ext x y z : 3`. -/ meta def interactive.ext : parse ext_parse → parse (tk ":" *> small_nat)? → tactic unit | [] (some n) := iterate_range 1 n (ext1 [] $> ()) | [] none := repeat1 (ext1 [] $> ()) | xs n := tactic.ext xs n end tactic
f92cb1b38dd5bb005b50600c94456401e52f61bc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/big_operators/order.lean
093e4e390cac32489fa7299ab5dcbe266d31e0cb
[ "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
28,176
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.order.absolute_value import algebra.order.ring.with_top import algebra.big_operators.basic import data.fintype.card /-! # Results about big operators with values in an ordered algebraic structure. Mostly monotonicity results for the `∏` and `∑` operations. -/ open function open_locale big_operators variables {ι α β M N G k R : Type*} namespace finset section ordered_comm_monoid variables [comm_monoid M] [ordered_comm_monoid N] /-- Let `{x | p x}` be a subsemigroup of a commutative monoid `M`. Let `f : M → N` be a map submultiplicative on `{x | p x}`, i.e., `p x → p y → f (x * y) ≤ f x * f y`. Let `g i`, `i ∈ s`, be a nonempty finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∏ x in s, g x) ≤ ∏ x in s, f (g x)`. -/ @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred (f : M → N) (p : M → Prop) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : ι → M) (s : finset ι) (hs_nonempty : s.nonempty) (hs : ∀ i ∈ s, p (g i)) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin refine le_trans (multiset.le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul _ _ _) _, { simp [hs_nonempty.ne_empty], }, { exact multiset.forall_mem_map_iff.mpr hs, }, rw multiset.map_map, refl, end /-- Let `{x | p x}` be an additive subsemigroup of an additive commutative monoid `M`. Let `f : M → N` be a map subadditive on `{x | p x}`, i.e., `p x → p y → f (x + y) ≤ f x + f y`. Let `g i`, `i ∈ s`, be a nonempty finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∑ i in s, g i) ≤ ∑ i in s, f (g i)`. -/ add_decl_doc le_sum_nonempty_of_subadditive_on_pred /-- If `f : M → N` is a submultiplicative function, `f (x * y) ≤ f x * f y` and `g i`, `i ∈ s`, is a nonempty finite family of elements of `M`, then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative (f : M → N) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) {s : finset ι} (hs : s.nonempty) (g : ι → M) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (λ x y _ _, h_mul x y) (λ _ _ _ _, trivial) g s hs (λ _ _, trivial) /-- If `f : M → N` is a subadditive function, `f (x + y) ≤ f x + f y` and `g i`, `i ∈ s`, is a nonempty finite family of elements of `M`, then `f (∑ i in s, g i) ≤ ∑ i in s, f (g i)`. -/ add_decl_doc le_sum_nonempty_of_subadditive /-- Let `{x | p x}` be a subsemigroup of a commutative monoid `M`. Let `f : M → N` be a map such that `f 1 = 1` and `f` is submultiplicative on `{x | p x}`, i.e., `p x → p y → f (x * y) ≤ f x * f y`. Let `g i`, `i ∈ s`, be a finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred (f : M → N) (p : M → Prop) (h_one : f 1 = 1) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : ι → M) {s : finset ι} (hs : ∀ i ∈ s, p (g i)) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin rcases eq_empty_or_nonempty s with rfl|hs_nonempty, { simp [h_one] }, { exact le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul g s hs_nonempty hs, }, end /-- Let `{x | p x}` be a subsemigroup of a commutative additive monoid `M`. Let `f : M → N` be a map such that `f 0 = 0` and `f` is subadditive on `{x | p x}`, i.e. `p x → p y → f (x + y) ≤ f x + f y`. Let `g i`, `i ∈ s`, be a finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∑ x in s, g x) ≤ ∑ x in s, f (g x)`. -/ add_decl_doc le_sum_of_subadditive_on_pred /-- If `f : M → N` is a submultiplicative function, `f (x * y) ≤ f x * f y`, `f 1 = 1`, and `g i`, `i ∈ s`, is a finite family of elements of `M`, then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative (f : M → N) (h_one : f 1 = 1) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) (s : finset ι) (g : ι → M) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin refine le_trans (multiset.le_prod_of_submultiplicative f h_one h_mul _) _, rw multiset.map_map, refl, end /-- If `f : M → N` is a subadditive function, `f (x + y) ≤ f x + f y`, `f 0 = 0`, and `g i`, `i ∈ s`, is a finite family of elements of `M`, then `f (∑ i in s, g i) ≤ ∑ i in s, f (g i)`. -/ add_decl_doc le_sum_of_subadditive variables {f g : ι → N} {s t : finset ι} /-- In an ordered commutative monoid, if each factor `f i` of one finite product is less than or equal to the corresponding factor `g i` of another finite product, then `∏ i in s, f i ≤ ∏ i in s, g i`. -/ @[to_additive sum_le_sum] lemma prod_le_prod'' (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := multiset.prod_map_le_prod_map f g h /-- In an ordered additive commutative monoid, if each summand `f i` of one finite sum is less than or equal to the corresponding summand `g i` of another finite sum, then `∑ i in s, f i ≤ ∑ i in s, g i`. -/ add_decl_doc sum_le_sum @[to_additive sum_nonneg] lemma one_le_prod' (h : ∀i ∈ s, 1 ≤ f i) : 1 ≤ (∏ i in s, f i) := le_trans (by rw prod_const_one) (prod_le_prod'' h) @[to_additive finset.sum_nonneg'] lemma one_le_prod'' (h : ∀ (i : ι), 1 ≤ f i) : 1 ≤ ∏ (i : ι) in s, f i := finset.one_le_prod' (λ i hi, h i) @[to_additive sum_nonpos] lemma prod_le_one' (h : ∀i ∈ s, f i ≤ 1) : (∏ i in s, f i) ≤ 1 := (prod_le_prod'' h).trans_eq (by rw prod_const_one) @[to_additive sum_le_sum_of_subset_of_nonneg] lemma prod_le_prod_of_subset_of_one_le' (h : s ⊆ t) (hf : ∀ i ∈ t, i ∉ s → 1 ≤ f i) : ∏ i in s, f i ≤ ∏ i in t, f i := by classical; calc (∏ i in s, f i) ≤ (∏ i in t \ s, f i) * (∏ i in s, f i) : le_mul_of_one_le_left' $ one_le_prod' $ by simpa only [mem_sdiff, and_imp] ... = ∏ i in t \ s ∪ s, f i : (prod_union sdiff_disjoint).symm ... = ∏ i in t, f i : by rw [sdiff_union_of_subset h] @[to_additive sum_mono_set_of_nonneg] lemma prod_mono_set_of_one_le' (hf : ∀ x, 1 ≤ f x) : monotone (λ s, ∏ x in s, f x) := λ s t hst, prod_le_prod_of_subset_of_one_le' hst $ λ x _ _, hf x @[to_additive sum_le_univ_sum_of_nonneg] lemma prod_le_univ_prod_of_one_le' [fintype ι] {s : finset ι} (w : ∀ x, 1 ≤ f x) : ∏ x in s, f x ≤ ∏ x, f x := prod_le_prod_of_subset_of_one_le' (subset_univ s) (λ a _ _, w a) @[to_additive sum_eq_zero_iff_of_nonneg] lemma prod_eq_one_iff_of_one_le' : (∀ i ∈ s, 1 ≤ f i) → (∏ i in s, f i = 1 ↔ ∀ i ∈ s, f i = 1) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ i ∈ s, 1 ≤ f i, from λ _, H _ ∘ mem_insert_of_mem, rw [prod_insert ha, mul_eq_one_iff' (H _ $ mem_insert_self _ _) (one_le_prod' this), forall_mem_insert, ih this] end @[to_additive sum_eq_zero_iff_of_nonneg] lemma prod_eq_one_iff_of_le_one' : (∀ i ∈ s, f i ≤ 1) → (∏ i in s, f i = 1 ↔ ∀ i ∈ s, f i = 1) := @prod_eq_one_iff_of_one_le' _ Nᵒᵈ _ _ _ @[to_additive single_le_sum] lemma single_le_prod' (hf : ∀ i ∈ s, 1 ≤ f i) {a} (h : a ∈ s) : f a ≤ (∏ x in s, f x) := calc f a = ∏ i in {a}, f i : prod_singleton.symm ... ≤ ∏ i in s, f i : prod_le_prod_of_subset_of_one_le' (singleton_subset_iff.2 h) $ λ i hi _, hf i hi @[to_additive sum_le_card_nsmul] lemma prod_le_pow_card (s : finset ι) (f : ι → N) (n : N) (h : ∀ x ∈ s, f x ≤ n) : s.prod f ≤ n ^ s.card := begin refine (multiset.prod_le_pow_card (s.val.map f) n _).trans _, { simpa using h }, { simpa } end @[to_additive card_nsmul_le_sum] lemma pow_card_le_prod (s : finset ι) (f : ι → N) (n : N) (h : ∀ x ∈ s, n ≤ f x) : n ^ s.card ≤ s.prod f := @finset.prod_le_pow_card _ Nᵒᵈ _ _ _ _ h lemma card_bUnion_le_card_mul [decidable_eq β] (s : finset ι) (f : ι → finset β) (n : ℕ) (h : ∀ a ∈ s, (f a).card ≤ n) : (s.bUnion f).card ≤ s.card * n := card_bUnion_le.trans $ sum_le_card_nsmul _ _ _ h variables {ι' : Type*} [decidable_eq ι'] @[to_additive sum_fiberwise_le_sum_of_sum_fiber_nonneg] lemma prod_fiberwise_le_prod_of_one_le_prod_fiber' {t : finset ι'} {g : ι → ι'} {f : ι → N} (h : ∀ y ∉ t, (1 : N) ≤ ∏ x in s.filter (λ x, g x = y), f x) : ∏ y in t, ∏ x in s.filter (λ x, g x = y), f x ≤ ∏ x in s, f x := calc (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) ≤ (∏ y in t ∪ s.image g, ∏ x in s.filter (λ x, g x = y), f x) : prod_le_prod_of_subset_of_one_le' (subset_union_left _ _) $ λ y hyts, h y ... = ∏ x in s, f x : prod_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _ @[to_additive sum_le_sum_fiberwise_of_sum_fiber_nonpos] lemma prod_le_prod_fiberwise_of_prod_fiber_le_one' {t : finset ι'} {g : ι → ι'} {f : ι → N} (h : ∀ y ∉ t, (∏ x in s.filter (λ x, g x = y), f x) ≤ 1) : (∏ x in s, f x) ≤ ∏ y in t, ∏ x in s.filter (λ x, g x = y), f x := @prod_fiberwise_le_prod_of_one_le_prod_fiber' _ Nᵒᵈ _ _ _ _ _ _ _ h end ordered_comm_monoid lemma abs_sum_le_sum_abs {G : Type*} [linear_ordered_add_comm_group G] (f : ι → G) (s : finset ι) : |∑ i in s, f i| ≤ ∑ i in s, |f i| := le_sum_of_subadditive _ abs_zero abs_add s f lemma abs_sum_of_nonneg {G : Type*} [linear_ordered_add_comm_group G] {f : ι → G} {s : finset ι} (hf : ∀ i ∈ s, 0 ≤ f i) : |∑ (i : ι) in s, f i| = ∑ (i : ι) in s, f i := by rw abs_of_nonneg (finset.sum_nonneg hf) lemma abs_sum_of_nonneg' {G : Type*} [linear_ordered_add_comm_group G] {f : ι → G} {s : finset ι} (hf : ∀ i, 0 ≤ f i) : |∑ (i : ι) in s, f i| = ∑ (i : ι) in s, f i := by rw abs_of_nonneg (finset.sum_nonneg' hf) lemma abs_prod {R : Type*} [linear_ordered_comm_ring R] {f : ι → R} {s : finset ι} : |∏ x in s, f x| = ∏ x in s, |f x| := (abs_hom.to_monoid_hom : R →* R).map_prod _ _ section pigeonhole variable [decidable_eq β] theorem card_le_mul_card_image_of_maps_to {f : α → β} {s : finset α} {t : finset β} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * t.card := calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf ... ≤ (∑ _ in t, n) : sum_le_sum hn ... = _ : by simp [mul_comm] theorem card_le_mul_card_image {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn theorem mul_card_image_le_card_of_maps_to {f : α → β} {s : finset α} {t : finset β} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) : n * t.card ≤ s.card := calc n * t.card = (∑ _ in t, n) : by simp [mul_comm] ... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn ... = s.card : by rw ← card_eq_sum_card_fiberwise Hf theorem mul_card_image_le_card {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) : n * (s.image f).card ≤ s.card := mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn end pigeonhole section double_counting variables [decidable_eq α] {s : finset α} {B : finset (finset α)} {n : ℕ} /-- If every element belongs to at most `n` finsets, then the sum of their sizes is at most `n` times how many they are. -/ lemma sum_card_inter_le (h : ∀ a ∈ s, (B.filter $ (∈) a).card ≤ n) : ∑ t in B, (s ∩ t).card ≤ s.card * n := begin refine le_trans _ (s.sum_le_card_nsmul _ _ h), simp_rw [←filter_mem_eq_inter, card_eq_sum_ones, sum_filter], exact sum_comm.le, end /-- If every element belongs to at most `n` finsets, then the sum of their sizes is at most `n` times how many they are. -/ lemma sum_card_le [fintype α] (h : ∀ a, (B.filter $ (∈) a).card ≤ n) : ∑ s in B, s.card ≤ fintype.card α * n := calc ∑ s in B, s.card = ∑ s in B, (univ ∩ s).card : by simp_rw univ_inter ... ≤ fintype.card α * n : sum_card_inter_le (λ a _, h a) /-- If every element belongs to at least `n` finsets, then the sum of their sizes is at least `n` times how many they are. -/ lemma le_sum_card_inter (h : ∀ a ∈ s, n ≤ (B.filter $ (∈) a).card) : s.card * n ≤ ∑ t in B, (s ∩ t).card := begin apply (s.card_nsmul_le_sum _ _ h).trans, simp_rw [←filter_mem_eq_inter, card_eq_sum_ones, sum_filter], exact sum_comm.le, end /-- If every element belongs to at least `n` finsets, then the sum of their sizes is at least `n` times how many they are. -/ lemma le_sum_card [fintype α] (h : ∀ a, n ≤ (B.filter $ (∈) a).card) : fintype.card α * n ≤ ∑ s in B, s.card := calc fintype.card α * n ≤ ∑ s in B, (univ ∩ s).card : le_sum_card_inter (λ a _, h a) ... = ∑ s in B, s.card : by simp_rw univ_inter /-- If every element belongs to exactly `n` finsets, then the sum of their sizes is `n` times how many they are. -/ lemma sum_card_inter (h : ∀ a ∈ s, (B.filter $ (∈) a).card = n) : ∑ t in B, (s ∩ t).card = s.card * n := (sum_card_inter_le $ λ a ha, (h a ha).le).antisymm (le_sum_card_inter $ λ a ha, (h a ha).ge) /-- If every element belongs to exactly `n` finsets, then the sum of their sizes is `n` times how many they are. -/ lemma sum_card [fintype α] (h : ∀ a, (B.filter $ (∈) a).card = n) : ∑ s in B, s.card = fintype.card α * n := by simp_rw [fintype.card, ←sum_card_inter (λ a _, h a), univ_inter] lemma card_le_card_bUnion {s : finset ι} {f : ι → finset α} (hs : (s : set ι).pairwise_disjoint f) (hf : ∀ i ∈ s, (f i).nonempty) : s.card ≤ (s.bUnion f).card := by { rw [card_bUnion hs, card_eq_sum_ones], exact sum_le_sum (λ i hi, (hf i hi).card_pos) } lemma card_le_card_bUnion_add_card_fiber {s : finset ι} {f : ι → finset α} (hs : (s : set ι).pairwise_disjoint f) : s.card ≤ (s.bUnion f).card + (s.filter $ λ i, f i = ∅).card := begin rw [←finset.filter_card_add_filter_neg_card_eq_card (λ i, f i = ∅), add_comm], exact add_le_add_right ((card_le_card_bUnion (hs.subset $ filter_subset _ _) $ λ i hi, nonempty_of_ne_empty $ (mem_filter.1 hi).2).trans $ card_le_of_subset $ bUnion_subset_bUnion_of_subset_left _ $ filter_subset _ _) _, end lemma card_le_card_bUnion_add_one {s : finset ι} {f : ι → finset α} (hf : injective f) (hs : (s : set ι).pairwise_disjoint f) : s.card ≤ (s.bUnion f).card + 1 := (card_le_card_bUnion_add_card_fiber hs).trans $ add_le_add_left (card_le_one.2 $ λ i hi j hj, hf $ (mem_filter.1 hi).2.trans (mem_filter.1 hj).2.symm) _ end double_counting section canonically_ordered_monoid variables [canonically_ordered_monoid M] {f : ι → M} {s t : finset ι} @[simp, to_additive sum_eq_zero_iff] lemma prod_eq_one_iff' : ∏ x in s, f x = 1 ↔ ∀ x ∈ s, f x = 1 := prod_eq_one_iff_of_one_le' $ λ x hx, one_le (f x) @[to_additive sum_le_sum_of_subset] lemma prod_le_prod_of_subset' (h : s ⊆ t) : ∏ x in s, f x ≤ ∏ x in t, f x := prod_le_prod_of_subset_of_one_le' h $ assume x h₁ h₂, one_le _ @[to_additive sum_mono_set] lemma prod_mono_set' (f : ι → M) : monotone (λ s, ∏ x in s, f x) := λ s₁ s₂ hs, prod_le_prod_of_subset' hs @[to_additive sum_le_sum_of_ne_zero] lemma prod_le_prod_of_ne_one' (h : ∀ x ∈ s, f x ≠ 1 → x ∈ t) : ∏ x in s, f x ≤ ∏ x in t, f x := by classical; calc ∏ x in s, f x = (∏ x in s.filter (λ x, f x = 1), f x) * ∏ x in s.filter (λ x, f x ≠ 1), f x : by rw [← prod_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ (∏ x in t, f x) : mul_le_of_le_one_of_le (prod_le_one' $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (prod_le_prod_of_subset' $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid M] {f g : ι → M} {s t : finset ι} @[to_additive sum_lt_sum] theorem prod_lt_prod' (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : ∏ i in s, f i < ∏ i in s, g i := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _)], exact mul_lt_mul_of_lt_of_le hlt (prod_le_prod'' $ λ j hj, Hle j $ mem_of_mem_erase hj) end @[to_additive sum_lt_sum_of_nonempty] lemma prod_lt_prod_of_nonempty' (hs : s.nonempty) (Hlt : ∀ i ∈ s, f i < g i) : ∏ i in s, f i < ∏ i in s, g i := begin apply prod_lt_prod', { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end @[to_additive sum_lt_sum_of_subset] lemma prod_lt_prod_of_subset' (h : s ⊆ t) {i : ι} (ht : i ∈ t) (hs : i ∉ s) (hlt : 1 < f i) (hle : ∀ j ∈ t, j ∉ s → 1 ≤ f j) : ∏ j in s, f j < ∏ j in t, f j := by classical; calc ∏ j in s, f j < ∏ j in insert i s, f j : begin rw prod_insert hs, exact lt_mul_of_one_lt_left' (∏ j in s, f j) hlt, end ... ≤ ∏ j in t, f j : begin apply prod_le_prod_of_subset_of_one_le', { simp [finset.insert_subset, h, ht] }, { assume x hx h'x, simp only [mem_insert, not_or_distrib] at h'x, exact hle x hx h'x.2 } end @[to_additive single_lt_sum] lemma single_lt_prod' {i j : ι} (hij : j ≠ i) (hi : i ∈ s) (hj : j ∈ s) (hlt : 1 < f j) (hle : ∀ k ∈ s, k ≠ i → 1 ≤ f k) : f i < ∏ k in s, f k := calc f i = ∏ k in {i}, f k : prod_singleton.symm ... < ∏ k in s, f k : prod_lt_prod_of_subset' (singleton_subset_iff.2 hi) hj (mt mem_singleton.1 hij) hlt $ λ k hks hki, hle k hks (mt mem_singleton.2 hki) @[to_additive sum_pos] lemma one_lt_prod (h : ∀i ∈ s, 1 < f i) (hs : s.nonempty) : 1 < (∏ i in s, f i) := lt_of_le_of_lt (by rw prod_const_one) $ prod_lt_prod_of_nonempty' hs h @[to_additive] lemma prod_lt_one (h : ∀i ∈ s, f i < 1) (hs : s.nonempty) : (∏ i in s, f i) < 1 := (prod_lt_prod_of_nonempty' hs h).trans_le (by rw prod_const_one) @[to_additive sum_pos'] lemma one_lt_prod' (h : ∀ i ∈ s, 1 ≤ f i) (hs : ∃ i ∈ s, 1 < f i) : 1 < (∏ i in s, f i) := prod_const_one.symm.trans_lt $ prod_lt_prod' h hs @[to_additive] lemma prod_lt_one' (h : ∀ i ∈ s, f i ≤ 1) (hs : ∃ i ∈ s, f i < 1) : ∏ i in s, f i < 1 := prod_const_one.le.trans_lt' $ prod_lt_prod' h hs @[to_additive] lemma prod_eq_prod_iff_of_le {f g : ι → M} (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i = ∏ i in s, g i ↔ ∀ i ∈ s, f i = g i := begin classical, revert h, refine finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) (λ a s ha ih H, _), specialize ih (λ i, H i ∘ finset.mem_insert_of_mem), rw [finset.prod_insert ha, finset.prod_insert ha, finset.forall_mem_insert, ←ih], exact mul_eq_mul_iff_eq_and_eq (H a (s.mem_insert_self a)) (finset.prod_le_prod'' (λ i, H i ∘ finset.mem_insert_of_mem)), end end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid M] {f g : ι → M} {s t : finset ι} @[to_additive exists_lt_of_sum_lt] theorem exists_lt_of_prod_lt' (Hlt : ∏ i in s, f i < ∏ i in s, g i) : ∃ i ∈ s, f i < g i := begin contrapose! Hlt with Hle, exact prod_le_prod'' Hle end @[to_additive exists_le_of_sum_le] theorem exists_le_of_prod_le' (hs : s.nonempty) (Hle : ∏ i in s, f i ≤ ∏ i in s, g i) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle with Hlt, exact prod_lt_prod_of_nonempty' hs Hlt end @[to_additive exists_pos_of_sum_zero_of_exists_nonzero] lemma exists_one_lt_of_prod_one_of_exists_ne_one' (f : ι → M) (h₁ : ∏ i in s, f i = 1) (h₂ : ∃ i ∈ s, f i ≠ 1) : ∃ i ∈ s, 1 < f i := begin contrapose! h₁, obtain ⟨i, m, i_ne⟩ : ∃ i ∈ s, f i ≠ 1 := h₂, apply ne_of_lt, calc ∏ j in s, f j < ∏ j in s, 1 : prod_lt_prod' h₁ ⟨i, m, (h₁ i m).lt_of_ne i_ne⟩ ... = 1 : prod_const_one end end linear_ordered_cancel_comm_monoid section ordered_comm_semiring variables [ordered_comm_semiring R] {f g : ι → R} {s t : finset ι} open_locale classical /- this is also true for a ordered commutative multiplicative monoid with zero -/ lemma prod_nonneg (h0 : ∀ i ∈ s, 0 ≤ f i) : 0 ≤ ∏ i in s, f i := prod_induction f (λ i, 0 ≤ i) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0 /-- If all `f i`, `i ∈ s`, are nonnegative and each `f i` is less than or equal to `g i`, then the product of `f i` is less than or equal to the product of `g i`. See also `finset.prod_le_prod''` for the case of an ordered commutative multiplicative monoid. -/ lemma prod_le_prod (h0 : ∀ i ∈ s, 0 ≤ f i) (h1 : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin induction s using finset.induction with a s has ih h, { simp }, { simp only [prod_insert has], apply mul_le_mul, { exact h1 a (mem_insert_self a s) }, { apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H) }, { apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)) }, { apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } } end /-- If each `f i`, `i ∈ s` belongs to `[0, 1]`, then their product is less than or equal to one. See also `finset.prod_le_one'` for the case of an ordered commutative multiplicative monoid. -/ lemma prod_le_one (h0 : ∀ i ∈ s, 0 ≤ f i) (h1 : ∀ i ∈ s, f i ≤ 1) : ∏ i in s, f i ≤ 1 := begin convert ← prod_le_prod h0 h1, exact finset.prod_const_one end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `ordered_comm_semiring`. -/ lemma prod_add_prod_le {i : ι} {f g h : ι → R} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin simp_rw [prod_eq_mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_of_nonneg_right h2i _), { rw [right_distrib], apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply_assumption; assumption }; apply prod_le_prod; simp * { contextual := tt } }, { apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton], intros j h1j h2j, exact le_trans (hg j h1j) (hgf j h1j h2j) } end end ordered_comm_semiring section strict_ordered_comm_semiring variables [strict_ordered_comm_semiring R] [nontrivial R] {f : ι → R} {s : finset ι} /- This is also true for a ordered commutative multiplicative monoid with zero -/ lemma prod_pos (h0 : ∀ i ∈ s, 0 < f i) : 0 < ∏ i in s, f i := prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0 end strict_ordered_comm_semiring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring R] {f g h : ι → R} {s : finset ι} {i : ι} lemma prod_le_prod' (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply mul_le_mul', { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`. -/ lemma prod_add_prod_le' (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin classical, simp_rw [prod_eq_mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_right' h2i _), rw [right_distrib], apply add_le_add; apply mul_le_mul_left'; apply prod_le_prod'; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption end end canonically_ordered_comm_semiring end finset namespace fintype variables [fintype ι] @[to_additive sum_mono, mono] lemma prod_mono' [ordered_comm_monoid M] : monotone (λ f : ι → M, ∏ i, f i) := λ f g hfg, finset.prod_le_prod'' $ λ x _, hfg x attribute [mono] sum_mono @[to_additive sum_strict_mono] lemma prod_strict_mono' [ordered_cancel_comm_monoid M] : strict_mono (λ f : ι → M, ∏ x, f x) := λ f g hfg, let ⟨hle, i, hlt⟩ := pi.lt_def.mp hfg in finset.prod_lt_prod' (λ i _, hle i) ⟨i, finset.mem_univ i, hlt⟩ end fintype namespace with_top open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top [canonically_ordered_comm_semiring R] [nontrivial R] [decidable_eq R] {s : finset ι} {f : ι → with_top R} (h : ∀ i ∈ s, f i ≠ ⊤) : ∏ i in s, f i < ⊤ := prod_induction f (λ a, a < ⊤) (λ a b h₁ h₂, mul_lt_top h₁.ne h₂.ne) (coe_lt_top 1) $ λ a ha, lt_top_iff_ne_top.2 (h a ha) /-- A sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} (h : ∀ i ∈ s, f i ≠ ⊤) : (∑ i in s, f i) < ⊤ := sum_induction f (λ a, a < ⊤) (λ a b h₁ h₂, add_lt_top.2 ⟨h₁, h₂⟩) zero_lt_top $ λ i hi, lt_top_iff_ne_top.2 (h i hi) /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} : ∑ i in s, f i = ⊤ ↔ ∃ i ∈ s, f i = ⊤ := begin classical, split, { contrapose!, exact λ h, (sum_lt_top $ λ i hi, (h i hi)).ne }, { rintro ⟨i, his, hi⟩, rw [sum_eq_add_sum_diff_singleton his, hi, top_add] } end /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} : ∑ i in s, f i < ⊤ ↔ ∀ i ∈ s, f i < ⊤ := by simp only [lt_top_iff_ne_top, ne.def, sum_eq_top_iff, not_exists] end with_top section absolute_value variables {S : Type*} lemma absolute_value.sum_le [semiring R] [ordered_semiring S] (abv : absolute_value R S) (s : finset ι) (f : ι → R) : abv (∑ i in s, f i) ≤ ∑ i in s, abv (f i) := begin letI := classical.dec_eq ι, refine finset.induction_on s _ (λ i s hi ih, _), { simp }, { simp only [finset.sum_insert hi], exact (abv.add_le _ _).trans (add_le_add le_rfl ih) }, end lemma is_absolute_value.abv_sum [semiring R] [ordered_semiring S] (abv : R → S) [is_absolute_value abv] (f : ι → R) (s : finset ι) : abv (∑ i in s, f i) ≤ ∑ i in s, abv (f i) := (is_absolute_value.to_absolute_value abv).sum_le _ _ lemma absolute_value.map_prod [comm_semiring R] [nontrivial R] [linear_ordered_comm_ring S] (abv : absolute_value R S) (f : ι → R) (s : finset ι) : abv (∏ i in s, f i) = ∏ i in s, abv (f i) := abv.to_monoid_hom.map_prod f s lemma is_absolute_value.map_prod [comm_semiring R] [nontrivial R] [linear_ordered_comm_ring S] (abv : R → S) [is_absolute_value abv] (f : ι → R) (s : finset ι) : abv (∏ i in s, f i) = ∏ i in s, abv (f i) := (is_absolute_value.to_absolute_value abv).map_prod _ _ end absolute_value
f03455611af762bbc6920d1699c8fa27869f2da8
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/analysis/normed_space/operator_norm.lean
ceb836f416a5ec13e709eebb9cd719e209d06e6e
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,187
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import linear_algebra.finite_dimensional import analysis.normed_space.riesz_lemma import analysis.asymptotics /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. -/ noncomputable theory open_locale classical nnreal variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map lemma exists_pos_bound_of_bound {f : E → F} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ section normed_field /- Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) theorem linear_map.antilipschitz_of_bound {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Reinterpret a linear map `𝕜 →ₗ[𝕜] E` as a continuous linear map. This construction is generalized to the case of any finite dimensional domain in `linear_map.to_continuous_linear_map`. -/ def linear_map.to_continuous_linear_map₁ (f : 𝕜 →ₗ[𝕜] E) : 𝕜 →L[𝕜] E := f.mk_continuous (∥f 1∥) $ λ x, le_of_eq $ by { conv_lhs { rw ← mul_one x }, rw [← smul_eq_mul, f.map_smul, norm_smul, mul_comm] } /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ lemma continuous_of_linear_of_bound {f : E → F} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = c • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₗ[𝕜] F := ⟨f, h_add, h_smul⟩ in φ.continuous_of_bound C h_bound @[simp, norm_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, norm_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_coe (f : 𝕜 →ₗ[𝕜] E) : (f.to_continuous_linear_map₁ : 𝕜 →ₗ[𝕜] E) = f := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_apply (f : 𝕜 →ₗ[𝕜] E) (x) : f.to_continuous_linear_map₁ x = f x := rfl lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (continuous_iff_is_closed.1 h) {0} (t1_space.t1 0), λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero_mem }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], norm_num }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg, norm_nonneg, inv_nonneg.2] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field section add_monoid_hom lemma add_monoid_hom.isometry_of_norm (f : E →+ F) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f := begin intros x y, simp_rw [edist_dist], congr', simp_rw [dist_eq_norm, ←add_monoid_hom.map_sub], exact hf (x - y), end end add_monoid_hom variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 lemma linear_map.bound_of_shell (f : E →ₗ[𝕜] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) (x : E) : ∥f x∥ ≤ C * ∥x∥ := begin by_cases hx : x = 0, { simp [hx] }, rcases rescale_to_shell hc ε_pos hx with ⟨δ, hδ, δxle, leδx, δinv⟩, simpa only [f.map_smul, norm_smul, mul_left_comm C, mul_le_mul_left (norm_pos_iff.2 hδ)] using hf (δ • x) leδx δxle end /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `ε`. The nondiscreteness is then used to rescale any element into an element of norm in `[ε/C, ε]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin have : continuous_at f 0 := continuous_iff_continuous_at.1 hf _, rcases (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).1 this 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, simp only [mem_closed_ball, dist_zero_right, f.map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨ε⁻¹ * ∥c∥, mul_pos (inv_pos.2 ε_pos) (lt_trans zero_lt_one hc), _⟩, suffices : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ ε⁻¹ * ∥c∥ * ∥x∥, from f.bound_of_shell ε_pos hc this, intros x hle hlt, refine (hε _ hlt.le).trans _, rwa [mul_assoc, ← div_le_iff' (inv_pos.2 ε_pos), div_eq_mul_inv, inv_inv', one_mul, ← div_le_iff' (zero_lt_one.trans hc)] end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open asymptotics filter theorem is_O_id (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := f.bound in is_O_of_le' l hM theorem is_O_comp {α : Type*} (g : F →L[𝕜] G) (f : α → F) (l : filter α) : is_O (λ x', g (f x')) f l := (g.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l /-- A linear map which is a homothety is a continuous linear map. Since the field `𝕜` need not have `ℝ` as a subfield, this theorem is not directly deducible from the corresponding theorem about isometries plus a theorem about scalar multiplication. Likewise for the other theorems about homotheties in this file. -/ def of_homothety (f : E →ₗ[𝕜] F) (a : ℝ) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E →L[𝕜] F := f.mk_continuous a (λ x, le_of_eq (hf x)) variable (𝕜) lemma to_span_singleton_homothety (x : E) (c : 𝕜) : ∥linear_map.to_span_singleton 𝕜 E x c∥ = ∥x∥ * ∥c∥ := by {rw mul_comm, exact norm_smul _ _} /-- Given an element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from `E` to the span of `x`.-/ def to_span_singleton (x : E) : 𝕜 →L[𝕜] E := of_homothety (linear_map.to_span_singleton 𝕜 E x) ∥x∥ (to_span_singleton_homothety 𝕜 x) end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := classical.by_cases (λ heq : x = 0, by { rw heq, simp }) (λ hne, have hlt : 0 < ∥x∥, from norm_pos_iff.2 hne, (div_le_iff hlt).mp ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc }))) theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ∥f∥ ≤ c) (x : E) : ∥f x∥ ≤ c * ∥x∥ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_iff_of_nonneg_of_le (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →L[𝕜] F} {K : ℝ≥0} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_le_of_shell {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := f.op_norm_le_bound hC $ (f : E →ₗ[𝕜] F).bound_of_shell ε_pos hc hf lemma op_norm_le_of_ball {f : E →L[𝕜] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine op_norm_le_of_shell ε_pos hC hc (λ x _ hx, hf x _), rwa ball_0_eq end lemma op_norm_le_of_shell' {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : ∥c∥ < 1) (hf : ∀ x, ε * ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin by_cases h0 : c = 0, { refine op_norm_le_of_ball ε_pos hC (λ x hx, hf x _ _), { simp [h0] }, { rwa ball_0_eq at hx } }, { rw [← inv_inv' c, normed_field.norm_inv, inv_lt_one_iff_of_pos (norm_pos_iff.2 $ inv_ne_zero h0)] at hc, refine op_norm_le_of_shell ε_pos hC hc _, rwa [normed_field.norm_inv, div_eq_mul_inv, inv_inv'] } end lemma op_norm_eq_of_bounds {φ : E →L[𝕜] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N ≥ 0, (∀ x, ∥φ x∥ ≤ N*∥x∥) → M ≤ N) : ∥φ∥ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := show ∥f + g∥ ≤ (coe : ℝ≥0 → ℝ) (⟨_, f.op_norm_nonneg⟩ + ⟨_, g.op_norm_nonneg⟩), from op_norm_le_of_lipschitz (f.lipschitz.add g.lipschitz) /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥id 𝕜 E∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If a space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id [nontrivial E] : ∥id 𝕜 E∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := exists_ne (0 : E) in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self (ne_of_gt $ norm_pos_iff.2 hx)] at this @[simp] lemma norm_id_field : ∥id 𝕜 𝕜∥ = 1 := norm_id @[simp] lemma norm_id_field' : ∥(1 : 𝕜 →L[𝕜] 𝕜)∥ = 1 := norm_id_field lemma op_norm_smul_le : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (E →L[𝕜] F) := ⟨op_norm_smul_le⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →L[𝕜] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_normed_group } /-- For a nonzero normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra [nontrivial E] : normed_algebra 𝕜 (E →L[𝕜] E) := { norm_algebra_map_eq := λ c, show ∥c • id 𝕜 E∥ = ∥c∥, by {rw [norm_smul, norm_id], simp}, .. continuous_linear_map.algebra } /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.uniform_continuous variable {f} /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm_image_eq_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := begin rw isometry_emetric_iff_metric, split, { assume H x, have := H x 0, rwa [dist_eq_norm, dist_eq_norm, f.map_zero, sub_zero, sub_zero] at this }, { assume H x y, rw [dist_eq_norm, dist_eq_norm, ← f.map_sub, H] } end lemma homothety_norm [nontrivial E] (f : E →L[𝕜] F) {a : ℝ} (hf : ∀x, ∥f x∥ = a * ∥x∥) : ∥f∥ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, have ha : 0 ≤ a, { apply nonneg_of_mul_nonneg_right, rw ← hf x, apply norm_nonneg, exact norm_pos_iff.mpr hx }, refine le_antisymm_iff.mpr ⟨_, _⟩, { exact continuous_linear_map.op_norm_le_bound f ha (λ y, le_of_eq (hf y)) }, { rw continuous_linear_map.norm_def, apply real.lb_le_Inf _ continuous_linear_map.bounds_nonempty, intros c h, rw mem_set_of_eq at h, apply (mul_le_mul_right (norm_pos_iff.mpr hx)).mp, rw ← hf x, exact h.2 x } end lemma to_span_singleton_norm (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := homothety_norm _ (to_span_singleton_homothety 𝕜 x) variable (f) theorem uniform_embedding_of_bound {K : ℝ≥0} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { refine (hε _).le, rw [f.map_zero, dist_zero_right], exact hx.trans_lt (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * nnnorm c, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxlt, ledx, dinv⟩, rw [← f.map_smul d] at dxlt, have : ∥d • x∥ ≤ 1 := H dxlt.le, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. -/ instance [complete_space F] : complete_space (E →L[𝕜] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, clear hf, -- and establish that the evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∥v∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (norm_nonneg _) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (norm_nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is linear, let Glin : E →ₗ[𝕜] F := { to_fun := G, map_add' := λ v w, begin have A := hG (v + w), have B := (hG v).add (hG w), simp only [map_add] at A B, exact tendsto_nhds_unique A B, end, map_smul' := λ c v, begin have A := hG (c • v), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hG v), simp only [map_smul] at A B, exact tendsto_nhds_unique A B end }, -- and that `G` has norm at most `(b 0 + ∥f 0∥)`. have Gnorm : ∀ v, ∥G v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (norm_nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hG v).norm (eventually_of_forall A) }, -- Thus `G` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Gcont := Glin.mk_continuous _ Gnorm, use Gcont, -- Our last task is to establish convergence to `G` in norm. have : ∀ n, ∥f n - Gcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∥v∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (norm_nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Gcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hG v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const.smul continuous_id)) ((continuous_const.smul continuous_id).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } lemma extend_unique (g : G →L[𝕜] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.injective_coe_fn $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : ℝ≥0} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma linear_map.mk_continuous_norm_le (f : E →ₗ[𝕜] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h namespace continuous_linear_map /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : ∥f∥ = 0, { rw h, simp [norm_nonneg] }, { have : 0 < ∥f∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm h), rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥((smul_right c f) : E → F) x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end /-- Given `c : c : E →L[𝕜] 𝕜`, `c.smul_rightL` is the continuous linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. -/ def smul_rightL (c : E →L[𝕜] 𝕜) : F →L[𝕜] (E →L[𝕜] F) := (c.smul_rightₗ : F →ₗ[𝕜] (E →L[𝕜] F)).mk_continuous _ (λ f, le_of_eq $ c.norm_smul_right_apply f) @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥c.smul_rightL f∥ = ∥c∥ * ∥f∥ := by simp [continuous_linear_map.smul_rightL, continuous_linear_map.smul_rightₗ] @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial F] : ∥(c.smul_rightL : F →L[𝕜] (E →L[𝕜] F))∥ = ∥c∥ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜 F) /-- The linear map obtained by applying a continuous linear map at a given vector. -/ def applyₗ (v : E) : (E →L[𝕜] F) →ₗ[𝕜] F := { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v } lemma continuous_applyₗ (v : E) : continuous (continuous_linear_map.applyₗ 𝕜 F v) := begin apply (continuous_linear_map.applyₗ 𝕜 F v).continuous_of_bound, intro f, rw mul_comm, exact f.le_op_norm v, end /-- The continuous linear map obtained by applying a continuous linear map at a given vector. -/ def apply (v : E) : (E →L[𝕜] F) →L[𝕜] F := ⟨continuous_linear_map.applyₗ 𝕜 F v, continuous_linear_map.continuous_applyₗ _ _ _⟩ variables {𝕜 F} section multiplication_linear variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] /-- Left-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_left 𝕜 x).mk_continuous ∥x∥ (λ y, by {rw algebra.lmul_left_apply, exact norm_mul_le x y}) /-- Right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_right : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_right 𝕜 x).mk_continuous ∥x∥ (λ y, by {rw [algebra.lmul_right_apply, mul_comm], exact norm_mul_le y x}) /-- Simultaneous left- and right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left_right (vw : 𝕜' × 𝕜') : 𝕜' →L[𝕜] 𝕜' := (lmul_right 𝕜 𝕜' vw.2).comp (lmul_left 𝕜 𝕜' vw.1) @[simp] lemma lmul_left_apply (x y : 𝕜') : lmul_left 𝕜 𝕜' x y = x * y := rfl @[simp] lemma lmul_right_apply (x y : 𝕜') : lmul_right 𝕜 𝕜' x y = y * x := rfl @[simp] lemma lmul_left_right_apply (vw : 𝕜' × 𝕜') (x : 𝕜') : lmul_left_right 𝕜 𝕜' vw x = vw.1 * x * vw.2 := rfl end multiplication_linear section restrict_scalars variable (𝕜) variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] [normed_space 𝕜' E'] variables [is_scalar_tower 𝕜 𝕜' E'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] [normed_space 𝕜' F'] variables [is_scalar_tower 𝕜 𝕜' F'] /-- `𝕜`-linear continuous function induced by a `𝕜'`-linear continuous function when `𝕜'` is a normed algebra over `𝕜`. -/ def restrict_scalars (f : E' →L[𝕜'] F') : E' →L[𝕜] F' := { cont := f.cont, ..linear_map.restrict_scalars 𝕜 (f.to_linear_map) } @[simp, norm_cast] lemma restrict_scalars_coe_eq_coe (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' →ₗ[𝕜] F') = (f : E' →ₗ[𝕜'] F').restrict_scalars 𝕜 := rfl @[simp, norm_cast squash] lemma restrict_scalars_coe_eq_coe' (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' → F') = f := rfl end restrict_scalars section extend_scalars variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] [normed_space 𝕜' F'] variables [is_scalar_tower 𝕜 𝕜' F'] instance has_scalar_extend_scalars : has_scalar 𝕜' (E →L[𝕜] F') := { smul := λ c f, (c • f.to_linear_map).mk_continuous (∥c∥ * ∥f∥) begin assume x, calc ∥c • (f x)∥ = ∥c∥ * ∥f x∥ : norm_smul c _ ... ≤ ∥c∥ * (∥f∥ * ∥x∥) : mul_le_mul_of_nonneg_left (le_op_norm f x) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : (mul_assoc _ _ _).symm end } instance module_extend_scalars : module 𝕜' (E →L[𝕜] F') := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance normed_space_extend_scalars : normed_space 𝕜' (E →L[𝕜] F') := { norm_smul_le := λ c f, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ } /-- When `f` is a continuous linear map taking values in `S`, then `λb, f b • x` is a continuous linear map. -/ def smul_algebra_right (f : E →L[𝕜] 𝕜') (x : F') : E →L[𝕜] F' := { cont := by continuity!, .. f.to_linear_map.smul_algebra_right x } @[simp] theorem smul_algebra_right_apply (f : E →L[𝕜] 𝕜') (x : F') (c : E) : smul_algebra_right f x c = f c • x := rfl end extend_scalars end continuous_linear_map section has_sum -- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we -- don't have bundled continuous additive homomorphisms. variables {ι R M M₂ : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] [topological_space M] [topological_space M₂] omit 𝕜 /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_map.has_sum {f : ι → M} (φ : M →L[R] M₂) {x : M} (hf : has_sum f x) : has_sum (λ (b:ι), φ (f b)) (φ x) := by simpa only using hf.map φ.to_linear_map.to_add_monoid_hom φ.continuous alias continuous_linear_map.has_sum ← has_sum.mapL protected lemma continuous_linear_map.summable {f : ι → M} (φ : M →L[R] M₂) (hf : summable f) : summable (λ b:ι, φ (f b)) := (hf.has_sum.mapL φ).summable alias continuous_linear_map.summable ← summable.mapL protected lemma continuous_linear_map.map_tsum [t2_space M₂] {f : ι → M} (φ : M →L[R] M₂) (hf : summable f) : φ (∑' z, f z) = ∑' z, φ (f z) := (hf.has_sum.mapL φ).tsum_eq.symm /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_equiv.has_sum {f : ι → M} (e : M ≃L[R] M₂) {y : M₂} : has_sum (λ (b:ι), e (f b)) y ↔ has_sum f (e.symm y) := ⟨λ h, by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →L[R] M), λ h, by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →L[R] M₂).has_sum h⟩ protected lemma continuous_linear_equiv.summable {f : ι → M} (e : M ≃L[R] M₂) : summable (λ b:ι, e (f b)) ↔ summable f := ⟨λ hf, (e.has_sum.1 hf.has_sum).summable, (e : M →L[R] M₂).summable⟩ lemma continuous_linear_equiv.tsum_eq_iff [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃L[R] M₂) {y : M₂} : (∑' z, e (f z)) = y ↔ (∑' z, f z) = e.symm y := begin by_cases hf : summable f, { exact ⟨λ h, (e.has_sum.mp ((e.summable.mpr hf).has_sum_iff.mpr h)).tsum_eq, λ h, (e.has_sum.mpr (hf.has_sum_iff.mpr h)).tsum_eq⟩ }, { have hf' : ¬summable (λ z, e (f z)) := λ h, hf (e.summable.mp h), rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable hf'], exact ⟨by { rintro rfl, simp }, λ H, by simpa using (congr_arg (λ z, e z) H)⟩ } end protected lemma continuous_linear_equiv.map_tsum [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃L[R] M₂) : e (∑' z, f z) = ∑' z, e (f z) := by { refine symm (e.tsum_eq_iff.mpr _), rw e.symm_apply_apply _ } end has_sum namespace continuous_linear_equiv variable (e : E ≃L[𝕜] F) protected lemma lipschitz : lipschitz_with (nnnorm (e : E →L[𝕜] F)) e := (e : E →L[𝕜] F).lipschitz protected lemma antilipschitz : antilipschitz_with (nnnorm (e.symm : F →L[𝕜] E)) e := e.symm.lipschitz.to_right_inverse e.left_inv theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O (λ x', e (f x')) f l := (e : E →L[𝕜] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : asymptotics.is_O (λ x', e (x' - x)) (λ x', x' - x) l := (e : E →L[𝕜] F).is_O_sub l x theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O f (λ x', e (f x')) l := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : asymptotics.is_O (λ x', x' - x) (λ x', e (x' - x)) l := e.is_O_comp_rev _ _ /-- A continuous linear equiv is a uniform embedding. -/ lemma uniform_embedding : uniform_embedding e := e.antilipschitz.uniform_embedding e.lipschitz.uniform_continuous lemma one_le_norm_mul_norm_symm [nontrivial E] : 1 ≤ ∥(e : E →L[𝕜] F)∥ * ∥(e.symm : F →L[𝕜] E)∥ := begin rw [mul_comm], convert (e.symm : F →L[𝕜] E).op_norm_comp_le (e : E →L[𝕜] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end lemma norm_pos [nontrivial E] : 0 < ∥(e : E →L[𝕜] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma norm_symm_pos [nontrivial E] : 0 < ∥(e.symm : F →L[𝕜] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma subsingleton_or_norm_symm_pos : subsingleton E ∨ 0 < ∥(e.symm : F →L[𝕜] E)∥ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos : subsingleton E ∨ 0 < (nnnorm $ (e.symm : F →L[𝕜] E)) := subsingleton_or_norm_symm_pos e lemma homothety_inverse (a : ℝ) (ha : 0 < a) (f : E ≃ₗ[𝕜] F) : (∀ (x : E), ∥f x∥ = a * ∥x∥) → (∀ (y : F), ∥f.symm y∥ = a⁻¹ * ∥y∥) := begin intros hf y, calc ∥(f.symm) y∥ = a⁻¹ * (a * ∥ (f.symm) y∥) : _ ... = a⁻¹ * ∥f ((f.symm) y)∥ : by rw hf ... = a⁻¹ * ∥y∥ : by simp, rw [← mul_assoc, inv_mul_cancel (ne_of_lt ha).symm, one_mul], end variable (𝕜) /-- A linear equivalence which is a homothety is a continuous linear equivalence. -/ def of_homothety (f : E ≃ₗ[𝕜] F) (a : ℝ) (ha : 0 < a) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := f, continuous_to_fun := f.to_linear_map.continuous_of_bound a (λ x, le_of_eq (hf x)), continuous_inv_fun := f.symm.to_linear_map.continuous_of_bound a⁻¹ (λ x, le_of_eq (homothety_inverse a ha f hf x)) } lemma to_span_nonzero_singleton_homothety (x : E) (h : x ≠ 0) (c : 𝕜) : ∥linear_equiv.to_span_nonzero_singleton 𝕜 E x h c∥ = ∥x∥ * ∥c∥ := continuous_linear_map.to_span_singleton_homothety _ _ _ /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear equivalence from `E` to the span of `x`.-/ def to_span_nonzero_singleton (x : E) (h : x ≠ 0) : 𝕜 ≃L[𝕜] (submodule.span 𝕜 ({x} : set E)) := of_homothety 𝕜 (linear_equiv.to_span_nonzero_singleton 𝕜 E x h) ∥x∥ (norm_pos_iff.mpr h) (to_span_nonzero_singleton_homothety 𝕜 x h) /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from the span of `x` to `𝕜`.-/ abbreviation coord (x : E) (h : x ≠ 0) : (submodule.span 𝕜 ({x} : set E)) →L[𝕜] 𝕜 := (to_span_nonzero_singleton 𝕜 x h).symm lemma coord_norm (x : E) (h : x ≠ 0) : ∥coord 𝕜 x h∥ = ∥x∥⁻¹ := begin have hx : 0 < ∥x∥ := (norm_pos_iff.mpr h), haveI : nontrivial (submodule.span 𝕜 ({x} : set E)) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end lemma coord_self (x : E) (h : x ≠ 0) : (coord 𝕜 x h) (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span 𝕜 ({x} : set E)) = 1 := linear_equiv.coord_self 𝕜 E x h end continuous_linear_equiv lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding { continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } /-- Construct a continuous linear equivalence from a linear equivalence together with bounds in both directions. -/ def linear_equiv.to_continuous_linear_equiv_of_bounds (e : E ≃ₗ[𝕜] F) (C_to C_inv : ℝ) (h_to : ∀ x, ∥e x∥ ≤ C_to * ∥x∥) (h_inv : ∀ x : F, ∥e.symm x∥ ≤ C_inv * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := e, continuous_to_fun := e.to_linear_map.continuous_of_bound C_to h_to, continuous_inv_fun := e.symm.to_linear_map.continuous_of_bound C_inv h_inv } namespace continuous_linear_map variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma lmul_left_norm (v : 𝕜') : ∥lmul_left 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_left 𝕜 𝕜' v) (1:𝕜') } end @[simp] lemma lmul_right_norm (v : 𝕜') : ∥lmul_right 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_right 𝕜 𝕜' v) (1:𝕜') } end lemma lmul_left_right_norm_le (vw : 𝕜' × 𝕜') : ∥lmul_left_right 𝕜 𝕜' vw∥ ≤ ∥vw.1∥ * ∥vw.2∥ := by simpa [mul_comm] using op_norm_comp_le (lmul_right 𝕜 𝕜' vw.2) (lmul_left 𝕜 𝕜' vw.1) end continuous_linear_map
8931a9a9d244a1bfa8d8bae563705ed3cf88fa1c
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/analysis/calculus/mean_value.lean
74d315a00638d8d4bb55907eca1a7bb3b8e70072
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
24,716
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, Yury Kudryashov -/ import analysis.calculus.local_extr /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentaible on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`. * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.mono_of_deriv_nonneg`, `convex.antimono_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_antimono_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/monotonically decreasing/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_mono`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. -/ set_option class.instance_max_depth 120 variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set lattice asymptotics continuous_linear_map /-! ### Vector-valued functions `f : E → F` -/ /-- The mean value theorem along a segment: a bound on the derivative of a function along a segment implies a bound on the distance of the endpoints images -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {f : ℝ → F} {C : ℝ} (hf : differentiable_on ℝ f (Icc 0 1)) (bound : ∀t ∈ Icc (0:ℝ) 1, ∥deriv_within f (Icc 0 1) t∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := begin /- Let D > C. We will show that, for all t ∈ [0,1], one has ∥f t - f 0∥ ≤ D * t. This is true for t=0. Let k be maximal in [0,1] for which this holds. By continuity of all functions, the maximum is realized. If k were <1, then a point x slightly to its right would satisfy ∥f x - f k∥ ≤ D * (k-x), since the differential of f at k has norm at most C < D. Therefore, the point x also satisfies ∥f x - f 0∥ ≤ D * x, contradicting the maximality of k. Hence, k = 1. -/ refine le_of_forall_le_of_dense (λD hD, _), let K := {t ∈ Icc (0 : ℝ) 1 | ∥f t - f 0∥ ≤ D * t}, let k := Sup K, have k_mem_K : k ∈ K, { refine cSup_mem_of_is_closed _ _ _, show K ≠ ∅, { have : (0 : ℝ) ∈ K, by simp [K, le_refl, zero_le_one], apply ne_empty_of_mem this }, show bdd_above K, from ⟨1, λy hy, hy.1.2⟩, have A : continuous_on (λt:ℝ, (∥f t - f 0∥, D * t)) (Icc 0 1), { apply continuous_on.prod, { refine continuous_norm.comp_continuous_on _, apply continuous_on.sub hf.continuous_on continuous_on_const }, { exact (continuous_const.mul continuous_id).continuous_on } }, show is_closed K, from A.preimage_closed_of_closed is_closed_Icc (ordered_topology.is_closed_le' _) }, have : k = 1, { by_contradiction k_ne_1, have k_lt_1 : k < 1 := lt_of_le_of_ne k_mem_K.1.2 k_ne_1, have : 0 ≤ k := k_mem_K.1.1, let g := deriv_within f (Icc 0 1) k, let h := λx, f x - f k - (x-k) • g, have : is_o (λ x, h x) (λ x, x - k) (nhds_within k (Icc 0 1)) := (hf k k_mem_K.1).has_deriv_within_at, have : {x | ∥h x∥ ≤ (D-C) * ∥x-k∥} ∈ nhds_within k (Icc 0 1) := this (sub_pos_of_lt hD), rcases mem_nhds_within.1 this with ⟨s, s_open, ks, hs⟩, rcases is_open_iff.1 s_open k ks with ⟨ε, εpos, hε⟩, change 0 < ε at εpos, let δ := min ε (1-k), have δpos : 0 < δ, by simp [δ, εpos, k_lt_1], let x := k + δ/2, have k_lt_x : k < x, by { simp only [x], linarith }, have x_lt_1 : x < 1 := calc x < k + δ : add_lt_add_left (half_lt_self δpos) _ ... ≤ k + (1-k) : add_le_add_left (min_le_right _ _) _ ... = 1 : by ring, have xε : x ∈ ball k ε, { simp [dist, x, abs_of_nonneg (le_of_lt (half_pos δpos))], exact lt_of_lt_of_le (half_lt_self δpos) (min_le_left _ _) }, have xI : x ∈ Icc (0:ℝ) 1 := ⟨le_of_lt (lt_of_le_of_lt (k_mem_K.1.1) k_lt_x), le_of_lt x_lt_1⟩, have Ih : ∥h x∥ ≤ (D - C) * ∥x - k∥ := hs ⟨hε xε, xI⟩, have I : ∥f x - f k∥ ≤ D * (x-k) := calc ∥f x - f k∥ = ∥(x-k) • g + h x∥ : by { congr' 1, simp only [h], abel } ... ≤ ∥g∥ * ∥x-k∥ + (D-C) * ∥x-k∥ : norm_add_le_of_le (by rw [norm_smul, mul_comm]) Ih ... ≤ C * ∥x-k∥ + (D-C) * ∥x-k∥ : add_le_add_right (mul_le_mul_of_nonneg_right (bound k k_mem_K.1) (norm_nonneg _)) _ ... = D * ∥x-k∥ : by ring ... = D * (x-k) : by simp [norm, abs_of_nonneg (le_of_lt (half_pos δpos))], have : ∥f x - f 0∥ ≤ D * x := calc ∥f x - f 0∥ = ∥(f x - f k) + (f k - f 0)∥ : by { congr' 1, abel } ... ≤ D * (x - k) + D * k : norm_add_le_of_le I (k_mem_K.2) ... = D * x : by ring, have xK : x ∈ K := ⟨xI, this⟩, have : x ≤ k := le_cSup ⟨1, λy hy, hy.1.2⟩ xK, exact (not_le_of_lt k_lt_x) this }, rw this at k_mem_K, simpa [this] using k_mem_K.2 end /-- The mean value theorem on a convex set: if the derivative of a function is bounded by C, then the function is C-Lipschitz -/ theorem convex.norm_image_sub_le_of_norm_deriv_le {f : E → F} {C : ℝ} {s : set E} {x y : E} (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥fderiv_within ℝ f s x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := begin /- By composition with t ↦ x + t • (y-x), we reduce to a statement for functions defined on [0,1], for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), let g := λ(t:ℝ), f (x + t • (y-x)), have D1 : differentiable ℝ (λt:ℝ, x + t • (y-x)) := (differentiable_id.smul_const (y - x)).const_add x, have segm : (λ (t : ℝ), x + t • (y - x)) '' Icc 0 1 ⊆ s, by { rw [← segment_eq_image_Icc_zero_one], apply convex_segment_iff.1 hs x y xs ys }, have : f x = g 0, by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = g 1, by { simp only [g], rw one_smul, congr' 1, abel }, rw this, apply norm_image_sub_le_of_norm_deriv_le_segment (hf.comp D1.differentiable_on (image_subset_iff.1 segm)) (λt ht, _), /- It remains to check that the derivative of g is bounded by C ∥y-x∥ at any t ∈ [0,1] -/ have t_s : x + t • (y-x) ∈ s := segm (mem_image_of_mem _ ht), /- Expand the derivative of the composition, and bound its norm by the product of the norms -/ rw fderiv_within.comp_deriv_within t (hf _ t_s) ((D1 t).differentiable_within_at) (image_subset_iff.1 segm) (unique_diff_on_Icc_zero_one t ht), refine le_trans (le_op_norm _ _) (mul_le_mul (bound _ t_s) _ (norm_nonneg _) C0), have : deriv_within (λ (t : ℝ), x + t • (y - x)) (Icc 0 1) t = y - x := calc deriv_within (λ (t : ℝ), x + t • (y - x)) (Icc 0 1) t = deriv (λ (t : ℝ), x + t • (y - x)) t : differentiable_at.deriv_within (D1 t) (unique_diff_on_Icc_zero_one t ht) ... = deriv (λ (t : ℝ), t • (y-x)) t : deriv_const_add x ((differentiable_id.smul_const (y - x)) t) ... = (deriv (@_root_.id ℝ) t) • (y - x) : deriv_smul_const differentiable_at_id _ ... = y - x : by rw [deriv_id, one_smul], rw [this] end /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem convex.is_const_of_fderiv_within_eq_zero {s : set E} (hs : convex s) {f : E → F} (hf : differentiable_on ℝ f s) (hf' : ∀ x ∈ s, fderiv_within ℝ f s x = 0) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ∥fderiv_within ℝ f s x∥ ≤ 0, from λ x hx, by simp only [hf' x hx, _root_.norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_deriv_le hf bound hx hy theorem is_const_of_fderiv_eq_zero {f : E → F} (hf : differentiable ℝ f) (hf' : ∀ x, fderiv ℝ f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's Mean Value Theorem, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hgc hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) g (deriv g) hgc (λ x hx, ((hgd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) /-- Lagrange's Mean Value Theorem, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x y hx hy hxy, have hxyD : Icc x y ⊆ D, from convex_real_iff.1 hD hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x y hx hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from convex_real_iff.1 hD hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x y hx hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv_neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x y hx hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv_neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotonically increasing function on `D`. -/ theorem convex.strict_mono_of_deriv_pos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_pos : ∀ x ∈ interior D, 0 < deriv f x) : ∀ x y ∈ D, x < y → f x < f y := by simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf hf' hf'_pos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotonically increasing function. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_pos : ∀ x, 0 < deriv f x) : strict_mono f := λ x y hxy, convex_univ.strict_mono_of_deriv_pos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_pos x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotonically increasing function on `D`. -/ theorem convex.mono_of_deriv_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → f x ≤ f y := by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotonically increasing function. -/ theorem mono_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := λ x y hxy, convex_univ.mono_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly monotonically decreasing function on `D`. -/ theorem convex.strict_antimono_of_deriv_neg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_neg : ∀ x ∈ interior D, deriv f x < 0) : ∀ x y ∈ D, x < y → f y < f x := by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf hf' hf'_neg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly monotonically decreasing function. -/ theorem strict_antimono_of_deriv_neg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x < 0) : ∀ ⦃x y⦄, x < y → f y < f x := λ x y hxy, convex_univ.strict_antimono_of_deriv_neg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is a monotonically decreasing function on `D`. -/ theorem convex.antimono_of_deriv_nonpos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : ∀ x y ∈ D, x ≤ y → f y ≤ f x := by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is a monotonically decreasing function. -/ theorem antimono_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : ∀ ⦃x y⦄, x ≤ y → f y ≤ f x := λ x y hxy, convex_univ.antimono_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv_mono {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : ∀ x y ∈ interior D, x ≤ y → deriv f x ≤ deriv f y) : convex_on D f := convex_on_real_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from convex_real_iff.1 hD hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono a b (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (le_of_lt $ lt_trans hay hyb) end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv_mono {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on univ f := convex_on_of_deriv_mono convex_univ hf.continuous.continuous_on hf.differentiable_on (λ x y _ _ h, hf'_mono h) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on D f := convex_on_of_deriv_mono hD hf hf' $ assume x y hx hy hxy, hD.interior.mono_of_deriv_nonneg hf''.continuous_on (by rwa [interior_interior]) (by rwa [interior_interior]) _ _ hx hy hxy /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f x)) : convex_on univ f := convex_on_of_deriv2_nonneg convex_univ hf'.continuous.continuous_on hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x)
ad1cf28e4f906f2d4129647fbd2dc4df993c3e56
4727251e0cd73359b15b664c3170e5d754078599
/src/data/seq/wseq.lean
b3a090a28752ca67e277ab823b2ce5a8869033c6
[ "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
55,326
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.dlist import data.list.basic import data.seq.seq open function universes u v w /- coinductive wseq (α : Type u) : Type u | nil : wseq α | cons : α → wseq α → wseq α | think : wseq α → wseq α -/ /-- Weak sequences. While the `seq` structure allows for lists which may not be finite, a weak sequence also allows the computation of each element to involve an indeterminate amount of computation, including possibly an infinite loop. This is represented as a regular `seq` interspersed with `none` elements to indicate that computation is ongoing. This model is appropriate for Haskell style lazy lists, and is closed under most interesting computation patterns on infinite lists, but conversely it is difficult to extract elements from it. -/ def wseq (α) := seq (option α) namespace wseq variables {α : Type u} {β : Type v} {γ : Type w} /-- Turn a sequence into a weak sequence -/ def of_seq : seq α → wseq α := (<$>) some /-- Turn a list into a weak sequence -/ def of_list (l : list α) : wseq α := of_seq l /-- Turn a stream into a weak sequence -/ def of_stream (l : stream α) : wseq α := of_seq l instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩ instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩ instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩ /-- The empty weak sequence -/ def nil : wseq α := seq.nil instance : inhabited (wseq α) := ⟨nil⟩ /-- Prepend an element to a weak sequence -/ def cons (a : α) : wseq α → wseq α := seq.cons (some a) /-- Compute for one tick, without producing any elements -/ def think : wseq α → wseq α := seq.cons none /-- Destruct a weak sequence, to (eventually possibly) produce either `none` for `nil` or `some (a, s)` if an element is produced. -/ def destruct : wseq α → computation (option (α × wseq α)) := computation.corec (λs, match seq.destruct s with | none := sum.inl none | some (none, s') := sum.inr s' | some (some a, s') := sum.inl (some (a, s')) end) def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s := seq.cases_on s h1 (λ o, option.cases_on o h3 h2) protected def mem (a : α) (s : wseq α) := seq.mem (some a) s instance : has_mem α (wseq α) := ⟨wseq.mem⟩ theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a /-- Get the head of a weak sequence. This involves a possibly infinite computation. -/ def head (s : wseq α) : computation (option α) := computation.map ((<$>) prod.fst) (destruct s) /-- Encode a computation yielding a weak sequence into additional `think` constructors in a weak sequence -/ def flatten : computation (wseq α) → wseq α := seq.corec (λc, match computation.destruct c with | sum.inl s := seq.omap return (seq.destruct s) | sum.inr c' := some (none, c') end) /-- Get the tail of a weak sequence. This doesn't need a `computation` wrapper, unlike `head`, because `flatten` allows us to hide this in the construction of the weak sequence itself. -/ def tail (s : wseq α) : wseq α := flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s /-- drop the first `n` elements from `s`. -/ def drop (s : wseq α) : ℕ → wseq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Get the nth element of `s`. -/ def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n) /-- Convert `s` to a list (if it is finite and completes in finite time). -/ def to_list (s : wseq α) : computation (list α) := @computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩, match seq.destruct s with | none := sum.inl l.reverse | some (none, s') := sum.inr (l, s') | some (some a, s') := sum.inr (a::l, s') end) ([], s) /-- Get the length of `s` (if it is finite and completes in finite time). -/ def length (s : wseq α) : computation ℕ := @computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s with | none := sum.inl n | some (none, s') := sum.inr (n, s') | some (some a, s') := sum.inr (n+1, s') end) (0, s) /-- A weak sequence is finite if `to_list s` terminates. Equivalently, it is a finite number of `think` and `cons` applied to `nil`. -/ class is_finite (s : wseq α) : Prop := (out : (to_list s).terminates) instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h.out /-- Get the list corresponding to a finite weak sequence. -/ def get (s : wseq α) [is_finite s] : list α := (to_list s).get /-- A weak sequence is *productive* if it never stalls forever - there are always a finite number of `think`s between `cons` constructors. The sequence itself is allowed to be infinite though. -/ class productive (s : wseq α) : Prop := (nth_terminates : ∀ n, (nth s n).terminates) theorem productive_iff (s : wseq α) : productive s ↔ ∀ n, (nth s n).terminates := ⟨λ h, h.1, λ h, ⟨h⟩⟩ instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h.nth_terminates instance head_terminates (s : wseq α) [productive s] : (head s).terminates := s.nth_terminates 0 /-- Replace the `n`th element of `s` with `a`. -/ def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (some a, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Remove the `n`th element of `s`. -/ def remove_nth (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (none, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Map the elements of `s` over `f`, removing any values that yield `none`. -/ def filter_map (f : α → option β) : wseq α → wseq β := seq.corec (λs, match seq.destruct s with | none := none | some (none, s') := some (none, s') | some (some a, s') := some (f a, s') end) /-- Select the elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α := filter_map (λa, if p a then some a else none) -- example of infinite list manipulations /-- Get the first element of `s` satisfying `p`. -/ def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) := head $ filter p s /-- Zip a function over two weak sequences -/ def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ := @seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (none, s1, s2') | some (none, s1'), some (some a2, s2') := some (none, s1', s2) | some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2') | _, _ := none end) (s1, s2) /-- Zip two weak sequences into a single sequence of pairs -/ def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk /-- Get the list of indexes of elements of `s` satisfying `p` -/ def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ := (zip s (stream.nats : wseq ℕ)).filter_map (λ ⟨a, n⟩, if p a then some n else none) /-- Get the index of the first element of `s` satisfying `p` -/ def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ := (λ o, option.get_or_else o 0) <$> head (find_indexes p s) /-- Get the index of the first occurrence of `a` in `s` -/ def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a) /-- Get the indexes of occurrences of `a` in `s` -/ def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a) /-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in some order (nondeterministically). -/ def union (s1 s2 : wseq α) : wseq α := @seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | none, none := none | some (a1, s1'), none := some (a1, s1', nil) | none, some (a2, s2') := some (a2, nil, s2') | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (some a1, s1', s2') | some (none, s1'), some (some a2, s2') := some (some a2, s1', s2') | some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2') end) (s1, s2) /-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/ def is_empty (s : wseq α) : computation bool := computation.map option.is_none $ head s /-- Calculate one step of computation -/ def compute (s : wseq α) : wseq α := match seq.destruct s with | some (none, s') := s' | _ := s end /-- Get the first `n` elements of a weak sequence -/ def take (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match n, seq.destruct s with | 0, _ := none | m+1, none := none | m+1, some (none, s') := some (none, m+1, s') | m+1, some (some a, s') := some (some a, m, s') end) (n, s) /-- Split the sequence at position `n` into a finite initial segment and the weak sequence tail -/ def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) := @computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩, match n, seq.destruct s with | 0, _ := sum.inl (l.reverse, s) | m+1, none := sum.inl (l.reverse, s) | m+1, some (none, s') := sum.inr (n, l, s') | m+1, some (some a, s') := sum.inr (m, a::l, s') end) (n, [], s) /-- Returns `tt` if any element of `s` satisfies `p` -/ def any (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl ff | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inl tt else sum.inr s' end) s /-- Returns `tt` if every element of `s` satisfies `p` -/ def all (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl tt | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inr s' else sum.inl ff end) s /-- Apply a function to the elements of the sequence to produce a sequence of partial results. (There is no `scanr` because this would require working from the end of the sequence, which may not exist.) -/ def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α := cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, a, s') | some (some b, s') := let a' := f a b in some (some a', a', s') end) (a, s) /-- Get the weak sequence of initial segments of the input sequence -/ def inits (s : wseq α) : wseq (list α) := cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, l, s') | some (some a, s') := let l' := l.concat a in some (some l'.to_list, l', s') end) (dlist.empty, s) /-- Like take, but does not wait for a result. Calculates `n` steps of computation and returns the sequence computed so far -/ def collect (s : wseq α) (n : ℕ) : list α := (seq.take n s).filter_map id /-- Append two weak sequences. As with `seq.append`, this may not use the second sequence if the first one takes forever to compute -/ def append : wseq α → wseq α → wseq α := seq.append /-- Map a function over a weak sequence -/ def map (f : α → β) : wseq α → wseq β := seq.map (option.map f) /-- Flatten a sequence of weak sequences. (Note that this allows empty sequences, unlike `seq.join`.) -/ def join (S : wseq (wseq α)) : wseq α := seq.join ((λo : option (wseq α), match o with | none := seq1.ret none | some s := (none, s) end) <$> S) /-- Monadic bind operator for weak sequences -/ def bind (s : wseq α) (f : α → wseq β) : wseq β := join (map f s) @[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) : option (α × wseq α) → option (β × wseq β) → Prop | none none := true | (some (a, s)) (some (b, t)) := R a b ∧ C s t | _ _ := false theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop} (H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) : ∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p | none none h := trivial | (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h | none (some _) h := false.elim h | (some (_, _)) none h := false.elim h theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop} (H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p := lift_rel_o.imp (λ _ _, id) H @[simp] def bisim_o (R : wseq α → wseq α → Prop) : option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} : bisim_o R o p → bisim_o S o p := lift_rel_o.imp_right _ H /-- Two weak sequences are `lift_rel R` related if they are either both empty, or they are both nonempty and the heads are `R` related and the tails are `lift_rel R` related. (This is a coinductive definition.) -/ def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop := ∃ C : wseq α → wseq β → Prop, C s t ∧ ∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t) /-- If two sequences are equivalent, then they have the same values and the same computational behavior (i.e. if one loops forever then so does the other), although they may differ in the number of `think`s needed to arrive at the answer. -/ def equiv : wseq α → wseq α → Prop := lift_rel (=) theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t → computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) | ⟨R, h1, h2⟩ := by refine computation.lift_rel.imp _ _ _ (h2 h1); apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩ theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t ↔ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) := ⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), or.inr h, λ s t h, begin have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), { cases h with h h, exact lift_rel_destruct h, assumption }, apply computation.lift_rel.imp _ _ _ h, intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end⟩⟩ infix ` ~ `:50 := equiv theorem destruct_congr {s t : wseq α} : s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct theorem destruct_congr_iff {s t : wseq α} : s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct_iff theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, begin refine ⟨(=), rfl, λ s t (h : s = t), _⟩, rw ←h, apply computation.lift_rel.refl, intro a, cases a with a, simp, cases a; simp, apply H end theorem lift_rel_o.swap (R : α → β → Prop) (C) : swap (lift_rel_o R C) = lift_rel_o (swap R) (swap C) := by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl } theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) : lift_rel (swap R) s2 s1 := begin refine ⟨swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩, rw [←lift_rel_o.swap, computation.lift_rel.swap], apply lift_rel_destruct h end theorem lift_rel.swap (R : α → β → Prop) : swap (lift_rel R) = lift_rel (swap R) := funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 (h : swap (lift_rel R) s2 s1), by rwa [lift_rel.swap, show swap R = R, from funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s t u h1 h2, begin refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩, rcases h with ⟨t, h1, h2⟩, have h1 := lift_rel_destruct h1, have h2 := lift_rel_destruct h2, refine computation.lift_rel_def.2 ⟨(computation.terminates_of_lift_rel h1).trans (computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩, rcases h1.left ha with ⟨b, hb, t1⟩, have t2 := computation.rel_of_lift_rel h2 hb hc, cases a with a; cases c with c, { trivial }, { cases b, {cases t2}, {cases t1} }, { cases a, cases b with b, {cases t1}, {cases b, cases t2} }, { cases a with a s, cases b with b, {cases t1}, cases b with b t, cases c with c u, cases t1 with ab st, cases t2 with bc tu, exact ⟨H ab bc, t, st, tu⟩ } end theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ @[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s := lift_rel.refl (=) eq.refl @[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s := lift_rel.symm (=) (@eq.symm _) @[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u := lift_rel.trans (=) (@eq.trans _) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ open computation local notation `return` := computation.return @[simp] theorem destruct_nil : destruct (nil : wseq α) = return none := computation.destruct_eq_ret rfl @[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) := computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap] @[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think := computation.destruct_eq_think $ by simp [destruct, think, computation.rmap] @[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none := seq.destruct_nil @[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) := seq.destruct_cons _ _ @[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) := seq.destruct_cons _ _ @[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl @[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl @[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s := begin refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl, intros s' s h, rw ←h, simp [flatten], cases seq.destruct s, { simp }, { cases val with o s', simp } end @[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) := seq.destruct_eq_cons $ by simp [flatten, think] @[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct := begin refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, (or.inr ⟨c, rfl, rfl⟩) := begin apply c.cases_on (λa, _) (λc', _); repeat {simp}, { cases (destruct a).destruct; simp }, { exact or.inr ⟨c', rfl, rfl⟩ } end end end theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) := terminates_map_iff _ (destruct s) @[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail] @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail] @[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail] @[simp] theorem dropn_nil (n) : drop (nil : wseq α) n = nil := by induction n; simp [*, drop] @[simp] theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop] @[simp] theorem dropn_think (s : wseq α) (n) : drop (think s) n = (drop s n).think := by induction n; simp [*, drop] theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n := congr_arg head (dropn_add _ _ _) theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) := congr_arg head (dropn_tail _ _) @[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil @[simp] theorem join_think (S : wseq (wseq α)) : join (think S) = think (join S) := by { simp [think, join], unfold functor.map, simp [join, seq1.ret] } @[simp] theorem join_cons (s : wseq α) (S) : join (cons s S) = think (append s (join S)) := by { simp [think, join], unfold functor.map, simp [join, cons, append] } @[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _ @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _ @[simp] theorem think_append (s t : wseq α) : append (think s) t = think (append s t) := seq.cons_append _ _ _ @[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _ @[simp] theorem append_assoc (s t u : wseq α) : append (append s t) u = append s (append t u) := seq.append_assoc _ _ _ @[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α)) | none := return none | (some (a, s)) := destruct s theorem destruct_tail (s : wseq α) : destruct (tail s) = destruct s >>= tail.aux := begin simp [tail], rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc], apply congr_arg, ext1 (_|⟨a, s⟩); apply (@pure_bind computation _ _ _ _ _ _).trans _; simp end @[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α)) | 0 := return | (n+1) := λ a, tail.aux a >>= drop.aux n theorem drop.aux_none : ∀ n, @drop.aux α n none = return none | 0 := rfl | (n+1) := show computation.bind (return none) (drop.aux n) = return none, by rw [ret_bind, drop.aux_none] theorem destruct_dropn : ∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n | s 0 := (bind_ret' _).symm | s (n+1) := by rw [← dropn_tail, destruct_dropn _ n, destruct_tail, is_lawful_monad.bind_assoc]; refl theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] : terminates (head s) := (head_terminates_iff _).2 $ begin rcases (head_terminates_iff _).1 T with ⟨⟨a, h⟩⟩, simp [tail] at h, rcases exists_of_mem_bind h with ⟨s', h1, h2⟩, unfold functor.map at h1, exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3 end theorem destruct_some_of_destruct_tail_some {s : wseq α} {a} (h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s := begin unfold tail functor.map at h, simp at h, rcases exists_of_mem_bind h with ⟨t, tm, td⟩, clear h, rcases exists_of_mem_map tm with ⟨t', ht', ht2⟩, clear tm, cases t' with t'; rw ←ht2 at td; simp at td, { have := mem_unique td (ret_mem _), contradiction }, { exact ⟨_, ht'⟩ } end theorem head_some_of_head_tail_some {s : wseq α} {a} (h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s := begin unfold head at h, rcases exists_of_mem_map h with ⟨o, md, e⟩, clear h, cases o with o; injection e with h', clear e h', cases destruct_some_of_destruct_tail_some md with a am, exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩ end theorem head_some_of_nth_some {s : wseq α} {a n} (h : some a ∈ nth s n) : ∃ a', some a' ∈ head s := begin revert a, induction n with n IH; intros, exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h'] end instance productive_tail (s : wseq α) [productive s] : productive (tail s) := ⟨λ n, by rw [nth_tail]; apply_instance⟩ instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) := ⟨λ m, by rw [←nth_add]; apply_instance⟩ /-- Given a productive weak sequence, we can collapse all the `think`s to produce a sequence. -/ def to_seq (s : wseq α) [productive s] : seq α := ⟨λ n, (nth s n).get, λn h, begin cases e : computation.get (nth s (n + 1)), {assumption}, have := mem_of_get_eq _ e, simp [nth] at this h, cases head_some_of_head_tail_some this with a' h', have := mem_unique h' (@mem_of_get_eq _ _ _ _ h), contradiction end⟩ theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) := by induction h with m' h IH; [exact id, exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)] theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) := nth_terminates_le (nat.zero_le n) theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) := (head_terminates_iff _).1 $ head_terminates_of_nth_terminates T theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) (h2 : ∀ s, C s → C (think s)) : C s := begin apply seq.mem_rec_on M, intros o s' h, cases o with b, { apply h2, cases h, {contradiction}, {assumption} }, { apply h1, apply or.imp_left _ h, intro h, injection h } end @[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s := begin cases s with f al, change some (some a) ∈ some none :: f ↔ some (some a) ∈ f, constructor; intro h, { apply (stream.eq_or_mem_of_mem_cons h).resolve_left, intro, injections }, { apply stream.mem_cons_of_mem _ h } end theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} : some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := begin generalize e : destruct s = c, intro h, revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s; apply s.cases_on _ (λ x s, _) (λ s, _); intros m; have := congr_arg computation.destruct m; simp at this; cases this with i1 i2, { rw [i1, i2], cases s' with f al, unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp, have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp}, rw [h_a_eq_a'], refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩, { cases o with e m, { rw e, apply stream.mem_cons }, { exact stream.mem_cons_of_mem _ m } } }, { simp, exact IH this } end @[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s := eq_or_mem_iff_mem $ by simp [ret_mem] theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s := (mem_cons_iff _ _).2 (or.inr h) theorem mem_cons (s : wseq α) (a) : a ∈ cons a s := (mem_cons_iff _ _).2 (or.inl rfl) theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s := begin intro h, have := h, cases h with n e, revert s, simp [stream.nth], induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _); repeat{simp}; intros m e; injections, { exact or.inr m }, { exact or.inr m }, { apply IH m, rw e, cases tail s, refl } end theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s | 0 h := h | (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h) theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s := begin revert s, induction n with n IH; intros s h, { rcases exists_of_mem_map h with ⟨o, h1, h2⟩, cases o with o; injection h2 with h', cases o with a' s', exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) }, { have := @IH (tail s), rw nth_tail at this, exact mem_of_mem_tail (this h) } end theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n := begin apply mem_rec_on h, { intros a' s' h, cases h with h h, { existsi 0, simp [nth], rw h, apply ret_mem }, { cases h with n h, existsi n+1, simp [nth], exact h } }, { intros s' h, cases h with n h, existsi n, simp [nth], apply think_mem h } end theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n s', some (a, s') ∈ destruct (drop s n) := let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin rcases (head_terminates_iff _).1 ⟨⟨_, h⟩⟩ with ⟨⟨o, om⟩⟩, have := mem_unique (mem_map _ om) h, cases o with o; injection this with i, cases o with a' s', dsimp at i, rw i at om, exact ⟨_, om⟩ end⟩ theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) : ∀ n, computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct (drop s n)) (destruct (drop t n)) | 0 := lift_rel_destruct H | (n+1) := begin simp [destruct_tail], apply lift_rel_bind, apply lift_rel_dropn_destruct n, exact λ a b o, match a, b, o with | none, none, _ := by simp | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2 end end theorem exists_of_lift_rel_left {R : α → β → Prop} {s t} (H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b := let ⟨n, h⟩ := exists_nth_of_mem h, ⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h, ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in ⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩ theorem exists_of_lift_rel_right {R : α → β → Prop} {s t} (H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b := by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) := let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨⟨_, h⟩⟩ theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ := seq.of_mem_append theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ := seq.mem_append_left theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ @[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) : lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) : lift_rel R (think s) t ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) : lift_rel R s (think t) ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t := by unfold equiv; simp; exact h theorem think_equiv (s : wseq α) : think s ~ s := by unfold equiv; simp; apply equiv.refl theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t := by unfold equiv; simp; exact h theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t := suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from λ s t h o, ⟨this h, this h.symm⟩, begin intros s t h o ho, rcases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩, rw ←dse, cases destruct_congr h with l r, rcases l dsm with ⟨dt, dtm, dst⟩, cases ds with a; cases dt with b, { apply mem_map _ dtm }, { cases b, cases dst }, { cases a, cases dst }, { cases a with a s', cases b with b t', rw dst.left, exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst) _ (destruct t) dtm } end theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s := begin apply computation.mem_rec_on h, { simp }, { intro s', apply equiv.trans, simp [think_equiv] } end theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)} (h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) := let S := λ s t, ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in ⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h, match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin simp, apply lift_rel_bind _ _ h, intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab), intros a b, apply lift_rel_o.imp_right, intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h] end end⟩ theorem flatten_congr {c1 c2 : computation (wseq α)} : computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t := begin apply flatten_congr, unfold functor.map, rw [←bind_ret, ←bind_ret], apply lift_rel_bind _ _ (destruct_congr h), intros a b h, simp, cases a with a; cases b with b, { trivial }, { cases h }, { cases a, cases h }, { cases a with a s', cases b with b t', exact h.right } end theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n := by induction n; simp [*, tail_congr] theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n := head_congr (dropn_congr h _) theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t := suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩, λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in nth_mem ((nth_congr h _ _).1 hn) theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t := by simp only [productive_iff]; exact forall_congr (λ n, terminates_congr $ nth_congr h _) theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t := ⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin refine lift_rel_def.2 ⟨_, _⟩, { rw [←head_terminates_iff, ←head_terminates_iff], exact terminates_congr (h 0) }, { intros a b ma mb, cases a with a; cases b with b, { trivial }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { cases a with a s', cases b with b t', injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab, refine ⟨ab, λ n, _⟩, refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans ((_ : nth (tail s) n ~ nth (tail t) n).trans (nth_congr (flatten_equiv (mem_map _ mb)) n)), rw [nth_tail, nth_tail], apply h } } end⟩ theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) := begin refine eq_of_bisim (λ c1 c2, ∃ (l : list α) (s : wseq α), c1 = corec length._match_2 (l.length, s) ∧ c2 = computation.map list.length (corec to_list._match_2 (l, s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l, s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l, s, _, _⟩; simp }, { refine ⟨l, s, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := show seq.map some (seq.of_list (a :: l)) = seq.cons (some a) (seq.map some (seq.of_list l)), by simp @[simp] theorem to_list'_nil (l : list α) : corec to_list._match_2 (l, nil) = return l.reverse := destruct_eq_ret rfl @[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) : corec to_list._match_2 (l, cons a s) = (corec to_list._match_2 (a::l, s)).think := destruct_eq_think $ by simp [to_list, cons] @[simp] theorem to_list'_think (l : list α) (s : wseq α) : corec to_list._match_2 (l, think s) = (corec to_list._match_2 (l, s)).think := destruct_eq_think $ by simp [to_list, think] theorem to_list'_map (l : list α) (s : wseq α) : corec to_list._match_2 (l, s) = ((++) l.reverse) <$> to_list s := begin refine eq_of_bisim (λ c1 c2, ∃ (l' : list α) (s : wseq α), c1 = corec to_list._match_2 (l' ++ l, s) ∧ c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l', s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l', s, _, _⟩; simp }, { refine ⟨l', s, _, _⟩; simp } end @[simp] theorem to_list_cons (a : α) (s) : to_list (cons a s) = (list.cons a <$> to_list s).think := destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl @[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] := destruct_eq_ret rfl theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) := by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH) @[simp] theorem destruct_of_seq (s : seq α) : destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) := destruct_eq_ret $ begin simp [of_seq, head, destruct, seq.destruct, seq.head], rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth], cases seq.nth s 0 with a, { refl }, unfold functor.map, simp [destruct] end @[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head := by simp [head]; cases seq.head s; refl @[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail := begin simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl}, rw [seq.head_cons, seq.tail_cons], refl end @[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n) | 0 := rfl | (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq] theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) := by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn] instance productive_of_seq (s : seq α) : productive (of_seq s) := ⟨λ n, by rw nth_of_seq; apply_instance⟩ theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s := begin apply subtype.eq, funext n, dsimp [to_seq], apply get_eq_of_mem, rw nth_of_seq, apply ret_mem end /-- The monadic `return a` is a singleton list containing `a`. -/ def ret (a : α) : wseq α := of_list [a] @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _ @[simp] theorem map_think (f : α → β) (s) : map f (think s) = think (map f s) := seq.map_cons _ _ _ @[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map] @[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret] @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := seq.map_append _ _ _ theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) : map (g ∘ f) s = map g (map f s) := begin dsimp [map], rw ←seq.map_comp, apply congr_fun, apply congr_arg, ext ⟨⟩; refl end theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s := seq.mem_map (option.map f) -- The converse is not true without additional assumptions theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h, (this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _), begin intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try {cases this}; try {contradiction}, substs b' ss, simp at m ⊢, cases o with e IH, { simp [e] }, cases m with e m, { simp [e] }, exact or.imp_left or.inr (IH _ _ rfl m) }, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try { try {have := this.1}, contradiction }; subst ss, { apply or.inr, simp at m ⊢, cases IH s S rfl m with as ex, { exact ⟨s, or.inl rfl, as⟩ }, { rcases ex with ⟨s', sS, as⟩, exact ⟨s', or.inr sS, as⟩ } }, { apply or.inr, simp at m, rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩, exact ⟨s, by simp [sS], as⟩ }, { simp at m IH ⊢, apply IH _ _ rfl m } } end theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨t, tm, bt⟩ := exists_of_mem_join h, ⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩ theorem destruct_map (f : α → β) (s : wseq α) : destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) := begin apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧ c2 = computation.map (option.map (prod.map f (map f))) (destruct s)), { intros c1 c2 h, cases h with s h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp, exact ⟨s, rfl, rfl⟩ }, { exact ⟨s, rfl, rfl⟩ } end theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := ⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t, ⟨s1, s2, rfl, rfl, h1⟩, λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b; simp, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, exact ⟨h2 r, s, rfl, t, rfl, h⟩ } end end⟩ theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t := lift_rel_map _ _ h (λ _ _, congr_arg _) @[simp] def destruct_append.aux (t : wseq α) : option (α × wseq α) → computation (option (α × wseq α)) | none := destruct t | (some (a, s)) := return (some (a, append s t)) theorem destruct_append (s t : wseq α) : destruct (append s t) = (destruct s).bind (destruct_append.aux t) := begin apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩, intros c1 c2 h, rcases h with ⟨s, t, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp, { apply t.cases_on _ (λ b t, _) (λ t, _); simp, { refine ⟨nil, t, _, _⟩; simp } }, { exact ⟨s, t, rfl, rfl⟩ } end @[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α)) | none := return none | (some (s, S)) := (destruct (append s (join S))).think theorem destruct_join (S : wseq (wseq α)) : destruct (join S) = (destruct S).bind destruct_join.aux := begin apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, or.inr ⟨S, rfl, rfl⟩ := begin apply S.cases_on _ (λ s S, _) (λ S, _); simp, { refine or.inr ⟨S, rfl, rfl⟩ } end end end theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β} (h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) : lift_rel R (append s1 s2) (append t1 t2) := ⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1, or.inr ⟨s1, t1, rfl, rfl, h1⟩, λ s t h, match s, t, h with | s, t, or.inl h := begin apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end | ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin simp [destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b, { simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl }, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ } end end⟩ theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop} (ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) : ∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b := begin cases exists_results_of_mem ma with n h, clear ma, revert a S T, apply nat.strong_induction_on n _, intros n IH a S T ST ra, simp [destruct_join] at ra, exact let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra, ⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in by exact match o, p, rop, rs1, rs2, mT with | none, none, _, rs1, rs2, mT := by simp only [destruct_join]; exact ⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩ | some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT := by simp [destruct_append] at rs2; exact let ⟨k1, rs3, ek⟩ := of_results_think rs2, ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3, ⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in by exact match o', p', rop', rs4, rs5, mt with | none, none, _, rs4, rs5', mt := have n1 < n, begin rw [en, ek, ek1], apply lt_of_lt_of_le _ (nat.le_add_right _ _), apply nat.lt_succ_of_le (nat.le_add_right _ _) end, let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩; { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, exact mb } | some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin simp at rs5, refine ⟨some (b, append t' (join T')), _, _⟩, { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, apply ret_mem }, rw eq_of_ret_mem rs5.mem, exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩ end end end end theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)} (h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) := ⟨λ s1 s2, ∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T, ⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin clear _fun_match _x, rw [h1, h2], rw [destruct_append, destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct st), exact λ o p h, match o, p, h with | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩ | none, none, _ := begin dsimp [destruct_append.aux, computation.lift_rel], constructor, { intro, apply lift_rel_join.lem _ ST (λ _ _, id) }, { intros b mb, rw [←lift_rel_o.swap], apply lift_rel_join.lem (swap R), { rw [←lift_rel.swap R, ←lift_rel.swap], apply ST }, { rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)], exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, ⟨t, s, T, S, h2, h1, st, ST⟩ }, { exact mb } } end end end⟩ theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T := lift_rel_join _ h theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → wseq γ} {f2 : β → wseq δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := lift_rel_join _ (lift_rel_map _ _ h1 @h2) theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2) @[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s := by simp [ret]; apply think_equiv @[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s := begin refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩, intros s' s h, rw ←h, apply lift_rel_rec (λ c1 c2, ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s), { exact λ c1 c2 h, match c1, c2, h with | ._, ._, ⟨s, rfl, rfl⟩ := begin clear h _match, have : ∀ s, ∃ s' : wseq α, (map ret s).join.destruct = (map ret s').join.destruct ∧ destruct s = s'.destruct, from λ s, ⟨s, rfl, rfl⟩, apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret, ret_mem, this, option.exists] end end }, { exact ⟨s, rfl, rfl⟩ } end @[simp] theorem join_append (S T : wseq (wseq α)) : join (append S T) ~ append (join S) (join T) := begin refine ⟨λ s1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T, c1 = destruct (append s (join (append S T))) ∧ c2 = destruct (append s (append (join S) (join T)))) _ _ _ (let ⟨s, S, T, h1, h2⟩ := h in ⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp, { refine ⟨s, nil, T, _, _⟩; simp }, { refine ⟨nil, nil, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { refine ⟨nil, S, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { exact ⟨s, S, T, rfl, rfl⟩ } end end end @[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s := begin dsimp [bind], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], apply join_map_ret end @[simp] theorem ret_bind (a : α) (f : α → wseq β) : bind (ret a) f ~ f a := by simp [bind] @[simp] theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := begin apply seq.eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { exact ⟨map f s, S, rfl, rfl⟩ }, { refine ⟨nil, S, _, _⟩; simp } }, { exact ⟨_, _, rfl, rfl⟩ }, { exact ⟨_, _, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem join_join (SS : wseq (wseq (wseq α))) : join (join SS) ~ join (map join SS) := begin refine ⟨λ s1 s2, ∃ s S SS, s1 = append s (join (append S (join SS))) ∧ s2 = append s (append (join S) (join (map join SS))), ⟨nil, nil, SS, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ s S SS, c1 = destruct (append s (join (append S (join SS)))) ∧ c2 = destruct (append s (append (join S) (join (map join SS))))) _ (destruct s1) (destruct s2) (let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp, { refine ⟨nil, S, SS, _, _⟩; simp }, { refine ⟨nil, nil, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { refine ⟨nil, S, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { exact ⟨s, S, SS, rfl, rfl⟩ } end end end @[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) : bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) := begin simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join], apply join_join end instance : monad wseq := { map := @map, pure := @ret, bind := @bind } /- Unfortunately, wseq is not a lawful monad, because it does not satisfy the monad laws exactly, only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient, because the join operation involves lists of quotient elements, with a lifted equivalence relation, and pure quotients cannot handle this type of construction. instance : is_lawful_monad wseq := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end wseq
7bdb85d7dc4773e84e26155d701b6a6c53f54958
4fa161becb8ce7378a709f5992a594764699e268
/src/topology/continuous_on.lean
6b8ebb96b9f29a84fc14c166c8388329b2a71801
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
25,138
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions `nhds_within` of `nhds` `continuous_on` of `continuous` `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] /-- The "neighborhood within" filter. Elements of `nhds_within a s` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ principal s theorem nhds_within_eq (a : α) (s : set α) : nhds_within a s = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, principal (t ∩ s) := have set.univ ∈ {s : set α | a ∈ s ∧ is_open s}, from ⟨set.mem_univ _, is_open_univ⟩, begin rw [nhds_within, nhds, binfi_inf]; try { exact this }, simp only [inf_principal] end theorem nhds_within_univ (a : α) : nhds_within a set.univ = 𝓝 a := by rw [nhds_within, principal_univ, inf_top_eq] lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s) (t : set α) : (nhds_within a t).has_basis p (λ i, s i ∩ t) := h.inf_principal t lemma nhds_within_basis_open (a : α) (t : set α) : (nhds_within a t).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) := nhds_within_has_basis (nhds_basis_opens a) t theorem mem_nhds_within {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := by simpa only [exists_prop, and_assoc, and_comm] using (nhds_within_basis_open a s).mem_iff lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := (nhds_within_has_basis (𝓝 a).basis_sets s).mem_iff lemma nhds_of_nhds_within_of_nhds {s t : set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ nhds_within a s) : (t ∈ 𝓝 a) := begin rcases mem_nhds_within_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩, exact (nhds a).sets_of_superset ((nhds a).inter_sets Hw h1) hw, end lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ nhds_within a t := mem_inf_sets_of_left h theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ nhds_within a s := mem_inf_sets_of_right (mem_principal_self s) theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ nhds_within a s := inter_mem_sets (mem_inf_sets_of_right (mem_principal_self s)) (mem_inf_sets_of_left h) theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : nhds_within a s ≤ nhds_within a t := inf_le_inf_left _ (principal_mono.mpr h) lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ nhds_within a s) : a ∈ t := let ⟨u, hu, H⟩ := mem_nhds_within.1 ht in H.2 ⟨H.1, ha⟩ lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α} (h : ∀ᶠ y in nhds_within x s, p y) (hx : x ∈ s) : p x := mem_of_mem_nhds_within hx h theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ nhds_within a s) : nhds_within a s = nhds_within a (s ∩ t) := le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem_sets self_mem_nhds_within h))) (inf_le_inf_left _ (principal_mono.mpr (set.inter_subset_left _ _))) theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict'' s $ mem_inf_sets_of_left h theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict' s (mem_nhds_sets h₁ h₀) theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ nhds_within a t) : nhds_within a t ≤ nhds_within a s := begin rcases mem_nhds_within.1 h with ⟨u, u_open, au, uts⟩, have : nhds_within a t = nhds_within a (t ∩ u) := nhds_within_restrict _ au u_open, rw [this, inter_comm], exact nhds_within_mono _ uts end theorem nhds_within_eq_nhds_within {a : α} {s t u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : nhds_within a t = nhds_within a u := by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂] theorem nhds_within_eq_of_open {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) : nhds_within a s = 𝓝 a := by rw [←nhds_within_univ]; apply nhds_within_eq_nhds_within h₀ h₁; rw [set.univ_inter, set.inter_self] @[simp] theorem nhds_within_empty (a : α) : nhds_within a {} = ⊥ := by rw [nhds_within, principal_empty, inf_bot_eq] theorem nhds_within_union (a : α) (s t : set α) : nhds_within a (s ∪ t) = nhds_within a s ⊔ nhds_within a t := by unfold nhds_within; rw [←inf_sup_left, sup_principal] theorem nhds_within_inter (a : α) (s t : set α) : nhds_within a (s ∩ t) = nhds_within a s ⊓ nhds_within a t := by unfold nhds_within; rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] theorem nhds_within_inter' (a : α) (s t : set α) : nhds_within a (s ∩ t) = (nhds_within a s) ⊓ principal t := by { unfold nhds_within, rw [←inf_principal, inf_assoc] } lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : nhds_within (a, b) (s.prod t) = (nhds_within a s).prod (nhds_within b t) := by { unfold nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] } theorem tendsto_if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (nhds_within a (s ∩ p)) l) (h₁ : tendsto g (nhds_within a (s ∩ {x | ¬ p x})) l) : tendsto (λ x, if p x then f x else g x) (nhds_within a s) l := by apply tendsto_if; rw [←nhds_within_inter']; assumption lemma map_nhds_within (f : α → β) (a : α) (s : set α) : map f (nhds_within a s) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, principal (set.image f (t ∩ s)) := ((nhds_within_basis_open a s).map f).eq_binfi theorem tendsto_nhds_within_mono_left {f : α → β} {a : α} {s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (nhds_within a t) l) : tendsto f (nhds_within a s) l := tendsto_le_left (nhds_within_mono a hst) h theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β} {a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (nhds_within a s)) : tendsto f l (nhds_within a t) := tendsto_le_right (nhds_within_mono a hst) h theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α} {s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) : tendsto f (nhds_within a s) l := by rw [←nhds_within_univ] at h; exact tendsto_nhds_within_mono_left (set.subset_univ _) h theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) : principal t = comap subtype.val (principal (subtype.val '' t)) := by rw comap_principal; rw set.preimage_image_eq; apply subtype.val_injective lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ nhds_within x s ≠ ⊥ := mem_closure_iff_nhds.trans (nhds_within_has_basis (𝓝 x).basis_sets s).forall_nonempty_iff_ne_bot lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) : nhds_within x s ≠ ⊥ := mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s) {x : α} (hx : nhds_within x s ≠ ⊥) : x ∈ s := by simpa only [closure_eq_of_is_closed hs] using mem_closure_iff_nhds_within_ne_bot.2 hx /- nhds_within and subtypes -/ theorem mem_nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t u : set {x // x ∈ s}) : t ∈ nhds_within a u ↔ t ∈ comap (@subtype.val _ s) (nhds_within a.val (subtype.val '' u)) := by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within] theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : nhds_within a t = comap (@subtype.val _ s) (nhds_within a.val (subtype.val '' t)) := filter_eq $ by ext u; rw mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_val {s : set α} {a : α} (h : a ∈ s) : nhds_within a s = map subtype.val (𝓝 ⟨a, h⟩) := have h₀ : s ∈ nhds_within a s, by { rw [mem_nhds_within], existsi set.univ, simp [set.diff_eq] }, have h₁ : ∀ y ∈ s, ∃ x, @subtype.val _ s x = y, from λ y h, ⟨⟨y, h⟩, rfl⟩, begin rw [←nhds_within_univ, nhds_within_subtype, subtype.val_image_univ], exact (map_comap_of_surjective' h₀ h₁).symm, end theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : tendsto f (nhds_within a s) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by { simp only [tendsto, nhds_within_eq_map_subtype_val h, filter.map_map], refl } variables [topological_space β] [topological_space γ] [topological_space δ] /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop := tendsto f (nhds_within x s) (𝓝 (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (𝓝 (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s) (hx : x ∈ s) : continuous_within_at f s x := hf x hx theorem continuous_within_at_univ (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := by rw [continuous_at, continuous_within_at, nhds_within_univ] theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ := tendsto_nhds_within_iff_subtype h f _ theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (nhds_within (f x) (f '' s)) := tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_sets_of_right $ mem_principal_sets.2 $ λ x, mem_image_of_mem _⟩ lemma continuous_within_at.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} {x : α} {y : β} (hf : continuous_within_at f s x) (hg : continuous_within_at g t y) : continuous_within_at (prod.map f g) (s.prod t) (x, y) := begin unfold continuous_within_at at *, rw [nhds_within_prod_eq, prod.map, nhds_prod_eq], exact hf.prod_map hg, end theorem continuous_on_iff {f : α → β} {s : set α} : continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within] theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} : continuous_on f s ↔ continuous (s.restrict f) := begin rw [continuous_on, continuous_iff_continuous_at], split, { rintros h ⟨x, xs⟩, exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) }, intros h x xs, exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩) end theorem continuous_on_iff' {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp], simp only [preimage_coe_eq_preimage_coe_iff], split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ } end, by rw [continuous_on_iff_continuous_restrict, continuous]; simp only [this] theorem continuous_on_iff_is_closed {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp], simp only [preimage_coe_eq_preimage_coe_iff] end, by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this] lemma continuous_on.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} (hf : continuous_on f s) (hg : continuous_on g t) : continuous_on (prod.map f g) (s.prod t) := λ ⟨x, y⟩ ⟨hx, hy⟩, continuous_within_at.prod_map (hf x hx) (hg y hy) lemma continuous_on_empty (f : α → β) : continuous_on f ∅ := λ x, false.elim theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : nhds_within x s ≤ comap f (nhds_within (f x) (f '' s)) := map_le_iff_le_comap.1 ctsf.tendsto_nhds_within_image theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _ lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ := by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at, nhds_within_univ] lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := tendsto_le_left (nhds_within_mono x hs) h lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ nhds_within x s) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict'' s h] lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict' s h] lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α} (hs : continuous_within_at f s x) (ht : continuous_within_at f t x) : continuous_within_at f (s ∪ t) x := by simp only [continuous_within_at, nhds_within_union, tendsto, map_sup, sup_le_iff.2 ⟨hs, ht⟩] lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_tendsto (mem_closure_iff_nhds_within_ne_bot.1 hx) h $ mem_sets_of_superset self_mem_nhds_within (subset_preimage_image f s) lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f⁻¹' A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) lemma continuous_within_at.image_closure {f : α → β} {s : set α} (hf : ∀ x ∈ closure s, continuous_within_at f s x) : f '' (closure s) ⊆ closure (f '' s) := begin rintros _ ⟨x, hx, rfl⟩, exact (hf x hx).mem_closure_image hx end theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α} (h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) : continuous_on finv (f '' s) := begin rintros _ ⟨x, xs, rfl⟩ t ht, rw [hleft xs] at ht, replace h := h.nhds_le ⟨x, xs⟩, apply mem_nhds_within_of_mem_nhds, apply h, erw [map_compose.symm, function.comp, mem_map, ← nhds_within_eq_map_subtype_val], apply mem_sets_of_superset (inter_mem_nhds_within _ ht), assume y hy, rw [mem_set_of_eq, mem_preimage, hleft hy.1], exact hy.2 end theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (range f) := begin rw [← image_univ], exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x) end lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s) (h' : ∀x ∈ s₁, g x = f x) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := begin assume x hx, unfold continuous_within_at, have A := (h x (h₁ hx)).mono h₁, unfold continuous_within_at at A, rw ← h' x hx at A, have : {x : α | g x = f x} ∈ nhds_within x s₁ := mem_inf_sets_of_right h', apply tendsto.congr' _ A, convert this, ext, finish end lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : ∀x ∈ s, g x = f x) : continuous_on g s := h.congr_mono h' (subset.refl _) lemma continuous_on_congr {f g : α → β} {s : set α} (h' : ∀x ∈ s, g x = f x) : continuous_on g s ↔ continuous_on f s := ⟨λ h, continuous_on.congr h (λx hx, (h' x hx).symm), λ h, continuous_on.congr h h'⟩ lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _) lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, continuous_within_at_inter hs, continuous_within_at_univ] at h end lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x := (h x (mem_of_nhds hx)).continuous_at hx lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) : continuous_within_at (g ∘ f) s x := begin have : tendsto f (principal s) (principal t), by { rw tendsto_principal_principal, exact λx hx, h hx }, have : tendsto f (nhds_within x s) (principal t) := tendsto_le_left inf_le_right this, have : tendsto f (nhds_within x s) (nhds_within (f x) t) := tendsto_inf.2 ⟨hf, this⟩, exact tendsto.comp hg this end lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) : continuous_on (g ∘ f) s := λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := λx hx, tendsto_le_left (nhds_within_mono _ h) (hf x (h hx)) lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := begin rw continuous_iff_continuous_on_univ at h, exact h.mono (subset_univ _) end lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := tendsto_le_left inf_le_left (h.tendsto x) lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := hg.continuous_on.comp hf subset_preimage_univ lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ nhds_within x s := h ht lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ nhds_within (f x) (f '' s)) : f ⁻¹' t ∈ nhds_within x s := begin rw mem_nhds_within at ht, rcases ht with ⟨u, u_open, fxu, hu⟩, have : f ⁻¹' u ∩ s ∈ nhds_within x s := filter.inter_mem_sets (h (mem_nhds_sets u_open fxu)) self_mem_nhds_within, apply mem_sets_of_superset this, calc f ⁻¹' u ∩ s ⊆ f ⁻¹' u ∩ f ⁻¹' (f '' s) : inter_subset_inter_right _ (subset_preimage_image f s) ... = f ⁻¹' (u ∩ f '' s) : rfl ... ⊆ f ⁻¹' t : preimage_mono hu end lemma continuous_within_at.congr_of_mem_nhds_within {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : continuous_within_at f₁ s x := by rwa [continuous_within_at, filter.tendsto, hx, filter.map_cong h₁] lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := h.congr_of_mem_nhds_within (mem_sets_of_superset self_mem_nhds_within h₁) hx lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s := continuous_const.continuous_on lemma continuous_within_at_const {b : β} {s : set α} {x : α} : continuous_within_at (λ _:α, b) s x := continuous_const.continuous_within_at lemma continuous_on_id {s : set α} : continuous_on id s := continuous_id.continuous_on lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x := continuous_id.continuous_within_at lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) := begin rw continuous_on_iff', split, { assume h t ht, rcases h t ht with ⟨u, u_open, hu⟩, rw [inter_comm, hu], apply is_open_inter u_open hs }, { assume h t ht, refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩, rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] } end lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) := (continuous_on_open_iff hs).1 hf t ht lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) := begin rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩, rw [inter_comm, hu.2], apply is_closed_inter hu.1 hs end lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) := calc s ∩ f ⁻¹' (interior t) ⊆ interior (s ∩ f ⁻¹' t) : interior_maximal (inter_subset_inter (subset.refl _) (preimage_mono interior_subset)) (hf.preimage_open_of_open hs is_open_interior) ... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, interior_eq_of_open hs] lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α} (h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := begin assume x xs, rcases h x xs with ⟨t, open_t, xt, ct⟩, have := ct x ⟨xs, xt⟩, rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this end lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) : @continuous_on α β _ (topological_space.generate_from T) f s := begin rw continuous_on_open_iff, assume t ht, induction ht with u hu u v Tu Tv hu hv U hU hU', { exact h u hu }, { simp only [preimage_univ, inter_univ], exact hs }, { have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v), by { ext x, simp, split, finish, finish }, rw this, exact is_open_inter hu hv }, { rw [preimage_sUnion, inter_bUnion], exact is_open_bUnion hU' }, { exact hs } end lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, (f x, g x)) s x := hf.prod_mk_nhds hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx)
85978bb1bf522a977569841bdebcdd25042dd8d7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/new_compiler.lean
152f1bfb1e1ee17d757ee2ad95fc4ccf714ea703
[ "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,712
lean
universe u v w r s set_option trace.compiler.stage1 true -- set_option pp.explicit true -- set_option pp.proofs true def foo (n : Nat) : Nat := let x := Nat.zero; let x1 := Nat.succ x; let x2 := Nat.succ x1; let x3 := Nat.succ x2; let x4 := Nat.succ x3; let x5 := Nat.succ x4; let x6 := Nat.succ x5; let x7 := Nat.succ x ; let x8 := Nat.succ x7; let y1 := x; let y2 := y1; y2 + n def cseTst (n : Nat) : Nat := let y := Nat.succ ((fun x => x) n); let z := Nat.succ n; y + z def tst1 (n : Nat) : Nat := let p := (Nat.succ n, n); let q := (p, p); match q with | ((z, w), y) => z def tst2 (n : Nat) : Nat := let p := (fun x => Nat.succ x, Nat.zero) ; let f := fun (p : (Nat → Nat) × Nat) => p.1; f p n partial def add' : Nat → Nat → Nat | 0, b => Nat.succ b | a+1, b => Nat.succ (Nat.succ (add' a b)) def aux (i : Nat) (h : i > 0) := i axiom bad (α : Sort u) : α unsafe def foo2 : Nat := @False.rec (fun _ => Nat) (bad _) set_option pp.notation false def foo3 (n : Nat) : Nat := (fun (a : Nat) => a + a + a) (n*n) def boo (a : Nat) (l : List Nat) : List Nat := let f := @List.cons Nat; f a (f a l) def bla (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat := @And.rec _ _ (fun _ => Nat) (fun h₁ h₂ => aux i h₁ + aux i h₁) h def bla' (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat := @And.casesOn _ _ (fun _ => Nat) h (fun h₁ h₂ => aux i h₁ + aux i h₁) inductive vec (α : Type u) : Nat → Type u | nil : vec α 0 | cons : ∀ {n}, α → vec α n → vec α (Nat.succ n) /- def vec.map {α β σ : Type u} (f : α → β → σ) : ∀ {n : Nat}, vec α n → vec β n → vec σ n | _, nil, nil => nil | _, cons a as, cons b bs => cons (f a b) (map f as bs) -/
0a7115e59f934ee2750537da289df7bcf7e8b67d
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/init/num.hlean
a3eed88bcd009ef4091f4856e1378ad0bf454731
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,818
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.bool open bool definition pos_num.is_inhabited [instance] : inhabited pos_num := inhabited.mk pos_num.one namespace pos_num definition succ (a : pos_num) : pos_num := rec_on a (bit0 one) (λn r, bit0 r) (λn r, bit1 n) definition is_one (a : pos_num) : bool := rec_on a tt (λn r, ff) (λn r, ff) definition pred (a : pos_num) : pos_num := rec_on a one (λn r, bit0 n) (λn r, cond (is_one n) one (bit1 r)) definition size (a : pos_num) : pos_num := rec_on a one (λn r, succ r) (λn r, succ r) definition add (a b : pos_num) : pos_num := rec_on a succ (λn f b, rec_on b (succ (bit1 n)) (λm r, succ (bit1 (f m))) (λm r, bit1 (f m))) (λn f b, rec_on b (bit1 n) (λm r, bit1 (f m)) (λm r, bit0 (f m))) b notation a + b := add a b definition mul (a b : pos_num) : pos_num := rec_on a b (λn r, bit0 r + b) (λn r, bit0 r) notation a * b := mul a b end pos_num definition num.is_inhabited [instance] : inhabited num := inhabited.mk num.zero namespace num open pos_num definition succ (a : num) : num := rec_on a (pos one) (λp, pos (succ p)) definition pred (a : num) : num := rec_on a zero (λp, cond (is_one p) zero (pos (pred p))) definition size (a : num) : num := rec_on a (pos one) (λp, pos (size p)) definition add (a b : num) : num := rec_on a b (λp_a, rec_on b (pos p_a) (λp_b, pos (pos_num.add p_a p_b))) definition mul (a b : num) : num := rec_on a zero (λp_a, rec_on b zero (λp_b, pos (pos_num.mul p_a p_b))) notation a + b := add a b notation a * b := mul a b end num
fb790cce91f5d1e709a8af17ccf8d5abad69d56b
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/homeomorph.lean
3d0ef7172be6cc97f168c41fc07586e63102c161
[ "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
23,704
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton -/ import logic.equiv.fin import topology.dense_embedding import topology.support /-! # Homeomorphisms This file defines homeomorphisms between two topological spaces. They are bijections with both directions continuous. We denote homeomorphisms with the notation `≃ₜ`. # Main definitions * `homeomorph α β`: The type of homeomorphisms from `α` to `β`. This type can be denoted using the following notation: `α ≃ₜ β`. # Main results * Pretty much every topological property is preserved under homeomorphisms. * `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is an open map is a homeomorphism. -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Homeomorphism between `α` and `β`, also called topological isomorphism -/ @[nolint has_nonempty_instance] -- not all spaces are homeomorphic to each other structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends α ≃ β := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') infix ` ≃ₜ `:25 := homeomorph namespace homeomorph variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : has_coe_to_fun (α ≃ₜ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩ @[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) : ((homeomorph.mk a b c) : α → β) = a := rfl /-- Inverse of a homeomorphism. -/ protected def symm (h : α ≃ₜ β) : β ≃ₜ α := { continuous_to_fun := h.continuous_inv_fun, continuous_inv_fun := h.continuous_to_fun, to_equiv := h.to_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : α ≃ₜ β) : α → β := h /-- See Note [custom simps projection] -/ def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm initialize_simps_projections homeomorph (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv) @[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl @[simp] lemma coe_symm_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv.symm = h.symm := rfl lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β) | ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl @[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' := to_equiv_injective $ equiv.ext H /-- Identity map as a homeomorphism. -/ @[simps apply {fully_applied := ff}] protected def refl (α : Type*) [topological_space α] : α ≃ₜ α := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, to_equiv := equiv.refl α } /-- Composition of two homeomorphisms. -/ protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ := { continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun, continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun, to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv } @[simp] lemma trans_apply (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl @[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) : ((homeomorph.mk a b c).symm : β → α) = a.symm := rfl @[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl @[continuity] protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun @[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm` protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun @[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x := h.to_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x := h.to_equiv.symm_apply_apply x @[simp] lemma self_trans_symm (h : α ≃ₜ β) : h.trans h.symm = homeomorph.refl α := by { ext, apply symm_apply_apply } @[simp] lemma symm_trans_self (h : α ≃ₜ β) : h.symm.trans h = homeomorph.refl β := by { ext, apply apply_symm_apply } protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective /-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/ def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β := have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm ... = f.symm x : by rw hg x), { to_fun := f, inv_fun := g, left_inv := by convert f.left_inv, right_inv := by convert f.right_inv, continuous_to_fun := f.continuous, continuous_inv_fun := by convert f.symm.continuous } @[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id := funext h.symm_apply_apply @[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id := funext h.apply_symm_apply @[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ := h.surjective.range_eq lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h := funext h.symm.to_equiv.image_eq_preimage lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h := (funext h.to_equiv.image_eq_preimage).symm @[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s := h.to_equiv.image_preimage s @[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s := h.to_equiv.preimage_image s protected lemma inducing (h : α ≃ₜ β) : inducing h := inducing_of_inducing_compose h.continuous h.symm.continuous $ by simp only [symm_comp_self, inducing_id] lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h := quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $ by simp only [self_comp_symm, quotient_map.id] lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› := h.quotient_map.2.symm protected lemma embedding (h : α ≃ₜ β) : embedding h := ⟨h.inducing, h.injective⟩ /-- Homeomorphism given an embedding. -/ noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) := { continuous_to_fun := hf.continuous.subtype_mk _, continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe], to_equiv := equiv.of_injective f hf.inj } protected lemma second_countable_topology [topological_space.second_countable_topology β] (h : α ≃ₜ β) : topological_space.second_countable_topology α := h.inducing.second_countable_topology lemma is_compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s := h.embedding.is_compact_iff_is_compact_image.symm lemma is_compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s := by rw ← image_symm; exact h.symm.is_compact_image @[simp] lemma comap_cocompact (h : α ≃ₜ β) : comap h (cocompact β) = cocompact α := (comap_cocompact_le h.continuous).antisymm $ (has_basis_cocompact.le_basis_iff (has_basis_cocompact.comap h)).2 $ λ K hK, ⟨h ⁻¹' K, h.is_compact_preimage.2 hK, subset.rfl⟩ @[simp] lemma map_cocompact (h : α ≃ₜ β) : map h (cocompact α) = cocompact β := by rw [← h.comap_cocompact, map_comap_of_surjective h.surjective] protected lemma compact_space [compact_space α] (h : α ≃ₜ β) : compact_space β := { is_compact_univ := by { rw [← image_univ_of_surjective h.surjective, h.is_compact_image], apply compact_space.is_compact_univ } } protected lemma t0_space [t0_space α] (h : α ≃ₜ β) : t0_space β := h.symm.embedding.t0_space protected lemma t1_space [t1_space α] (h : α ≃ₜ β) : t1_space β := h.symm.embedding.t1_space protected lemma t2_space [t2_space α] (h : α ≃ₜ β) : t2_space β := h.symm.embedding.t2_space protected lemma t3_space [t3_space α] (h : α ≃ₜ β) : t3_space β := h.symm.embedding.t3_space protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h := { dense := h.surjective.dense_range, .. h.embedding } @[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s := h.quotient_map.is_open_preimage @[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s := by rw [← preimage_symm, is_open_preimage] protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2 @[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s := by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage] @[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s := by rw [← preimage_symm, is_closed_preimage] protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2 protected lemma open_embedding (h : α ≃ₜ β) : open_embedding h := open_embedding_of_embedding_open h.embedding h.is_open_map protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h := closed_embedding_of_embedding_closed h.embedding h.is_closed_map protected lemma normal_space [normal_space α] (h : α ≃ₜ β) : normal_space β := h.symm.closed_embedding.normal_space lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) := h.is_open_map.preimage_closure_eq_closure_preimage h.continuous _ lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) := by rw [← preimage_symm, preimage_closure] lemma preimage_interior (h : α ≃ₜ β) (s : set β) : h⁻¹' (interior s) = interior (h ⁻¹' s) := h.is_open_map.preimage_interior_eq_interior_preimage h.continuous _ lemma image_interior (h : α ≃ₜ β) (s : set α) : h '' (interior s) = interior (h '' s) := by rw [← preimage_symm, preimage_interior] lemma preimage_frontier (h : α ≃ₜ β) (s : set β) : h ⁻¹' (frontier s) = frontier (h ⁻¹' s) := h.is_open_map.preimage_frontier_eq_frontier_preimage h.continuous _ lemma image_frontier (h : α ≃ₜ β) (s : set α) : h '' frontier s = frontier (h '' s) := by rw [←preimage_symm, preimage_frontier] @[to_additive] lemma _root_.has_compact_mul_support.comp_homeomorph {M} [has_one M] {f : β → M} (hf : has_compact_mul_support f) (φ : α ≃ₜ β) : has_compact_mul_support (f ∘ φ) := hf.comp_closed_embedding φ.closed_embedding @[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) := h.embedding.map_nhds_of_mem _ (by simp) lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x := by rw [h.symm.map_nhds_eq, h.symm_apply_apply] lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) := h.embedding.to_inducing.nhds_eq_comap x @[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) := by rw [h.nhds_eq_comap, h.apply_symm_apply] /-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/ def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) : α ≃ₜ β := { continuous_to_fun := h₁, continuous_inv_fun := begin rw continuous_def, intros s hs, convert ← h₂ s hs using 1, apply e.image_eq_preimage end, to_equiv := e } @[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) : continuous_on (h ∘ f) s ↔ continuous_on f s := h.inducing.continuous_on_iff.symm @[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} : continuous (h ∘ f) ↔ continuous f := h.inducing.continuous_iff.symm @[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} : continuous (f ∘ h) ↔ continuous f := h.quotient_map.continuous_iff.symm lemma comp_continuous_at_iff (h : α ≃ₜ β) (f : γ → α) (x : γ) : continuous_at (h ∘ f) x ↔ continuous_at f x := h.inducing.continuous_at_iff.symm lemma comp_continuous_at_iff' (h : α ≃ₜ β) (f : β → γ) (x : α) : continuous_at (f ∘ h) x ↔ continuous_at f (h x) := h.inducing.continuous_at_iff' (by simp) lemma comp_continuous_within_at_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) (x : γ) : continuous_within_at f s x ↔ continuous_within_at (h ∘ f) s x := h.inducing.continuous_within_at_iff @[simp] lemma comp_is_open_map_iff (h : α ≃ₜ β) {f : γ → α} : is_open_map (h ∘ f) ↔ is_open_map f := begin refine ⟨_, λ hf, h.is_open_map.comp hf⟩, intros hf, rw [← function.comp.left_id f, ← h.symm_comp_self, function.comp.assoc], exact h.symm.is_open_map.comp hf, end @[simp] lemma comp_is_open_map_iff' (h : α ≃ₜ β) {f : β → γ} : is_open_map (f ∘ h) ↔ is_open_map f := begin refine ⟨_, λ hf, hf.comp h.is_open_map⟩, intros hf, rw [← function.comp.right_id f, ← h.self_comp_symm, ← function.comp.assoc], exact hf.comp h.symm.is_open_map, end /-- If two sets are equal, then they are homeomorphic. -/ def set_congr {s t : set α} (h : s = t) : s ≃ₜ t := { continuous_to_fun := continuous_inclusion h.subset, continuous_inv_fun := continuous_inclusion h.symm.subset, to_equiv := equiv.set_congr h } /-- Sum of two homeomorphisms. -/ def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ := { continuous_to_fun := h₁.continuous.sum_map h₂.continuous, continuous_inv_fun := h₁.symm.continuous.sum_map h₂.symm.continuous, to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv } /-- Product of two homeomorphisms. -/ def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ := { continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk (h₂.continuous.comp continuous_snd), continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk (h₂.symm.continuous.comp continuous_snd), to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv } @[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : (h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl @[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : ⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl section variables (α β γ) /-- `α × β` is homeomorphic to `β × α`. -/ def prod_comm : α × β ≃ₜ β × α := { continuous_to_fun := continuous_snd.prod_mk continuous_fst, continuous_inv_fun := continuous_snd.prod_mk continuous_fst, to_equiv := equiv.prod_comm α β } @[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl @[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl /-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/ def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) := { continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk ((continuous_snd.comp continuous_fst).prod_mk continuous_snd), continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk (continuous_snd.comp continuous_snd), to_equiv := equiv.prod_assoc α β γ } /-- `α × {*}` is homeomorphic to `α`. -/ @[simps apply {fully_applied := ff}] def prod_punit : α × punit ≃ₜ α := { to_equiv := equiv.prod_punit α, continuous_to_fun := continuous_fst, continuous_inv_fun := continuous_id.prod_mk continuous_const } /-- `{*} × α` is homeomorphic to `α`. -/ def punit_prod : punit × α ≃ₜ α := (prod_comm _ _).trans (prod_punit _) @[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl /-- If both `α` and `β` have a unique element, then `α ≃ₜ β`. -/ @[simps] def _root_.homeomorph.homeomorph_of_unique [unique α] [unique β] : α ≃ₜ β := { continuous_to_fun := @continuous_const α β _ _ default, continuous_inv_fun := @continuous_const β α _ _ default, .. equiv.equiv_of_unique α β } end /-- If each `β₁ i` is homeomorphic to `β₂ i`, then `Π i, β₁ i` is homeomorphic to `Π i, β₂ i`. -/ @[simps apply to_equiv] def Pi_congr_right {ι : Type*} {β₁ β₂ : ι → Type*} [Π i, topological_space (β₁ i)] [Π i, topological_space (β₂ i)] (F : Π i, β₁ i ≃ₜ β₂ i) : (Π i, β₁ i) ≃ₜ (Π i, β₂ i) := { continuous_to_fun := continuous_pi (λ i, (F i).continuous.comp $ continuous_apply i), continuous_inv_fun := continuous_pi (λ i, (F i).symm.continuous.comp $ continuous_apply i), to_equiv := equiv.Pi_congr_right (λ i, (F i).to_equiv) } @[simp] lemma Pi_congr_right_symm {ι : Type*} {β₁ β₂ : ι → Type*} [Π i, topological_space (β₁ i)] [Π i, topological_space (β₂ i)] (F : Π i, β₁ i ≃ₜ β₂ i) : (Pi_congr_right F).symm = Pi_congr_right (λ i, (F i).symm) := rfl /-- `ulift α` is homeomorphic to `α`. -/ def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α := { continuous_to_fun := continuous_ulift_down, continuous_inv_fun := continuous_ulift_up, to_equiv := equiv.ulift } section distrib /-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/ def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ := homeomorph.symm $ homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm ((continuous_inl.prod_map continuous_id).sum_elim (continuous_inr.prod_map continuous_id)) $ (is_open_map_inl.prod is_open_map.id).sum_elim (is_open_map_inr.prod is_open_map.id) /-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/ def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ := (prod_comm _ _).trans $ sum_prod_distrib.trans $ sum_congr (prod_comm _ _) (prod_comm _ _) variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] /-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/ def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) := homeomorph.symm $ homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm (continuous_sigma $ λ i, continuous_sigma_mk.fst'.prod_mk continuous_snd) (is_open_map_sigma.2 $ λ i, is_open_map_sigma_mk.prod is_open_map.id) end distrib /-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/ @[simps { fully_applied := ff }] def fun_unique (ι α : Type*) [unique ι] [topological_space α] : (ι → α) ≃ₜ α := { to_equiv := equiv.fun_unique ι α, continuous_to_fun := continuous_apply _, continuous_inv_fun := continuous_pi (λ _, continuous_id) } /-- Homeomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/ @[simps { fully_applied := ff }] def {u} pi_fin_two (α : fin 2 → Type u) [Π i, topological_space (α i)] : (Π i, α i) ≃ₜ α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, continuous_to_fun := (continuous_apply 0).prod_mk (continuous_apply 1), continuous_inv_fun := continuous_pi $ fin.forall_fin_two.2 ⟨continuous_fst, continuous_snd⟩ } /-- Homeomorphism between `α² = fin 2 → α` and `α × α`. -/ @[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ₜ α × α := { to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) } /-- A subset of a topological space is homeomorphic to its image under a homeomorphism. -/ @[simps] def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s := { continuous_to_fun := by continuity!, continuous_inv_fun := by continuity!, to_equiv := e.to_equiv.image s, } /-- `set.univ α` is homeomorphic to `α`. -/ @[simps { fully_applied := ff }] def set.univ (α : Type*) [topological_space α] : (univ : set α) ≃ₜ α := { to_equiv := equiv.set.univ α, continuous_to_fun := continuous_subtype_coe, continuous_inv_fun := continuous_id.subtype_mk _ } /-- `s ×ˢ t` is homeomorphic to `s × t`. -/ @[simps] def set.prod (s : set α) (t : set β) : ↥(s ×ˢ t) ≃ₜ s × t := { to_equiv := equiv.set.prod s t, continuous_to_fun := (continuous_subtype_coe.fst.subtype_mk _).prod_mk (continuous_subtype_coe.snd.subtype_mk _), continuous_inv_fun := (continuous_subtype_coe.fst'.prod_mk continuous_subtype_coe.snd').subtype_mk _ } section variable {ι : Type*} /-- The topological space `Π i, β i` can be split as a product by separating the indices in ι depending on whether they satisfy a predicate p or not.-/ @[simps] def pi_equiv_pi_subtype_prod (p : ι → Prop) (β : ι → Type*) [Π i, topological_space (β i)] [decidable_pred p] : (Π i, β i) ≃ₜ (Π i : {x // p x}, β i) × Π i : {x // ¬p x}, β i := { to_equiv := equiv.pi_equiv_pi_subtype_prod p β, continuous_to_fun := by apply continuous.prod_mk; exact continuous_pi (λ j, continuous_apply j), continuous_inv_fun := continuous_pi $ λ j, begin dsimp only [equiv.pi_equiv_pi_subtype_prod], split_ifs, exacts [(continuous_apply _).comp continuous_fst, (continuous_apply _).comp continuous_snd], end } variables [decidable_eq ι] (i : ι) /-- A product of topological spaces can be split as the binary product of one of the spaces and the product of all the remaining spaces. -/ @[simps] def pi_split_at (β : ι → Type*) [Π j, topological_space (β j)] : (Π j, β j) ≃ₜ β i × Π j : {j // j ≠ i}, β j := { to_equiv := equiv.pi_split_at i β, continuous_to_fun := (continuous_apply i).prod_mk (continuous_pi $ λ j, continuous_apply j), continuous_inv_fun := continuous_pi $ λ j, by { dsimp only [equiv.pi_split_at], split_ifs, subst h, exacts [continuous_fst, (continuous_apply _).comp continuous_snd] } } /-- A product of copies of a topological space can be split as the binary product of one copy and the product of all the remaining copies. -/ @[simps] def fun_split_at : (ι → β) ≃ₜ β × ({j // j ≠ i} → β) := pi_split_at i _ end end homeomorph /-- An inducing equiv between topological spaces is a homeomorphism. -/ @[simps] def equiv.to_homeomorph_of_inducing [topological_space α] [topological_space β] (f : α ≃ β) (hf : inducing f) : α ≃ₜ β := { continuous_to_fun := hf.continuous, continuous_inv_fun := hf.continuous_iff.2 $ by simpa using continuous_id, .. f } namespace continuous variables [topological_space α] [topological_space β] lemma continuous_symm_of_equiv_compact_to_t2 [compact_space α] [t2_space β] {f : α ≃ β} (hf : continuous f) : continuous f.symm := begin rw continuous_iff_is_closed, intros C hC, have hC' : is_closed (f '' C) := (hC.is_compact.image hf).is_closed, rwa equiv.image_eq_preimage at hC', end /-- Continuous equivalences from a compact space to a T2 space are homeomorphisms. This is not true when T2 is weakened to T1 (see `continuous.homeo_of_equiv_compact_to_t2.t1_counterexample`). -/ @[simps] def homeo_of_equiv_compact_to_t2 [compact_space α] [t2_space β] {f : α ≃ β} (hf : continuous f) : α ≃ₜ β := { continuous_to_fun := hf, continuous_inv_fun := hf.continuous_symm_of_equiv_compact_to_t2, ..f } end continuous
1cfe1858b65d5b592e638e3f39611da0df82c68d
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Compiler/IR.lean
8bb7108c5387617472c886484c0859c6cc224fec
[ "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
2,979
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.Basic import Lean.Compiler.IR.Format import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.PushProj import Lean.Compiler.IR.ElimDeadVars import Lean.Compiler.IR.SimpCase import Lean.Compiler.IR.ResetReuse import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.Checker import Lean.Compiler.IR.Borrow import Lean.Compiler.IR.Boxing import Lean.Compiler.IR.RC import Lean.Compiler.IR.ExpandResetReuse import Lean.Compiler.IR.UnboxResult import Lean.Compiler.IR.ElimDeadBranches import Lean.Compiler.IR.EmitC import Lean.Compiler.IR.EmitLLVM import Lean.Compiler.IR.CtorLayout import Lean.Compiler.IR.Sorry namespace Lean.IR register_builtin_option compiler.reuse : Bool := { defValue := true descr := "heuristically insert reset/reuse instruction pairs" } private def compileAux (decls : Array Decl) : CompilerM Unit := do logDecls `init decls checkDecls decls let mut decls ← elimDeadBranches decls logDecls `elim_dead_branches decls decls := decls.map Decl.pushProj logDecls `push_proj decls if compiler.reuse.get (← read) then decls := decls.map Decl.insertResetReuse logDecls `reset_reuse decls decls := decls.map Decl.elimDead logDecls `elim_dead decls decls := decls.map Decl.simpCase logDecls `simp_case decls decls := decls.map Decl.normalizeIds decls ← inferBorrow decls logDecls `borrow decls decls ← explicitBoxing decls logDecls `boxing decls decls ← explicitRC decls logDecls `rc decls if compiler.reuse.get (← read) then decls := decls.map Decl.expandResetReuse logDecls `expand_reset_reuse decls decls := decls.map Decl.pushProj logDecls `push_proj decls decls ← updateSorryDep decls logDecls `result decls checkDecls decls addDecls decls @[export lean_ir_compile] def compile (env : Environment) (opts : Options) (decls : Array Decl) : Log × (Except String Environment) := match (compileAux decls opts).run { env := env } with | EStateM.Result.ok _ s => (s.log, Except.ok s.env) | EStateM.Result.error msg s => (s.log, Except.error msg) def addBoxedVersionAux (decl : Decl) : CompilerM Unit := do let env ← getEnv if !ExplicitBoxing.requiresBoxedVersion env decl then pure () else let decl := ExplicitBoxing.mkBoxedVersion decl let decls : Array Decl := #[decl] let decls ← explicitRC decls decls.forM fun decl => modifyEnv fun env => addDeclAux env decl pure () -- Remark: we are ignoring the `Log` here. This should be fine. @[export lean_ir_add_boxed_version] def addBoxedVersion (env : Environment) (decl : Decl) : Except String Environment := match (addBoxedVersionAux decl Options.empty).run { env := env } with | EStateM.Result.ok _ s => Except.ok s.env | EStateM.Result.error msg _ => Except.error msg end Lean.IR
bde641f6594030836683ec395c680fbf4324722d
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/prod.lean
8295debdca5844a4432bbba4175af5a08dc0bf7e
[ "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
46,987
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.giry_monad import measure_theory.set_integral /-! # The product measure In this file we define and prove properties about the binary product measure. If `α` and `β` have σ-finite measures `μ` resp. `ν` then `α × β` can be equipped with a σ-finite measure `μ.prod ν` that satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`. We also have `(μ.prod ν) (s.prod t) = μ s * ν t`, i.e. the measure of a rectangle is the product of the measures of the sides. We also prove Tonelli's theorem and Fubini's theorem. ## Main definition * `measure_theory.measure.prod`: The product of two measures. ## Main results * `measure_theory.measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ` for measurable `s`. `measure_theory.measure.prod_apply_symm` is the reversed version. * `measure_theory.measure.prod_prod` states `μ.prod ν (s.prod t) = μ s * ν t` for measurable sets `s` and `t`. * `measure_theory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function `α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have a variant with `_symm` appended, where the order of integration is reversed. The lemma `measurable.lintegral_prod_right'` states that the inner integral of the right-hand side is measurable. * `measure_theory.integrable_prod_iff` states that a binary function is integrable iff both * `y ↦ f (x, y)` is integrable for almost every `x`, and * the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable. * `measure_theory.integral_prod`: Fubini's theorem. It states that for a integrable function `α × β → E` (where `E` is a second countable Banach space) we have `∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ`. This theorem has the same variants as Tonelli's theorem. The lemma `measure_theory.integrable.integral_prod_right` states that the inner integral of the right-hand side is integrable. ## Implementation Notes Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for functions in uncurried form (`α × β → γ`). The former often has an assumption `measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more common that the function has to be given explicitly, since Lean cannot synthesize the function by itself. We name the lemmas about the uncurried form with a prime. Tonelli's theorem and Fubini's theorem have a different naming scheme, since the version for the uncurried version is reversed. ## Tags product measure, Fubini's theorem, Tonelli's theorem, Fubini-Tonelli theorem -/ noncomputable theory open_locale classical topological_space ennreal measure_theory open set function real ennreal open measure_theory measurable_space measure_theory.measure open topological_space (hiding generate_from) open filter (hiding prod_eq map) variables {α α' β β' γ E : Type*} /-- Rectangles formed by π-systems form a π-system. -/ lemma is_pi_system.prod {C : set (set α)} {D : set (set β)} (hC : is_pi_system C) (hD : is_pi_system D) : is_pi_system (image2 set.prod C D) := begin rintro _ _ ⟨s₁, t₁, hs₁, ht₁, rfl⟩ ⟨s₂, t₂, hs₂, ht₂, rfl⟩ hst, rw [prod_inter_prod] at hst ⊢, rw [prod_nonempty_iff] at hst, exact mem_image2_of_mem (hC _ _ hs₁ hs₂ hst.1) (hD _ _ ht₁ ht₂ hst.2) end /-- Rectangles of countably spanning sets are countably spanning. -/ lemma is_countably_spanning.prod {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : is_countably_spanning (image2 set.prod C D) := begin rcases ⟨hC, hD⟩ with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩, refine ⟨λ n, (s n.unpair.1).prod (t n.unpair.2), λ n, mem_image2_of_mem (h1s _) (h1t _), _⟩, rw [Union_unpair_prod, h2s, h2t, univ_prod_univ] end variables [measurable_space α] [measurable_space α'] [measurable_space β] [measurable_space β'] variables [measurable_space γ] variables {μ : measure α} {ν : measure β} {τ : measure γ} variables [normed_group E] [measurable_space E] /-! ### Measurability Before we define the product measure, we can talk about the measurability of operations on binary functions. We show that if `f` is a binary measurable function, then the function that integrates along one of the variables (using either the Lebesgue or Bochner integral) is measurable. -/ /-- The product of generated σ-algebras is the one generated by rectangles, if both generating sets are countably spanning. -/ lemma generate_from_prod_eq {α β} {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : @prod.measurable_space _ _ (generate_from C) (generate_from D) = generate_from (image2 set.prod C D) := begin apply le_antisymm, { refine sup_le _ _; rw [comap_generate_from]; apply generate_from_le; rintro _ ⟨s, hs, rfl⟩, { rcases hD with ⟨t, h1t, h2t⟩, rw [← prod_univ, ← h2t, prod_Union], apply measurable_set.Union, intro n, apply measurable_set_generate_from, exact ⟨s, t n, hs, h1t n, rfl⟩ }, { rcases hC with ⟨t, h1t, h2t⟩, rw [← univ_prod, ← h2t, Union_prod_const], apply measurable_set.Union, rintro n, apply measurable_set_generate_from, exact mem_image2_of_mem (h1t n) hs } }, { apply generate_from_le, rintro _ ⟨s, t, hs, ht, rfl⟩, rw [prod_eq], apply (measurable_fst _).inter (measurable_snd _), { exact measurable_set_generate_from hs }, { exact measurable_set_generate_from ht } } end /-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D` generate the σ-algebra on `α × β`. -/ lemma generate_from_eq_prod {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_countably_spanning C) (h2D : is_countably_spanning D) : generate_from (image2 set.prod C D) = prod.measurable_space := by rw [← hC, ← hD, generate_from_prod_eq h2C h2D] /-- The product σ-algebra is generated from boxes, i.e. `s.prod t` for sets `s : set α` and `t : set β`. -/ lemma generate_from_prod : generate_from (image2 set.prod {s : set α | measurable_set s} {t : set β | measurable_set t}) = prod.measurable_space := generate_from_eq_prod generate_from_measurable_set generate_from_measurable_set is_countably_spanning_measurable_set is_countably_spanning_measurable_set /-- Rectangles form a π-system. -/ lemma is_pi_system_prod : is_pi_system (image2 set.prod {s : set α | measurable_set s} {t : set β | measurable_set t}) := is_pi_system_measurable_set.prod is_pi_system_measurable_set /-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. `measurable_measure_prod_mk_left` is strictly more general. -/ lemma measurable_measure_prod_mk_left_finite [finite_measure ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin refine induction_on_inter generate_from_prod.symm is_pi_system_prod _ _ _ _ hs, { simp [measurable_zero, const_def] }, { rintro _ ⟨s, t, hs, ht, rfl⟩, simp only [mk_preimage_prod_right_eq_if, measure_if], exact measurable_const.indicator hs }, { intros t ht h2t, simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_lt_top ν _)], exact h2t.const_sub _ }, { intros f h1f h2f h3f, simp_rw [preimage_Union], have : ∀ b, ν (⋃ i, prod.mk b ⁻¹' f i) = ∑' i, ν (prod.mk b ⁻¹' f i) := λ b, measure_Union (λ i j hij, disjoint.preimage _ (h1f i j hij)) (λ i, measurable_prod_mk_left (h2f i)), simp_rw [this], apply measurable.ennreal_tsum h3f }, end /-- If `ν` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_left [sigma_finite ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin have : ∀ x, measurable_set (prod.mk x ⁻¹' s) := λ x, measurable_prod_mk_left hs, simp only [← @supr_restrict_spanning_sets _ _ ν, this], apply measurable_supr, intro i, haveI := fact.mk (measure_spanning_sets_lt_top ν i), exact measurable_measure_prod_mk_left_finite hs end /-- If `μ` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_right {μ : measure α} [sigma_finite μ] {s : set (α × β)} (hs : measurable_set s) : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' s)) := measurable_measure_prod_mk_left (measurable_set_swap_iff.mpr hs) lemma measurable.map_prod_mk_left [sigma_finite ν] : measurable (λ x : α, map (prod.mk x) ν) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_left hs], exact measurable_measure_prod_mk_left hs end lemma measurable.map_prod_mk_right {μ : measure α} [sigma_finite μ] : measurable (λ y : β, map (λ x : α, (x, y)) μ) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_right hs], exact measurable_measure_prod_mk_right hs end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_right' [sigma_finite ν] : ∀ {f : α × β → ℝ≥0∞} (hf : measurable f), measurable (λ x, ∫⁻ y, f (x, y) ∂ν) := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], suffices : measurable (λ x, c * ν (prod.mk x ⁻¹' s)), { simpa [lintegral_indicator _ (m hs)] }, exact (measurable_measure_prod_mk_left hs).const_mul _ }, { rintro f g - hf hg h2f h2g, simp_rw [pi.add_apply, lintegral_add (hf.comp m) (hg.comp m)], exact h2f.add h2g }, { intros f hf h2f h3f, have := measurable_supr h3f, have : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), simpa [lintegral_supr (λ n, (hf n).comp m), this] } end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_right [sigma_finite ν] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ x, ∫⁻ y, f x y ∂ν) := hf.lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_left' [sigma_finite μ] {f : α × β → ℝ≥0∞} (hf : measurable f) : measurable (λ y, ∫⁻ x, f (x, y) ∂μ) := (measurable_swap_iff.mpr hf).lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_left [sigma_finite μ] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ y, ∫⁻ x, f x y ∂μ) := hf.lintegral_prod_left' lemma measurable_set_integrable [sigma_finite ν] [opens_measurable_space E] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable_set { x | integrable (f x) ν } := begin simp_rw [integrable, hf.of_uncurry_left.ae_measurable, true_and], exact measurable_set_lt (measurable.lintegral_prod_right hf.ennnorm) measurable_const end section variables [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measurable.integral_prod_right [sigma_finite ν] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable (λ x, ∫ y, f x y ∂ν) := begin let s : ℕ → simple_func (α × β) E := simple_func.approx_on _ hf univ _ (mem_univ 0), let s' : ℕ → α → simple_func β E := λ n x, (s n).comp (prod.mk x) measurable_prod_mk_left, let f' : ℕ → α → E := λ n, {x | integrable (f x) ν}.indicator (λ x, (s' n x).integral ν), have hf' : ∀ n, measurable (f' n), { intro n, refine measurable.indicator _ (measurable_set_integrable hf), have : ∀ x, (s' n x).range.filter (λ x, x ≠ 0) ⊆ (s n).range, { intros x, refine finset.subset.trans (finset.filter_subset _ _) _, intro y, simp_rw [simple_func.mem_range], rintro ⟨z, rfl⟩, exact ⟨(x, z), rfl⟩ }, simp only [simple_func.integral_eq_sum_of_subset (this _)], refine finset.measurable_sum _ (λ x _, _), refine (measurable.ennreal_to_real _).smul_const _, simp only [simple_func.coe_comp, preimage_comp] {single_pass := tt}, apply measurable_measure_prod_mk_left, exact (s n).measurable_set_fiber x }, have h2f' : tendsto f' at_top (𝓝 (λ (x : α), ∫ (y : β), f x y ∂ν)), { rw [tendsto_pi], intro x, by_cases hfx : integrable (f x) ν, { have : ∀ n, integrable (s' n x) ν, { intro n, apply (hfx.norm.add hfx.norm).mono' (s' n x).measurable.ae_measurable, apply eventually_of_forall, intro y, simp_rw [s', simple_func.coe_comp], exact simple_func.norm_approx_on_zero_le _ _ (x, y) n }, simp only [f', hfx, simple_func.integral_eq_integral _ (this _), indicator_of_mem, mem_set_of_eq], refine tendsto_integral_of_dominated_convergence (λ y, ∥f x y∥ + ∥f x y∥) (λ n, (s' n x).ae_measurable) hf.of_uncurry_left.ae_measurable (hfx.norm.add hfx.norm) _ _, { exact λ n, eventually_of_forall (λ y, simple_func.norm_approx_on_zero_le _ _ (x, y) n) }, { exact eventually_of_forall (λ y, simple_func.tendsto_approx_on _ _ (by simp)) } }, { simpa [f', hfx, integral_undef] using @tendsto_const_nhds _ _ _ (0 : E) _, } }, exact measurable_of_tendsto_metric hf' h2f' end /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. -/ lemma measurable.integral_prod_right' [sigma_finite ν] ⦃f : α × β → E⦄ (hf : measurable f) : measurable (λ x, ∫ y, f (x, y) ∂ν) := by { rw [← uncurry_curry f] at hf, exact hf.integral_prod_right } /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measurable.integral_prod_left [sigma_finite μ] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable (λ y, ∫ x, f x y ∂μ) := (hf.comp measurable_swap).integral_prod_right' /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. -/ lemma measurable.integral_prod_left' [sigma_finite μ] ⦃f : α × β → E⦄ (hf : measurable f) : measurable (λ y, ∫ x, f (x, y) ∂μ) := (hf.comp measurable_swap).integral_prod_right' end /-! ### The product measure -/ namespace measure_theory namespace measure /-- The binary product of measures. They are defined for arbitrary measures, but we basically prove all properties under the assumption that at least one of them is σ-finite. -/ @[irreducible] protected def prod (μ : measure α) (ν : measure β) : measure (α × β) := bind μ $ λ x : α, map (prod.mk x) ν instance prod.measure_space {α β} [measure_space α] [measure_space β] : measure_space (α × β) := { volume := volume.prod volume } variables {μ ν} [sigma_finite ν] lemma prod_apply {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ x, ν (prod.mk x ⁻¹' s) ∂μ := by simp_rw [measure.prod, bind_apply hs measurable.map_prod_mk_left, map_apply measurable_prod_mk_left hs] @[simp] lemma prod_prod {s : set α} {t : set β} (hs : measurable_set s) (ht : measurable_set t) : μ.prod ν (s.prod t) = μ s * ν t := by simp_rw [prod_apply (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ hs, lintegral_const, restrict_apply measurable_set.univ, univ_inter, mul_comm] local attribute [instance] nonempty_measurable_superset /-- If we don't assume measurability of `s` and `t`, we can bound the measure of their product. -/ lemma prod_prod_le (s : set α) (t : set β) : μ.prod ν (s.prod t) ≤ μ s * ν t := begin by_cases hs0 : μ s = 0, { rcases (exists_measurable_superset_of_null hs0) with ⟨s', hs', h2s', h3s'⟩, convert measure_mono (prod_mono hs' (subset_univ _)), simp_rw [hs0, prod_prod h2s' measurable_set.univ, h3s', zero_mul] }, by_cases hti : ν t = ∞, { convert le_top, simp_rw [hti, ennreal.mul_top, hs0, if_false] }, rw [measure_eq_infi' μ], simp_rw [ennreal.infi_mul hti], refine le_infi _, rintro ⟨s', h1s', h2s'⟩, rw [subtype.coe_mk], by_cases ht0 : ν t = 0, { rcases (exists_measurable_superset_of_null ht0) with ⟨t', ht', h2t', h3t'⟩, convert measure_mono (prod_mono (subset_univ _) ht'), simp_rw [ht0, prod_prod measurable_set.univ h2t', h3t', mul_zero] }, by_cases hsi : μ s' = ∞, { convert le_top, simp_rw [hsi, ennreal.top_mul, ht0, if_false] }, rw [measure_eq_infi' ν], simp_rw [ennreal.mul_infi hsi], refine le_infi _, rintro ⟨t', h1t', h2t'⟩, convert measure_mono (prod_mono h1s' h1t'), simp [prod_prod h2s' h2t'], end lemma ae_measure_lt_top {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s < ∞) : ∀ᵐ x ∂μ, ν (prod.mk x ⁻¹' s) < ∞ := by { simp_rw [prod_apply hs] at h2s, refine ae_lt_top (measurable_measure_prod_mk_left hs) h2s } lemma integrable_measure_prod_mk_left {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s < ∞) : integrable (λ x, (ν (prod.mk x ⁻¹' s)).to_real) μ := begin refine ⟨(measurable_measure_prod_mk_left hs).ennreal_to_real.ae_measurable, _⟩, simp_rw [has_finite_integral, ennnorm_eq_of_real to_real_nonneg], convert h2s using 1, simp_rw [prod_apply hs], apply lintegral_congr_ae, refine (ae_measure_lt_top hs h2s).mp _, apply eventually_of_forall, intros x hx, rw [lt_top_iff_ne_top] at hx, simp [of_real_to_real, hx], end /-- Note: the assumption `hs` cannot be dropped. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_prod_null {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = 0 ↔ (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by simp_rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)] /-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_ae_null_of_prod_null {s : set (α × β)} (h : μ.prod ν s = 0) : (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := begin obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h, simp_rw [measure_prod_null mt] at ht, rw [eventually_le_antisymm_iff], exact ⟨eventually_le.trans_eq (eventually_of_forall $ λ x, (measure_mono (preimage_mono hst) : _)) ht, eventually_of_forall $ λ x, zero_le _⟩ end /-- Note: the converse is not true. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) : ∀ᵐ x ∂ μ, ∀ᵐ y ∂ ν, p (x, y) := measure_ae_null_of_prod_null h /-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/ def finite_spanning_sets_in.prod {ν : measure β} {C : set (set α)} {D : set (set β)} (hμ : μ.finite_spanning_sets_in C) (hν : ν.finite_spanning_sets_in D) (hC : ∀ s ∈ C, measurable_set s) (hD : ∀ t ∈ D, measurable_set t) : (μ.prod ν).finite_spanning_sets_in (image2 set.prod C D) := begin haveI := hν.sigma_finite hD, refine ⟨λ n, (hμ.set n.unpair.1).prod (hν.set n.unpair.2), λ n, mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), λ n, _, _⟩, { simp_rw [prod_prod (hC _ (hμ.set_mem _)) (hD _ (hν.set_mem _))], exact mul_lt_top (hμ.finite _) (hν.finite _) }, { simp_rw [Union_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] } end lemma prod_fst_absolutely_continuous : map prod.fst (μ.prod ν) ≪ μ := begin refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [map_apply measurable_fst hs, ← prod_univ, prod_prod hs measurable_set.univ], rw [h2s, zero_mul] -- for some reason `simp_rw [h2s]` doesn't work end lemma prod_snd_absolutely_continuous : map prod.snd (μ.prod ν) ≪ ν := begin refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [map_apply measurable_snd hs, ← univ_prod, prod_prod measurable_set.univ hs], rw [h2s, mul_zero] -- for some reason `simp_rw [h2s]` doesn't work end variables [sigma_finite μ] instance prod.sigma_finite : sigma_finite (μ.prod ν) := ⟨⟨(μ.to_finite_spanning_sets_in.prod ν.to_finite_spanning_sets_in (λ _, id) (λ _, id)).mono $ by { rintro _ ⟨s, t, hs, ht, rfl⟩, exact hs.prod ht }⟩⟩ /-- A measure on a product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ lemma prod_eq_generate_from {μ : measure α} {ν : measure β} {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_pi_system C) (h2D : is_pi_system D) (h3C : μ.finite_spanning_sets_in C) (h3D : ν.finite_spanning_sets_in D) {μν : measure (α × β)} (h₁ : ∀ (s ∈ C) (t ∈ D), μν (set.prod s t) = μ s * ν t) : μ.prod ν = μν := begin have h4C : ∀ (s : set α), s ∈ C → measurable_set s, { intros s hs, rw [← hC], exact measurable_set_generate_from hs }, have h4D : ∀ (t : set β), t ∈ D → measurable_set t, { intros t ht, rw [← hD], exact measurable_set_generate_from ht }, refine (h3C.prod h3D h4C h4D).ext (generate_from_eq_prod hC hD h3C.is_countably_spanning h3D.is_countably_spanning).symm (h2C.prod h2D) _, { rintro _ ⟨s, t, hs, ht, rfl⟩, haveI := h3D.sigma_finite h4D, simp_rw [h₁ s hs t ht, prod_prod (h4C s hs) (h4D t ht)] } end /-- A measure on a product space equals the product measure if they are equal on rectangles. -/ lemma prod_eq {μν : measure (α × β)} (h : ∀ s t, measurable_set s → measurable_set t → μν (s.prod t) = μ s * ν t) : μ.prod ν = μν := prod_eq_generate_from generate_from_measurable_set generate_from_measurable_set is_pi_system_measurable_set is_pi_system_measurable_set μ.to_finite_spanning_sets_in ν.to_finite_spanning_sets_in (λ s hs t ht, h s t hs ht) lemma prod_swap : map prod.swap (μ.prod ν) = ν.prod μ := begin refine (prod_eq _).symm, intros s t hs ht, simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod ht hs, mul_comm] end lemma prod_apply_symm {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ y, μ ((λ x, (x, y)) ⁻¹' s) ∂ν := by { rw [← prod_swap, map_apply measurable_swap hs], simp only [prod_apply (measurable_swap hs)], refl } lemma prod_assoc_prod [sigma_finite τ] : map measurable_equiv.prod_assoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) := begin refine (prod_eq_generate_from generate_from_measurable_set generate_from_prod is_pi_system_measurable_set is_pi_system_prod μ.to_finite_spanning_sets_in (ν.to_finite_spanning_sets_in.prod τ.to_finite_spanning_sets_in (λ _, id) (λ _, id)) _).symm, rintro s hs _ ⟨t, u, ht, hu, rfl⟩, rw [mem_set_of_eq] at hs ht hu, simp_rw [map_apply (measurable_equiv.measurable _) (hs.prod (ht.prod hu)), prod_prod ht hu, measurable_equiv.prod_assoc, measurable_equiv.coe_eq, equiv.prod_assoc_preimage, prod_prod (hs.prod ht) hu, prod_prod hs ht, mul_assoc] end /-! ### The product of specific measures -/ lemma prod_restrict {s : set α} {t : set β} (hs : measurable_set s) (ht : measurable_set t) : (μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s.prod t) := begin refine prod_eq (λ s' t' hs' ht', _), simp_rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod (hs'.inter hs) (ht'.inter ht), restrict_apply hs', restrict_apply ht'] end lemma restrict_prod_eq_prod_univ {s : set α} (hs : measurable_set s) : (μ.restrict s).prod ν = (μ.prod ν).restrict (s.prod univ) := begin have : ν = ν.restrict set.univ := measure.restrict_univ.symm, rwa [this, measure.prod_restrict, ← this], exact measurable_set.univ, end lemma prod_dirac (y : β) : μ.prod (dirac y) = map (λ x, (x, y)) μ := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if, dirac_apply' _ ht, ← indicator_mul_right _ (λ x, μ s), pi.one_apply, mul_one] end lemma dirac_prod (x : α) : (dirac x).prod ν = map (prod.mk x) ν := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, dirac_apply' _ hs, ← indicator_mul_left _ _ (λ x, ν t), pi.one_apply, one_mul] end lemma dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) := by rw [prod_dirac, map_dirac measurable_prod_mk_right] lemma prod_sum {ι : Type*} [fintype ι] (ν : ι → measure β) [∀ i, sigma_finite (ν i)] : μ.prod (sum ν) = sum (λ i, μ.prod (ν i)) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ ht, prod_prod hs ht, tsum_fintype, finset.mul_sum] end lemma sum_prod {ι : Type*} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : (sum μ).prod ν = sum (λ i, (μ i).prod ν) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ hs, prod_prod hs ht, tsum_fintype, finset.sum_mul] end lemma prod_add (ν' : measure β) [sigma_finite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod hs ht, left_distrib] } lemma add_prod (μ' : measure α) [sigma_finite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod hs ht, right_distrib] } @[simp] lemma zero_prod (ν : measure β) : (0 : measure α).prod ν = 0 := by { rw measure.prod, exact bind_zero_left _ } @[simp] lemma prod_zero (μ : measure α) : μ.prod (0 : measure β) = 0 := by simp [measure.prod] lemma map_prod_map {δ} [measurable_space δ] {f : α → β} {g : γ → δ} {μa : measure α} {μc : measure γ} (hfa : sigma_finite (map f μa)) (hgc : sigma_finite (map g μc)) (hf : measurable f) (hg : measurable g) : (map f μa).prod (map g μc) = map (prod.map f g) (μa.prod μc) := begin haveI := hgc.of_map μc hg, refine prod_eq (λ s t hs ht, _), rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht], exact prod_prod (hf hs) (hg ht) end end measure end measure_theory open measure_theory.measure section lemma ae_measurable.prod_swap [sigma_finite μ] [sigma_finite ν] {f : β × α → γ} (hf : ae_measurable f (ν.prod μ)) : ae_measurable (λ (z : α × β), f z.swap) (μ.prod ν) := by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap } lemma ae_measurable.fst [sigma_finite ν] {f : α → γ} (hf : ae_measurable f μ) : ae_measurable (λ (z : α × β), f z.1) (μ.prod ν) := hf.comp_measurable' measurable_fst prod_fst_absolutely_continuous lemma ae_measurable.snd [sigma_finite ν] {f : β → γ} (hf : ae_measurable f ν) : ae_measurable (λ (z : α × β), f z.2) (μ.prod ν) := hf.comp_measurable' measurable_snd prod_snd_absolutely_continuous /-- The Bochner integral is a.e.-measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is a.e.-measurable. -/ lemma ae_measurable.integral_prod_right' [sigma_finite ν] [second_countable_topology E] [normed_space ℝ E] [borel_space E] [complete_space E] ⦃f : α × β → E⦄ (hf : ae_measurable f (μ.prod ν)) : ae_measurable (λ x, ∫ y, f (x, y) ∂ν) μ := ⟨λ x, ∫ y, hf.mk f (x, y) ∂ν, hf.measurable_mk.integral_prod_right', begin filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk], assume x hx, exact integral_congr_ae hx end⟩ lemma ae_measurable.prod_mk_left [sigma_finite ν] {f : α × β → γ} (hf : ae_measurable f (μ.prod ν)) : ∀ᵐ x ∂μ, ae_measurable (λ y, f (x, y)) ν := begin filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk], intros x hx, exact ⟨λ y, hf.mk f (x, y), hf.measurable_mk.comp measurable_prod_mk_left, hx⟩ end end namespace measure_theory /-! ### The Lebesgue integral on a product -/ variables [sigma_finite ν] lemma lintegral_prod_swap [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z.swap ∂(ν.prod μ) = ∫⁻ z, f z ∂(μ.prod ν) := by { rw ← prod_swap at hf, rw [← lintegral_map' hf measurable_swap, prod_swap] } /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod_of_measurable : ∀ (f : α × β → ℝ≥0∞) (hf : measurable f), ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], simp [lintegral_indicator, m hs, hs, lintegral_const_mul, measurable_measure_prod_mk_left hs, prod_apply] }, { rintro f g - hf hg h2f h2g, simp [lintegral_add, measurable.lintegral_prod_right', hf.comp m, hg.comp m, hf, hg, h2f, h2g] }, { intros f hf h2f h3f, have kf : ∀ x n, measurable (λ y, f n (x, y)) := λ x n, (hf n).comp m, have k2f : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), have lf : ∀ n, measurable (λ x, ∫⁻ y, f n (x, y) ∂ν) := λ n, (hf n).lintegral_prod_right', have l2f : monotone (λ n x, ∫⁻ y, f n (x, y) ∂ν) := λ i j hij x, lintegral_mono (k2f x hij), simp only [lintegral_supr hf h2f, lintegral_supr (kf _), k2f, lintegral_supr lf l2f, h3f] }, end /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have A : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ z, hf.mk f z ∂(μ.prod ν) := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ, { apply lintegral_congr_ae, filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk], assume a ha, exact lintegral_congr_ae ha }, rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk], apply_instance end /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm' [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := by { simp_rw [← lintegral_prod_swap f hf], exact lintegral_prod _ hf.prod_swap } /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := lintegral_prod_symm' f hf /-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂(μ.prod ν) := (lintegral_prod _ hf).symm /-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral_symm [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂(ν.prod μ) := (lintegral_prod_symm _ hf.prod_swap).symm /-- Change the order of Lebesgue integration. -/ lemma lintegral_lintegral_swap [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν := (lintegral_lintegral hf).trans (lintegral_prod_symm _ hf) lemma lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) : ∫⁻ z, f z.1 * g z.2 ∂(μ.prod ν) = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg] /-! ### Integrability on a product -/ section variables [opens_measurable_space E] lemma integrable.swap [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (f ∘ prod.swap) (ν.prod μ) := ⟨hf.ae_measurable.prod_swap, (lintegral_prod_swap _ hf.ae_measurable.ennnorm : _).le.trans_lt hf.has_finite_integral⟩ lemma integrable_swap_iff [sigma_finite μ] ⦃f : α × β → E⦄ : integrable (f ∘ prod.swap) (ν.prod μ) ↔ integrable f (μ.prod ν) := ⟨λ hf, by { convert hf.swap, ext ⟨x, y⟩, refl }, λ hf, hf.swap⟩ lemma has_finite_integral_prod_iff ⦃f : α × β → E⦄ (h1f : measurable f) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := begin simp only [has_finite_integral, lintegral_prod_of_measurable _ h1f.ennnorm], have : ∀ x, ∀ᵐ y ∂ν, 0 ≤ ∥f (x, y)∥ := λ x, eventually_of_forall (λ y, norm_nonneg _), simp_rw [integral_eq_lintegral_of_nonneg_ae (this _) (h1f.norm.comp measurable_prod_mk_left).ae_measurable, ennnorm_eq_of_real to_real_nonneg, of_real_norm_eq_coe_nnnorm], -- this fact is probably too specialized to be its own lemma have : ∀ {p q r : Prop} (h1 : r → p), (r ↔ p ∧ q) ↔ (p → (r ↔ q)) := λ p q r h1, by rw [← and.congr_right_iff, and_iff_right_of_imp h1], rw [this], { intro h2f, rw lintegral_congr_ae, refine h2f.mp _, apply eventually_of_forall, intros x hx, dsimp only, rw [of_real_to_real], rw [← lt_top_iff_ne_top], exact hx }, { intro h2f, refine ae_lt_top _ h2f, exact h1f.ennnorm.lintegral_prod_right' }, end lemma has_finite_integral_prod_iff' ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := begin rw [has_finite_integral_congr h1f.ae_eq_mk, has_finite_integral_prod_iff h1f.measurable_mk], apply and_congr, { apply eventually_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm], assume x hx, exact has_finite_integral_congr hx }, { apply has_finite_integral_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm], assume x hx, exact integral_congr_ae (eventually_eq.fun_comp hx _) }, { apply_instance } end /-- A binary function is integrable if the function `y ↦ f (x, y)` is integrable for almost every `x` and the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable. -/ lemma integrable_prod_iff ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν) ∧ integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := by simp [integrable, h1f, has_finite_integral_prod_iff', h1f.norm.integral_prod_right', h1f.prod_mk_left] /-- A binary function is integrable if the function `x ↦ f (x, y)` is integrable for almost every `y` and the function `y ↦ ∫ ∥f (x, y)∥ dx` is integrable. -/ lemma integrable_prod_iff' [sigma_finite μ] ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ) ∧ integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν := by { convert integrable_prod_iff (h1f.prod_swap) using 1, rw [integrable_swap_iff] } lemma integrable.prod_left_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ := ((integrable_prod_iff' hf.ae_measurable).mp hf).1 lemma integrable.prod_right_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν := hf.swap.prod_left_ae lemma integrable.integral_norm_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := ((integrable_prod_iff hf.ae_measurable).mp hf).2 lemma integrable.integral_norm_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν := hf.swap.integral_norm_prod_left end variables [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] lemma integrable.integral_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, f (x, y) ∂ν) μ := integrable.mono hf.integral_norm_prod_left hf.ae_measurable.integral_prod_right' $ eventually_of_forall $ λ x, (norm_integral_le_integral_norm _).trans_eq $ (norm_of_nonneg $ integral_nonneg_of_ae $ eventually_of_forall $ λ y, (norm_nonneg (f (x, y)) : _)).symm lemma integrable.integral_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, f (x, y) ∂μ) ν := hf.swap.integral_prod_left /-! ### The Bochner integral on a product -/ variables [sigma_finite μ] lemma integral_prod_swap (f : α × β → E) (hf : ae_measurable f (μ.prod ν)) : ∫ z, f z.swap ∂(ν.prod μ) = ∫ z, f z ∂(μ.prod ν) := begin rw ← prod_swap at hf, rw [← integral_map measurable_swap hf, prod_swap] end variables {E' : Type*} [measurable_space E'] [normed_group E'] [borel_space E'] [complete_space E'] [normed_space ℝ E'] [second_countable_topology E'] /-! Some rules about the sum/difference of double integrals. They follow from `integral_add`, but we separate them out as separate lemmas, because they involve quite some steps. -/ /-- Integrals commute with addition inside another integral. `F` can be any function. -/ lemma integral_fn_integral_add ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) + g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν + ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae], intros x h2f h2g, simp [integral_add h2f h2g], end /-- Integrals commute with subtraction inside another integral. `F` can be any measurable function. -/ lemma integral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae], intros x h2f h2g, simp [integral_sub h2f h2g] end /-- Integrals commute with subtraction inside a lower Lebesgue integral. `F` can be any function. -/ lemma lintegral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → ℝ≥0∞) (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫⁻ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫⁻ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine lintegral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae], intros x h2f h2g, simp [integral_sub h2f h2g] end /-- Double integrals commute with addition. -/ lemma integral_integral_add ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) + g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_add id hf hg).trans $ integral_add hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with addition. This is the version with `(f + g) (x, y)` (instead of `f (x, y) + g (x, y)`) in the LHS. -/ lemma integral_integral_add' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f + g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_add hf hg /-- Double integrals commute with subtraction. -/ lemma integral_integral_sub ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) - g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_sub id hf hg).trans $ integral_sub hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with subtraction. This is the version with `(f - g) (x, y)` (instead of `f (x, y) - g (x, y)`) in the LHS. -/ lemma integral_integral_sub' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f - g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_sub hf hg /-- The map that sends an L¹-function `f : α × β → E` to `∫∫f` is continuous. -/ lemma continuous_integral_integral : continuous (λ (f : α × β →₁[μ.prod ν] E), ∫ x, ∫ y, f (x, y) ∂ν ∂μ) := begin rw [continuous_iff_continuous_at], intro g, refine tendsto_integral_of_L1 _ (L1.integrable_coe_fn g).integral_prod_left (eventually_of_forall $ λ h, (L1.integrable_coe_fn h).integral_prod_left) _, simp_rw [← lintegral_fn_integral_sub (λ x, (nnnorm x : ℝ≥0∞)) (L1.integrable_coe_fn _) (L1.integrable_coe_fn g)], refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds _ (λ i, zero_le _) _, { exact λ i, ∫⁻ x, ∫⁻ y, nnnorm (i (x, y) - g (x, y)) ∂ν ∂μ }, swap, { exact λ i, lintegral_mono (λ x, ennnorm_integral_le_lintegral_ennnorm _) }, show tendsto (λ (i : α × β →₁[μ.prod ν] E), ∫⁻ x, ∫⁻ (y : β), nnnorm (i (x, y) - g (x, y)) ∂ν ∂μ) (𝓝 g) (𝓝 0), have : ∀ (i : α × β →₁[μ.prod ν] E), measurable (λ z, (nnnorm (i z - g z) : ℝ≥0∞)) := λ i, ((Lp.measurable i).sub (Lp.measurable g)).ennnorm, simp_rw [← lintegral_prod_of_measurable _ (this _), ← L1.of_real_norm_sub_eq_lintegral, ← of_real_zero], refine (continuous_of_real.tendsto 0).comp _, rw [← tendsto_iff_norm_tendsto_zero], exact tendsto_id end /-- **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. `integrable_prod_iff` can be useful to show that the function in question in integrable. `measure_theory.integrable.integral_prod_right` is useful to show that the inner integral of the right-hand side is integrable. -/ lemma integral_prod : ∀ (f : α × β → E) (hf : integrable f (μ.prod ν)), ∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ := begin apply integrable.induction, { intros c s hs h2s, simp_rw [integral_indicator hs, ← indicator_comp_right, function.comp, integral_indicator (measurable_prod_mk_left hs), set_integral_const, integral_smul_const, integral_to_real (measurable_measure_prod_mk_left hs).ae_measurable (ae_measure_lt_top hs h2s), prod_apply hs] }, { intros f g hfg i_f i_g hf hg, simp_rw [integral_add' i_f i_g, integral_integral_add' i_f i_g, hf, hg] }, { exact is_closed_eq continuous_integral continuous_integral_integral }, { intros f g hfg i_f hf, convert hf using 1, { exact integral_congr_ae hfg.symm }, { refine integral_congr_ae _, refine (ae_ae_of_ae_prod hfg).mp _, apply eventually_of_forall, intros x hfgx, exact integral_congr_ae (ae_eq_symm hfgx) } } end /-- Symmetric version of **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. This version has the integrals on the right-hand side in the other order. -/ lemma integral_prod_symm (f : α × β → E) (hf : integrable f (μ.prod ν)) : ∫ z, f z ∂(μ.prod ν) = ∫ y, ∫ x, f (x, y) ∂μ ∂ν := by { simp_rw [← integral_prod_swap f hf.ae_measurable], exact integral_prod _ hf.swap } /-- Reversed version of **Fubini's Theorem**. -/ lemma integral_integral {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.1 z.2 ∂(μ.prod ν) := (integral_prod _ hf).symm /-- Reversed version of **Fubini's Theorem** (symmetric version). -/ lemma integral_integral_symm {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.2 z.1 ∂(ν.prod μ) := (integral_prod_symm _ hf.swap).symm /-- Change the order of Bochner integration. -/ lemma integral_integral_swap ⦃f : α → β → E⦄ (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ y, ∫ x, f x y ∂μ ∂ν := (integral_integral hf).trans (integral_prod_symm _ hf) end measure_theory
629a34bbeab911113f0ba719bf9ffe6b05088d4e
11e28114d9553ecd984ac4819661ffce3068bafe
/src/rule.lean
f2a04adde96315bd7fdf166199e2da7e15b736b5
[ "MIT" ]
permissive
EdAyers/lean-subtask
9a26eb81f0c8576effed4ca94342ae1281445c59
04ac5a6c3bc3bfd190af4d6dcce444ddc8914e4b
refs/heads/master
1,586,516,665,621
1,558,701,948,000
1,558,701,948,000
160,983,035
4
1
null
null
null
null
UTF-8
Lean
false
false
6,207
lean
/- Author: E.W.Ayers © 2019 -/ import .util .table open tactic /-- Member of a telescope.-/ @[derive decidable_eq] meta structure hyp := (n : name) (bi : binder_info) (type : expr) /-- A telescope keeps track of all of the names and types of the free variables in the context. -/ meta def telescope := list hyp meta def telescope.to_pis : expr → telescope → expr := list.foldl (λ e ⟨n,b,y⟩, expr.pi n b y e) meta def telescope.to_lambdas : expr → telescope → expr := list.foldl (λ e ⟨n,b,y⟩, expr.lam n b y e) private meta def telescope.of_pis_aux : telescope → expr → telescope × expr | acc (expr.pi n bi y b) := telescope.of_pis_aux (⟨n,bi,y⟩::acc) b | acc x := ⟨acc,x⟩ meta def telescope.of_pis : expr → (telescope × expr) := telescope.of_pis_aux [] meta def telescope.to_pattern_core : expr → tactic (expr × list expr) |(expr.lam n bi y b) := do un ← mk_fresh_name, let x := expr.local_const un n bi b, let b := expr.instantiate_var b x, (p, xs) ← telescope.to_pattern_core b, return (p, x::xs) |x := pure (x, []) meta def telescope.to_pattern (t : telescope) (e : expr) : tactic pattern := do (e,xs) ← telescope.to_pattern_core $ telescope.to_lambdas e t, mk_pattern [] xs e [] xs @[derive decidable_eq] meta structure rule := -- relation is always `=` for now. (id : name) -- a way of identifying the rule. (ctxt : telescope) -- arguments, local context. (lhs : expr) (rhs : expr) (type : expr) (pf : expr) -- the proof expression of the given rule. (was_flipped : option (name × expr)) -- [HACK] needed to make sure `rule.flip` doesn't keep applying `eq.symm`. namespace rule meta instance has_lt : has_lt rule := ⟨λ r1 r2, (r1.lhs,r1.rhs) < (r2.lhs,r2.rhs)⟩ meta instance has_decidable_lt : decidable_rel ((<) : rule → rule → Prop) := by apply_instance meta instance : has_to_string rule := ⟨λ r, (to_string r.lhs) ++ " = " ++ (to_string r.rhs)⟩ meta instance : has_to_tactic_format rule := ⟨λ r, do plhs ← tactic.pp r.lhs, prhs ← tactic.pp r.rhs, pure $ plhs ++ " = " ++ prhs -- infer_type r.pf >>= whnf >>= tactic_format_expr ⟩ /-- Create a `rule` from a proof term and a name. -/ meta def of_prf (id : name) : expr → tactic rule := λ pf, do t ← infer_type pf >>= whnf, -- trace t, ⟨ctxt,`(%%lhs = %%rhs)⟩ ← pure $ telescope.of_pis t | (do pft ← pp pf, ppt ← pp t, fail $ (to_fmt "rule.of_prf: supplied expression ") ++ pft ++ " : " ++ ppt ++ " is not an equality proof "), pure {id := id, ctxt := ctxt, lhs := lhs, rhs := rhs, pf := pf, type := t, was_flipped := none} /-- Swap the LHS and RHS. -/ meta def flip (r : rule) : tactic rule := match r.was_flipped with |none := do let P := r.ctxt.foldl (λ e ⟨n,b,y⟩, expr.pi n b (to_pexpr y) e) $ ```(%%r.rhs = %%r.lhs), T ← to_expr $ P, pf ← tactic.fabricate (some T) (do tactic.intros, tactic.applyc `eq.symm, tactic.apply_core r.pf {new_goals := new_goals.non_dep_only}, all_goals $ try $ prop_assumption, skip ), pure { ctxt := r.ctxt , lhs := r.rhs , rhs := r.lhs , type := r.type , pf := pf , id := r.id ++ `flipped , was_flipped := some (r.id, r.pf) } |some pf := of_prf pf.1 pf.2 end /-- Sanity check that the LHS, RHS actually correspond to what the proof says.-/ meta def is_wf (r : rule) : tactic bool := do r' ← of_prf r.id $ pf $ r, pure $ r = r' /-- Take a name `n` and try to make a rule from the lemma at the name's declaration. -/ meta def of_name (n : name) : tactic rule := resolve_name n >>= pure ∘ pexpr.mk_explicit >>= to_expr >>= rule.of_prf n /--Returns true when the left hand side is a variable or metavariable. -/ meta def lhs_wildcard : rule → bool := λ r, expr.is_var r.lhs || expr.is_mvar r.lhs /--Returns true when the right hand side is a variable or metavariable. -/ meta def rhs_wildcard : rule → bool := λ r, expr.is_var r.rhs || expr.is_mvar r.rhs -- private meta def specify_aux : nat → expr → expr -- |0 acc := acc -- |(n+1) acc := specify_aux n $ expr.app acc (expr.var n) -- private meta def specify_aux₂ : list (hyp × option expr) → expr → expr -- |[] e := e -- |(⟨⟨n,b,y⟩, some E⟩::rest) e := specify_aux₂ rest $ expr.instantiate_var e E -- |(⟨⟨n,b,y⟩, none⟩ :: rest) e := specify_aux₂ rest $ expr.lam n b y e -- meta def specify : list (option expr) → rule → tactic rule | vals r := do -- when (r.ctxt.length ≠ vals.length) (fail "context assignment list is a different length to the rule's context. "), -- let rctxt := list.zip r.ctxt vals, -- let pf := specify_aux r.ctxt.length r.pf, -- let pf := specify_aux₂ rctxt pf, -- infer_type pf, -- make sure it's valid -- of_prf r.id pf meta def instantiate_mvars (r : rule) : tactic rule := tactic.instantiate_mvars r.pf >>= rule.of_prf r.id meta def get_local_const_dependencies (r : rule) : tactic (list expr) := do pf ← tactic.instantiate_mvars r.pf, let lcs := expr.list_local_consts pf, pure lcs meta def is_local_hypothesis (r : rule) : tactic bool := do lcds ← r.get_local_const_dependencies >>= list.mmap infer_type >>= list.mmap is_prop , -- [HACK] I am assuming that there are no subtypings and so on which is probably a bad assumption. pure $ list.foldl bor ff lcds meta def is_commuter (r : rule) : tactic bool := match r.lhs, r.rhs with | (expr.app (expr.app f1 (expr.var n1)) (expr.var m1)) , (expr.app (expr.app f2 (expr.var n2)) (expr.var m2)) := pure $ f1 = f2 ∧ n1 = m2 ∧ n2 = m1 |_, _ := pure ff end meta def is_def_eq (r₁ r₂ : rule) : tactic bool := tactic.is_success $ (do tactic.is_def_eq r₁.lhs r₂.lhs, tactic.is_def_eq r₁.rhs r₂.rhs ) end rule
795e15d65c8135a73dbe9000f736215e96eb2de4
2ee768fce4d0783536570385ee340d97e2411436
/src/uniqueness.lean
b28b09d53f7d5b7e8c4eeafe2ee5912c70dcf92a
[]
no_license
agjftucker/exists-unique
835cf0c0ec622d49dbceb84be37db62e6ab8a6d0
1fba6035a08347f424c765d8a1c56b1a15c8abbe
refs/heads/master
1,683,445,592,336
1,622,649,822,000
1,622,649,822,000
309,485,697
2
0
null
null
null
null
UTF-8
Lean
false
false
3,863
lean
import existence continuity monotonicity local prefix `𝒫`:100 := fun {α : Type} (s : finset α), {t // t ≤ s} variables {𝒩 : Type} [decidable_eq 𝒩] {T : with_top ℝ} variables {ℋ : well_behaved_soln 𝒩 T} {ℰ : equity_function 𝒩 T} variable (crash : ∀ ψ {A : finset 𝒩} (h : A.nonempty) (t : Tt T) (y : X 𝒩), ∃ (η : ℝ) (hη : η ≤ 0) (i : 𝒩) (hi : i ∈ A), E_star ℰ (v ℋ ψ A) t (y + η) i ≤ 0) section ind variables {ψ : ∀ (A : finset 𝒩), Tt T → X 𝒩 → 𝒫 A} (hψ : survivors_fn ℋ ℰ ψ) variables {A : finset 𝒩} (ih : ∀ B < A, ψ B = φ ℋ ℰ B) include hψ ih lemma vψ_continuous_wrt_assets : continuous_wrt_assets (v ℋ ψ A) := begin apply v_continuous_of_continuous_on_compl, intro t, rw continuous_on_congr (vψ_eq_u_on_compl_Vψ hψ ih), apply continuous.continuous_on, apply u_continuous_wrt_assets, end lemma Eψ_continuous_wrt_assets : continuous_wrt_assets (E_star ℰ (v ℋ ψ A)) := fun t, ℰ.continuity_preserving (vψ_continuous_wrt_assets hψ ih t) lemma Eψ_min_continuous_wrt_assets (h : A.nonempty) {t : Tt T} : continuous (fun y, A.inf' h (E_star ℰ (v ℋ ψ A) t y)) := begin suffices : continuous (A.inf' h (fun i y, E_star ℰ (v ℋ ψ A) t y i)), { convert this, ext y, rw finset.inf'_apply, }, apply finset.inf'_induction h, { exact fun _ _, continuous.min, }, { intros i hi, apply continuous_pi_iff.1, apply Eψ_continuous_wrt_assets hψ ih, }, end lemma Eψ_min_continuous_wrt_η (h : A.nonempty) {t : Tt T} {y : X 𝒩} : continuous (fun (η : ℝ), A.inf' h (E_star ℰ (v ℋ ψ A) t (y + η))) := begin apply (Eψ_min_continuous_wrt_assets hψ ih h).comp, apply (continuous_add_left y).comp, rw continuous_pi_iff, intro i, exact continuous_id, end include crash lemma exists_η₀_of_mem_Vψ (h : A.nonempty) {t : Tt T} {y : X 𝒩} : y ∈ V ψ A t → ∃ (η₀ : ℝ) (hη₀ : η₀ < 0), A.inf' h (E_star ℰ (v ℋ ψ A) t (y + η₀)) = 0 := begin intro hV, specialize crash ψ h t y, rcases crash with ⟨η, hη, i, hi, hE⟩, have hl : A.inf' h (E_star ℰ (v ℋ ψ A) t (y + η)) ≤ 0, { exact le_trans (finset.inf'_le _ hi) hE, }, have hu : 0 < A.inf' h (E_star ℰ (v ℋ ψ A) t (y + 0)), { rw [add_zero y, finset.lt_inf'_iff], rwa hψ.consistent at hV, }, have := intermediate_value_Ico hη (Eψ_min_continuous_wrt_η hψ ih h).continuous_on ⟨hl, hu⟩, rcases this with ⟨η₀, hη₀, he⟩, exact ⟨η₀, hη₀.2, he⟩, end lemma Vψ_subset_U : V ψ A ⊆ U ℋ ℰ A := begin intros t y hV, rw φ_consistent, intros i hi, rcases exists_η₀_of_mem_Vψ crash hψ ih ⟨i, hi⟩ hV with ⟨η₀, hη₀, he⟩, rw show y = y + η₀ + (-η₀ : ℝ), { exact eq_sub_of_add_eq rfl, }, suffices : 0 ≤ E_star ℰ (u ℋ ℰ A) t (y + η₀) i, { apply lt_of_le_of_lt this, apply E_strict_mono_wrt_assets, linarith, }, convert finset.inf'_le (E_star ℰ (u ℋ ℰ A) t (y + η₀)) hi, rw ← he, dunfold E_star, congr' 2, apply vψ_eq_u_on_compl_Vψ hψ ih, intro h, rw [hψ.consistent, ← finset.lt_inf'_iff ⟨i, hi⟩] at h, linarith, end variable (A) lemma ψ_eq_φ_of_eq_on_ssubsets : ψ A = φ ℋ ℰ A := begin funext t y, by_cases hV : y ∈ V ψ A t, { apply subtype.ext, transitivity A, { exact le_antisymm (ψ A t y).prop hV, }, { refine le_antisymm _ (φ ℋ ℰ A t y).prop, exact Vψ_subset_U crash hψ ih t hV, }, }, { exact ψ_eq_φ_on_compl_Vψ hψ ih hV, }, end end ind lemma unique_soln : ∀ ψ, survivors_fn ℋ ℰ ψ → ψ = φ ℋ ℰ := fun ψ hψ, funext (finset.strong_induction (ψ_eq_φ_of_eq_on_ssubsets crash hψ)) theorem exists_unique_soln : ∃! ψ, survivors_fn ℋ ℰ ψ := ⟨φ ℋ ℰ, exists_soln, unique_soln crash⟩
7dfee91f26f07ef60a30703260ae45dc400452fe
2de8c1580f92bb6c28b60135f589fe9d0513faba
/src/buch_correctness.lean
cebd41895655d0dfdd23031049884e82fce79850
[]
no_license
FCL-lean/verification
44a52e40ab78b18654b8d61bb55c2c912a40d2f4
be02c698c0ca78b18762e3fe7749cdc72a55d197
refs/heads/master
1,585,960,207,309
1,560,259,990,000
1,560,259,990,000
155,650,137
0
0
null
1,541,039,704,000
1,541,038,972,000
Lean
UTF-8
Lean
false
false
33,009
lean
import buchberger rtc wf_mv_polynomial open mv_polynomial open finsupp namespace buch variables {σ : Type*} {α : Type*} [decidable_eq σ] [decidable_eq α] [fintype σ] [decidable_linear_order (σ →₀ ℕ)] variables [discrete_field α] [is_well_founded (σ →₀ ℕ) (<)] [is_monomial_order (σ →₀ ℕ) (≤)] section reduction variables (s : finset (mv_polynomial σ α)) {S : finset (mv_polynomial σ α)} inductive red_one_step : mv_polynomial σ α → mv_polynomial σ α → Prop | cons : ∀ {p r : mv_polynomial σ α}, p ≠ 0 → red_one_step p.TL r.TL → p.LT = r.LT → red_one_step p r | red_LM : ∀ {p r : mv_polynomial σ α}, p ≠ 0 → (∃ (q : mv_polynomial σ α) (h₁ : q ∈ s) (h₂ : q ≠ 0) (h₃ : q.LM ∣ p.LM), reduction p q = r) → red_one_step p r def reducible (p : mv_polynomial σ α) := ∃ (q : mv_polynomial σ α) (hq₁ : q ∈ s) (hq₂ : q ≠ 0) (pₜ : σ →₀ ℕ) (hp : pₜ ∈ p.support), q.LM ∣ pₜ def is_red_rel (p r : mv_polynomial σ α) := ∃ (q : mv_polynomial σ α) (hq₁ : q ∈ s) (hq₂ : q ≠ 0) (pₜ : σ →₀ ℕ) (hp : pₜ ∈ p.support) (hqpₜ : q.LM ∣ pₜ), r = p - q * monomial (pₜ - q.LM) (p pₜ / q.LC) notation a `→[` S `]` b := red_one_step S a b notation a `↛[` S `]` b := ¬ red_one_step S a b def red_plus : mv_polynomial σ α → mv_polynomial σ α → Prop := rtc (red_one_step s) notation a `→[` S `]+` b := red_plus S a b notation a `↛[` S `]+` b := ¬ red_plus S a b def irreducible (p : mv_polynomial σ α) := ∀ (q : mv_polynomial σ α) (hq₁ : q ∈ s) (hq₂ : q ≠ 0) (pₜ ∈ p.support), q.LM ∤ pₜ notation a `→[` S `]*` b := red_plus S a b ∧ irreducible S b instance irreducible_decidable (p : mv_polynomial σ α) : decidable (irreducible s p) := finset.decidable_dforall_finset instance reducible_decidable (p : mv_polynomial σ α) : decidable (reducible s p) := finset.decidable_dexists_finset @[simp] lemma irred_not_red {p : mv_polynomial σ α} : irreducible s p ↔ ¬ reducible s p := by simp [irreducible, reducible] lemma red_not_irred {p : mv_polynomial σ α} : ¬ irreducible s p ↔ reducible s p := by simp [irred_not_red] lemma zero_irreducible : irreducible S 0 := by simp [irreducible] lemma zero_not_reducible : ¬ reducible S 0 := by rw ←irred_not_red; exact zero_irreducible lemma zero_not_is_red_rel : ∀ {r}, ¬ is_red_rel S 0 r := by simp [is_red_rel] lemma red_one_step_is_red_rel {p r : mv_polynomial σ α} : (p →[S] r) ↔ is_red_rel S p r := ⟨λ h, begin induction h with p r hp hpr₁ hpr₂ ih p r hp h, { rcases ih with ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ, h⟩, rw [←@add_left_cancel_iff _ _ p.LT, ←add_sub_assoc, LM_TL_eq p, hpr₂, LM_TL_eq r, TL_apply_mem hpₜ] at h, refine ⟨q, hq₁, hq₂, pₜ, TL_support_subset hpₜ, hqpₜ, h⟩, }, { rcases h with ⟨q, hq₁, hq₂, hpq, h⟩, refine ⟨q, hq₁, hq₂, p.LM, LM_mem_support hp, hpq, by rw ←h; refl⟩, } end, begin revert r, apply induction p, {intros r hr, apply absurd hr zero_not_is_red_rel}, { intros p ih r hr, rcases hr with ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ, h⟩, by_cases hpₜp : pₜ = p.LM, { apply red_one_step.red_LM (nez_of_mem_support hpₜ), refine ⟨q, hq₁, hq₂, by rwa ←hpₜp, by rw [h, hpₜp]; refl,⟩, }, { have hp_LM : p.LM > (-(q * monomial (pₜ - LM q) (p pₜ / LC q))).LM, { simp [LM_of_mul_m, hq₂, div_ne_zero (mem_support_iff.1 hpₜ) (LC_nez_iff.1 hq₂), add_sub_cancel' hqpₜ], apply lt_of_le_of_ne (LM_rel' hpₜ) hpₜp }, have hr : p.LT = r.LT := by simp [LT, h, LM_of_add_left hp_LM, LC_of_add_left hp_LM], apply red_one_step.cons (nez_of_mem_support hpₜ) (ih ⟨q, hq₁, hq₂, pₜ, mem_TL_support hpₜp hpₜ, hqpₜ, _⟩) hr, { rw [←@add_left_cancel_iff _ _ p.LT, ←add_sub_assoc, LM_TL_eq p, hr, LM_TL_eq r, TL_apply pₜ], simpa [ne.symm hpₜp] using h, }, } } end⟩ lemma is_red_rel_reducible {p r : mv_polynomial σ α} (h : is_red_rel S p r) : reducible S p := begin rcases h with ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ, _⟩, refine ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ⟩, end lemma reducible_is_red_rel {p : mv_polynomial σ α} (h : reducible S p) : ∃ r, is_red_rel S p r := begin rcases h with ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ⟩, refine ⟨p - q * monomial (pₜ - q.LM) (p pₜ / q.LC), q, hq₁, hq₂, pₜ, hpₜ, hqpₜ, rfl⟩, end lemma zero_red {r : mv_polynomial σ α} : (0 : mv_polynomial σ α) ↛[s] r := λ h, zero_not_reducible (is_red_rel_reducible (by rwa red_one_step_is_red_rel at h)) lemma red_mem_S {q : mv_polynomial σ α} (hq₁ : q ∈ S) (hq₂ : q ≠ 0) : q →[S] 0 := begin rw red_one_step_is_red_rel, refine ⟨q, hq₁, hq₂, q.LM, LM_mem_support hq₂, by simp, _⟩, have h₁ : q q.LM = q.LC := rfl, have h₂ : (monomial 0 1 : mv_polynomial σ α) = C 1 := by simp [C], simp [h₁, div_self (LC_nez_iff.1 hq₂), h₂], end theorem red_plus_mul {p r : mv_polynomial σ α} (h : p →[S]+ r) : ∀ a b, (monomial a b * p) →[S]+ (monomial a b * r) := begin intros a b, by_cases hb : b = 0, {simp [hb], exact rtc.refl'}, { revert a b, induction h with p p r h p q r hpq hqr ih₁ ih₂; intros a b hb, {exact rtc.refl'}, { apply rtc.base', rw red_one_step_is_red_rel at h ⊢, rcases h with ⟨q, hq₁, hq₂, pₜ, hp, hpq, h⟩, refine ⟨q, hq₁, hq₂, a + pₜ, mul_mem_mul_support hb _ hp, dvd_of_dvd_of_add' hpq _, by rw [mul_apply hp, finsupp.add_sub_assoc' hpq, mul_div_assoc, ←monomial_mul_monomial, mul_left_comm, ←mul_sub, h]⟩, }, {exact rtc.trans' (ih₁ a b hb) (ih₂ a b hb)} } end lemma red_plus_zero_of_mul {p : mv_polynomial σ α} (h : p →[S]+ 0) : ∀ a b, (monomial a b * p) →[S]+ 0 := by simpa using red_plus_mul h lemma red_star_zero_of_mul {p : mv_polynomial σ α} (h : p →[S]* 0) : ∀ a b, (monomial a b * p) →[S]* 0 := λ a b, ⟨red_plus_zero_of_mul h.left a b, zero_irreducible⟩ lemma lt_of_red_one_step {p r : mv_polynomial σ α} (h : p →[S] r) : r < p := begin induction h with p r hp h₁ h₂ ih p r hp h, {apply lt.LM_eq hp h₂.symm ih}, { rcases h with ⟨q, h₁, h₂, h₃, h₄⟩, rw ←h₄, by_cases hp' : p.LM = 0, { simp [hp'] at h₃, rw reduction_of_LM_eqz hp' h₃ h₂, apply lt.zero hp, }, {apply lt.LM_lt (reduction_LM_lt h₃ hp' h₂)} } end lemma le_of_red_plus {p r : mv_polynomial σ α} (h : p →[S]+ r) : r < p ∨ r = p := begin induction h with _ _ _ h p q r hpq hqr ih₁ ih₂, {simp}, {left, apply lt_of_red_one_step h}, { cases ih₁; cases ih₂, {left, exact trans ih₂ ih₁}, {left, rwa ih₂}, {left, rwa ←ih₁}, {right, rwa ih₂}, } end lemma red_lt_of_le_of_lt {p q r : mv_polynomial σ α} (hpq : p →[S] q) (hqr : q →[S]+ r) : r < p := begin cases le_of_red_plus hqr, {exact trans h (lt_of_red_one_step hpq)}, {simpa [h] using lt_of_red_one_step hpq} end lemma red_lt_of_le_of_lt' {p q r : mv_polynomial σ α} (hpq : p →[S] q) (hqr : q →[S]* r) : r < p := red_lt_of_le_of_lt hpq hqr.left lemma red_one_step_LM_ge {p r : mv_polynomial σ α} (h : p →[S] r) : p.LM ≥ r.LM := LM_le_of_lt (lt_of_red_one_step h) lemma red_plus_LM_ge {p r : mv_polynomial σ α} (h : p →[S]+ r) : p.LM ≥ r.LM := begin induction h with _ _ _ h _ _ _ _ _ ih₁ ih₂, {exact le_refl _}, {exact red_one_step_LM_ge h}, {exact ge_trans ih₁ ih₂}, end lemma red_plus_irreducible {p q : mv_polynomial σ α} (hp : irreducible S p) (h : p →[S]+ q) : q = p := begin induction h with _ p q h p q r hpq hpr ih₁ ih₂, {refl}, {apply absurd (is_red_rel_reducible (by rwa red_one_step_is_red_rel at h)) (by simpa using hp)}, {simpa [ih₁ hp, hp] using ih₂}, end theorem red_star_irreducible {p q : mv_polynomial σ α} (hp : irreducible S p) (h : p →[S]* q) : q = p := red_plus_irreducible hp h.left lemma red_const {p r : mv_polynomial σ α} (hp : p.LM = 0) (h : p →[S] r) : r = 0 := begin cases h with _ _ _ h _ _ _ hp' h, {apply absurd (by rwa TL_eqz_of_LM_eqz hp at h) (zero_red _)}, { rcases h with ⟨q, h₁, h₂, h₃, h₄⟩, simp [hp] at h₃, rw ←h₄, exact reduction_of_LM_eqz hp h₃ h₂, } end lemma red_plus_const {p r : mv_polynomial σ α} (hp : p.LM = 0) (h : p →[S]+ r) : p = r ∨ r = 0 := begin induction h with _ p r h p q r hpq hqr ih₁ ih₂, {simp}, {simp [red_const hp h]}, { cases ih₁ hp, { rw ←h at ih₂, exact ih₂ hp, }, { right, conv at ih₂ in (_ ∨ _) {rw eq_comm}, simpa [h] using ih₂, } } end lemma red_star_const {p r : mv_polynomial σ α} (hp : p.LM = 0) (h : p →[S]* r) : p = r ∨ r = 0 := red_plus_const hp h.left lemma red_plus_trans {p r : mv_polynomial σ α} (h : p →[S]+ r) : p ≠ r → ∃ q, (p →[S] q) ∧ (q →[S]+ r) := begin induction h with _ p₂ r₂ h p₃ q₃ r₃ h₁ h₂ ih₁ ih₂, {simp}, {intro, use [r₂, h, rtc.refl']}, { by_cases p₃ = q₃, {rwa h}, { intro, rcases ih₁ h with ⟨t, ht₁, ht₂⟩, use [t, ht₁, rtc.trans' ht₂ h₂], } } end lemma red_star_trans {p r : mv_polynomial σ α} (h : p →[S]* r) : reducible S p → ∃ q, (p →[S] q) ∧ (q →[S]* r) := λ hp, by simpa [h.right] using red_plus_trans h.left (λ hpr, ((irred_not_red S).1 h.right) (by rwa hpr at hp)) lemma exists_red_star (p : mv_polynomial σ α) : ∃ r, p →[s]* r := @well_founded.recursion (mv_polynomial σ α) (<) lt_wf _ p (begin intros p ih, by_cases hp : irreducible s p, {use [p, rtc.refl', hp]}, { cases reducible_is_red_rel (by rwa ←red_not_irred) with q hq, rw ←red_one_step_is_red_rel at hq, rcases ih q (lt_of_red_one_step hq) with ⟨r, hr₁, hr₂⟩, refine ⟨r, rtc.base_trans hq hr₁, hr₂⟩, } end) lemma exists_red_star_of_red {p q : mv_polynomial σ α} (h : p →[S] q) : ∃ r, (q →[S]* r) ∧ (p →[S]* r) := begin rcases exists_red_star S q with ⟨r, hr₁, hr₂⟩, refine ⟨r, ⟨hr₁, hr₂⟩, ⟨rtc.base_trans h hr₁, hr₂⟩⟩, end lemma exists_red_star_of_red_plus {p q : mv_polynomial σ α} (h : p →[S]+ q) : ∃ r, (q →[S]* r) ∧ (p →[S]* r) := begin induction h with p p q h p₃ q₃ r₃ hpq hqr ih₁ ih₂, { cases exists_red_star S p with r h, use [r, h, h], }, {exact exists_red_star_of_red h}, { rcases ih₂ with ⟨r, hr₁, ⟨hr₂, hr₃⟩⟩, use [r, hr₁, ⟨rtc.trans' hpq hr₂, hr₃⟩], } end lemma red_m_not_mem {p q r : mv_polynomial σ α} (hq : q ≠ 0) {pₜ} (hpₜ : pₜ ∈ p.support) (hqpₜ : q.LM ∣ pₜ) (h : r = p - q * monomial (pₜ - q.LM) (p pₜ / q.LC)) : pₜ ∉ r.support := begin have h_LC : (q * monomial (pₜ - LM q) (p pₜ / LC q)) pₜ = (q * monomial (pₜ - LM q) (p pₜ / LC q)).LC, have h₁ : p pₜ / q q.LM ≠ 0 := div_ne_zero (by simpa using hpₜ) (LC_nez_iff.1 hq), simp [LC, LM_of_mul_m, hq, h₁, finsupp.add_sub_cancel' hqpₜ], refl, simp [h, h_LC, LC_of_mul_m, mul_div_cancel' _ (LC_nez_iff.1 hq)], end lemma sub_red_comp {p r : mv_polynomial σ α} (h : p →[S] r) : ∀ u, ∃ t₁ t₂, (p + u →[S]+ t₁) ∧ (u →[S]+ t₂) ∧ (r = t₁ - t₂) := λ u, begin rcases red_one_step_is_red_rel.1 h with ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ, h⟩, have hr := red_m_not_mem hq₂ hpₜ hqpₜ h, by_cases hpₜu : pₜ ∈ u.support; simp at hpₜu hr hpₜ, { by_cases hpₜ': pₜ ∈ (p + u).support, { refine ⟨p + u - q * monomial (pₜ - LM q) ((p + u) pₜ / LC q), u - q * monomial (pₜ - LM q) (u pₜ / LC q), rtc.base' (red_one_step_is_red_rel.2 ⟨q, hq₁, hq₂, pₜ, hpₜ', hqpₜ, rfl⟩), rtc.base' (red_one_step_is_red_rel.2 ⟨q, hq₁, hq₂, pₜ, by simpa using hpₜu, hqpₜ, rfl⟩), _⟩, { simp [-mul_neg_eq_neg_mul_symm, neg_mul_eq_mul_neg], rw [←mul_add, ←monomial_neg, ←neg_div, ←monomial_add_monomial, div_add_div_same, neg_add_rev, ←add_assoc], simp [neg_div, h], } }, { simp [add_eq_zero_iff_neg_eq] at hpₜ', refine ⟨p + u, u - q * monomial (pₜ - LM q) (u pₜ / LC q), rtc.refl', rtc.base' (red_one_step_is_red_rel.2 ⟨q, hq₁, hq₂, pₜ, by simpa using hpₜu, hqpₜ, rfl⟩), by simp [hpₜ'.symm, neg_div, h]⟩, } }, { refine ⟨p + u - q * monomial (pₜ - q.LM) ((p + u) pₜ/ q.LC), u, rtc.base' (red_one_step_is_red_rel.2 ⟨q, hq₁, hq₂, pₜ, by simpa [hpₜu] using hpₜ, hqpₜ, rfl⟩), rtc.refl', by simp [hpₜu, h]⟩, } end lemma sub_red_plus_comp {p r : mv_polynomial σ α} (h : p →[S]+ r) : ∀ u, ∃ t, (p + u →[S]+ r + t) ∧ (u →[S]+ t) := begin induction h with r p r h p q r hpq hqr ih₁ ih₂; intros u, {refine ⟨u, rtc.refl', rtc.refl'⟩}, { rcases sub_red_comp h u with ⟨t₁, t₂, h₁, h₂, h₃⟩, refine ⟨t₂, by rwa eq_sub_iff_add_eq.1 h₃, h₂⟩, }, { rcases ih₁ u with ⟨t₁, hput₁, hut₁⟩, rcases ih₂ t₁ with ⟨t₂, hqut₂, hut₂⟩, refine ⟨t₂, rtc.trans' hput₁ hqut₂, rtc.trans' hut₁ hut₂⟩, } end lemma sub_red_star_zero {p q : mv_polynomial σ α} (h : p - q →[S]* 0) : ∃ t, (p →[S]* t) ∧ (q →[S]* t) := begin rcases sub_red_plus_comp h.left q with ⟨r, hpr, hqr⟩, rcases exists_red_star S r with ⟨t, ht₁, ht₂⟩, refine ⟨t, ⟨rtc.trans' (by simpa using hpr) ht₁, ht₂⟩, ⟨rtc.trans' hqr ht₁, ht₂⟩⟩, end lemma red_add_of_red {p r : mv_polynomial σ α} (h : p →[S] r) : ∀ u, ∃ t, (p + u →[S]+ t) ∧ (r + u →[S]+ t) := λ u, begin rcases red_one_step_is_red_rel.1 h with ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ, h⟩, have hr := red_m_not_mem hq₂ hpₜ hqpₜ h, by_cases hpₜu : pₜ ∈ u.support; simp at hpₜu hr, { by_cases hpₜ': pₜ ∈ (p + u).support, { refine ⟨r + u - q * monomial (pₜ - LM q) (u pₜ / LC q), _, _⟩; apply rtc.base'; rw [red_one_step_is_red_rel], { conv at h { rw [←@add_right_cancel_iff _ _ (u - q * monomial (pₜ - q.LM) (u pₜ / q.LC)), ←add_sub_assoc], to_rhs, rw [←add_sub_assoc, sub_add_eq_add_sub, sub_sub, ←mul_add, ←monomial_add_monomial, div_add_div_same, ←add_apply], }, refine ⟨q, hq₁, hq₂, pₜ, hpₜ', hqpₜ, by rw h⟩, }, {refine ⟨q, hq₁, hq₂, pₜ, by simpa [hr] using hpₜu, hqpₜ, by conv in ((r + u) pₜ) {simp [hr]},⟩} }, { refine ⟨p + u, rtc.refl', _⟩, apply rtc.base', rw red_one_step_is_red_rel, refine ⟨q, hq₁, hq₂, pₜ, by simpa [hr] using hpₜu, hqpₜ, _⟩, simp [add_eq_zero_iff_eq_neg] at hpₜ', simp [h, hpₜ', neg_div, hr], } }, { refine ⟨r + u, _, rtc.refl'⟩, apply rtc.base', rw [red_one_step_is_red_rel, h, sub_add_eq_add_sub], refine ⟨q, hq₁, hq₂, pₜ, by simpa [hpₜu] using hpₜ, hqpₜ, by simp [hpₜu]⟩, } end lemma red_of_TL_red {p r : mv_polynomial σ α} (h : p.TL →[S] r) : p →[S] p.LT + r := begin by_cases hp : p.LM = 0, { rw [TL_eqz_of_LM_eqz hp] at h, apply absurd h (zero_red _), }, { have hpr := gt_of_gt_of_ge (gt_TL_LM_of_LM_nez hp) (red_one_step_LM_ge h), apply red_one_step.cons (nez_of_LM_nez hp) (by rwa ←TL_of_add_gt_LM hpr (LC_nez_of_LM_nez hp) at h), simp [LT_of_add_right (by rwa eq_LM_of_monomial p.LM (LC_nez_of_LM_nez hp) at hpr)], refl, } end lemma red_plus_TL_plus {p r : mv_polynomial σ α} (h : p.TL →[S]+ r) : p →[S]+ p.LT + r := begin conv in p {rw ←LM_TL_eq p}, by_cases hp : p.LM = 0, { rw [TL_eqz_of_LM_eqz hp] at h ⊢, have hr : r = 0, by_contradiction hr, rcases red_plus_trans h (ne.symm hr) with ⟨_, hq, _⟩, exact (zero_red _) hq, simpa [hr] using rtc.refl', }, { have := gt_TL_LM_of_LM_nez hp, revert this, induction h with _ p' r' h p' q' r' hpq hqr ih₁ ih₂; intro hp', {exact rtc.refl'}, { have := red_of_TL_red (by rwa ←TL_of_add_gt_LM hp' (LC_nez_of_LM_nez hp) at h), rw LT_of_add_gt_LM hp' (LC_nez_of_LM_nez hp) at this, apply rtc.base' this, }, {exact rtc.trans' (ih₁ hp') (ih₂ (lt_of_le_of_lt (red_plus_LM_ge hpq) hp'))} } end lemma red_plus_TL_star {p r : mv_polynomial σ α} (h : p.TL →[S]* r) : p →[S]+ p.LT + r := red_plus_TL_plus h.left lemma LM_eq_lt_of_lt_TL {p q : mv_polynomial σ α} (h : q < p.TL) : p.LT + q < p := begin by_cases hp₁ : p.LM = 0, { simp [TL_eqz_of_LM_eqz hp₁] at h, apply absurd h not_lt_zero, }, { have hp₂ := nez_of_LM_nez hp₁, have hp₃ := LC_nez_iff.1 hp₂, have hq : p.LM > q.LM := lt_of_le_of_lt (LM_le_of_lt h) (gt_TL_LM_of_LM_nez hp₁), apply lt.LM_eq hp₂, { conv at hq in p.LM {rw ←LM_of_LT}, rw LT_of_add_left hq, conv in (p.LT.LT) {rw LT, simp}, refl, }, {rwa [LT, TL_of_add_gt_LM hq hp₃]}, } end lemma red_cons_reduction {p r : mv_polynomial σ α} (hpq₁ : p.TL →[S] r.TL) (hpq₂ : p.LT = r.LT) : ∀ q, ∃ u, (reduction p q →[S]* u) ∧ (reduction r q →[S]* u) := λ q, begin have hpr : (p →[S] r) := by simpa [hpq₂, LM_TL_eq r] using red_of_TL_red hpq₁, rcases red_add_of_red hpr (-q * monomial (p.LM - q.LM) (p.LC/q.LC)) with ⟨u, hpu, hru⟩, rcases exists_red_star S u with ⟨u', hu'₁, hu'₂⟩, refine ⟨u', ⟨rtc.trans' (by simpa [reduction] using hpu) hu'₁, hu'₂⟩, ⟨rtc.trans' (by simpa [reduction, LM_eq_of_LT_eq hpq₂, LC_eq_of_LT_eq hpq₂] using hru) hu'₁, hu'₂⟩⟩, end theorem red_confluent (h : ∀ {p q} (hp : p ∈ S) (hq : q ∈ S), s_poly p q →[S]* 0) (p : mv_polynomial σ α) : ∀ {r t}, (p →[S]* r) → (p →[S]* t) → r = t := well_founded.recursion lt_wf p begin intros p ih r t hpr hpt, by_cases hp₁ : irreducible S p, {simp [red_star_irreducible hp₁ hpr, red_star_irreducible hp₁ hpt]}, { by_cases hp₂ : p.LM = 0, { cases red_star_const hp₂ hpr, { rw h_1 at hp₁, cases hpr with _ hpr, apply absurd hpr hp₁, }, { cases red_star_const hp₂ hpt, { rw h_2 at hp₁, cases hpt with _ hpt, apply absurd hpt hp₁, }, {rw [h_1, h_2]} } }, { rcases red_star_trans hpr (by simpa using hp₁) with ⟨q₁, hpq₁, hq₁r⟩, rcases red_star_trans hpt (by simpa using hp₁) with ⟨q₂, hpq₂, hq₂t⟩, have hpq₁_lt := lt_of_red_one_step hpq₁, have hpq₂_lt := lt_of_red_one_step hpq₂, cases hqr : hpq₁ with a b hp₃ hpq₁₁ hpq₁₂ _ _ hp₃ hr_pq₁; cases hqt : hpq₂ with _ _ hp₃ hpq₂₁ hpq₂₂ _ _ hp₃ hr_pq₂; clear hp₃ hqr hqt _x _x_1, { rcases exists_red_star_of_red hpq₁₁ with ⟨r'₁, hqr'₁, hpr'₁⟩, rcases exists_red_star_of_red hpq₂₁ with ⟨t'₁, hqt'₁, hpt'₁⟩, have hrt₁: r'₁ = t'₁ := ih _ (TL_lt hp₃) hpr'₁ hpt'₁, rcases exists_red_star_of_red_plus (red_plus_TL_star hqr'₁) with ⟨r'₂, hqr'₁₂, hqr'₂⟩, rcases exists_red_star_of_red_plus (red_plus_TL_star hqt'₁) with ⟨t'₂, hqt'₁₂, hqt'₂⟩, have hrt₂: r'₂ = t'₂ := ih (p.LT + t'₁) (LM_eq_lt_of_lt_TL (red_lt_of_le_of_lt' hpq₂₁ hqt'₁)) (by simpa [hrt₁, hpq₁₂] using hqr'₁₂) (by simpa [hpq₂₂] using hqt'₁₂), simpa [ih _ hpq₁_lt hq₁r hqr'₂, ih _ hpq₂_lt hq₂t hqt'₂] using hrt₂, }, { rcases hr_pq₂ with ⟨q, h₁, h₂, h₃, h₄⟩, rcases red_cons_reduction hpq₁₁ hpq₁₂ q with ⟨u, hq₂u, hq₁u⟩, rw h₄ at hq₂u, have hq₁u' : (q₁ →[S]* u) := ⟨rtc.base_trans (red_one_step.red_LM (nez_of_LM_nez (by rwa [←LM_eq_of_LT_eq hpq₁₂])) ⟨q, h₁, h₂, by rwa ←LM_eq_of_LT_eq hpq₁₂, rfl⟩) hq₁u.left, hq₁u.right⟩, simp [ih _ hpq₁_lt hq₁r hq₁u', ih _ hpq₂_lt hq₂t hq₂u], }, { rcases hr_pq₁ with ⟨q, h₁, h₂, h₃, h₄⟩, rcases red_cons_reduction hpq₂₁ hpq₂₂ q with ⟨u, hq₁u, hq₂u⟩, rw h₄ at hq₁u, have hq₂u' : (q₂ →[S]* u) := ⟨rtc.base_trans (red_one_step.red_LM (nez_of_LM_nez (by rwa [←LM_eq_of_LT_eq hpq₂₂])) ⟨q, h₁, h₂, by rwa ←LM_eq_of_LT_eq hpq₂₂, rfl⟩) hq₂u.left, hq₂u.right⟩, simp [ih _ hpq₁_lt hq₁r hq₁u, ih _ hpq₂_lt hq₂t hq₂u'], }, { rcases hr_pq₁ with ⟨q₁', hq₁₁, hq₁₂, hq₁₃, hq₁₄⟩, rcases hr_pq₂ with ⟨q₂', hq₂₁, hq₂₂, hq₂₃, hq₂₄⟩, cases exists_eq_mul_left_of_dvd (lcm_dvd hq₁₃ hq₂₃) with m hq₃, have hq : ((q₁ - q₂) →[S]* 0), { have h_s : s_poly q₂' q₁' = (q₂' * monomial (m_lcm q₁'.LM q₂'.LM - q₂'.LM) q₂'.LC⁻¹) + -(q₁' * monomial (m_lcm q₁'.LM q₂'.LM - q₁'.LM) q₁'.LC⁻¹), simp [s_poly, mul_comm, m_lcm_comm q₁'.LM q₂'.LM], simp [hq₁₄.symm, hq₂₄.symm, reduction, hq₃, add_sub_assoc', finsupp.dvd_lcm_right, finsupp.dvd_lcm_left, div_eq_mul_one_div p.LC, monomial_mul_monomial.symm, mul_left_comm _ (monomial m p.LC)], rw [neg_mul_eq_mul_neg, ←mul_add, ←h_s], refine ⟨red_plus_zero_of_mul (h hq₂₁ hq₁₁).left _ _, zero_not_reducible⟩, }, rcases sub_red_star_zero hq with ⟨u, hq₁u, hq₂u⟩, simp [ih _ hpq₁_lt hq₁r hq₁u, ih _ hpq₂_lt hq₂t hq₂u], } } } end lemma red_plus_insert {p r : mv_polynomial σ α} (h : p →[S]+ r) : ∀ a, p →[insert a S]+ r := begin induction h with _ p r h p q r hpq hqr ih₁ ih₂; intro a, {exact rtc.refl'}, { apply rtc.base', rw red_one_step_is_red_rel at h ⊢, rcases h with ⟨q, hq₁, hq₂, pₜ, hpₜ, hqpₜ, h⟩, refine ⟨q, by simp [hq₁], hq₂, pₜ, hpₜ, hqpₜ, h⟩, }, {exact rtc.trans' (ih₁ a) (ih₂ a)} end end reduction section step inductive buchstep : (list (mv_polynomial σ α) × list (mv_polynomial σ α) × list (mv_polynomial σ α)) → (list (mv_polynomial σ α) × list (mv_polynomial σ α) × list (mv_polynomial σ α)) → Prop | zero {p} : ∀ l₁ l₂ l₃, red_list p l₁ = 0 → buchstep ⟨l₁, p :: l₂, l₃⟩ ⟨l₁, l₂, l₃⟩ | non_zero {p} : ∀ l₁ l₂ l₃, red_list p l₁ ≠ 0 → buchstep ⟨l₁, p :: l₂, l₃⟩ ⟨(red_list p l₁) :: l₁, s_polyL (red_list p l₁) l₁ ++ l₂, s_polyL (red_list p l₁) l₁ ++ l₃⟩ def buchstep_plus : (list (mv_polynomial σ α) × list (mv_polynomial σ α) × list (mv_polynomial σ α)) → (list (mv_polynomial σ α) × list (mv_polynomial σ α) × list (mv_polynomial σ α)) → Prop := rtc buchstep lemma buchstep.zero' {p : mv_polynomial σ α} {l₁ l₂ l₃} (h : red_list p l₁ = 0) : buchstep ⟨l₁, p :: l₂, l₃⟩ ⟨l₁, l₂, l₃⟩ := buchstep.zero l₁ l₂ l₃ h lemma buchstep.non_zero' {p : mv_polynomial σ α} {l₁ l₂ l₃} (h : red_list p l₁ ≠ 0) : buchstep ⟨l₁, p :: l₂, l₃⟩ ⟨(red_list p l₁) :: l₁, s_polyL (red_list p l₁) l₁ ++ l₂, s_polyL (red_list p l₁) l₁ ++ l₃⟩ := buchstep.non_zero l₁ l₂ l₃ h lemma red_list_aux_red_plus_aux : ∀ (p : mv_polynomial σ α) {l₁ l₂ : list (mv_polynomial σ α)}, l₂ ⊆ l₁ → (p →[l₁.to_finset]+ red_list_aux p l₂) | p l₁ [] := by simp [red_list_aux]; exact rtc.refl' | p l₁ (q :: l₂) := λ h, begin by_cases hp : p = 0, {simp [hp, zero_red_list_aux], exact rtc.refl'}, { by_cases hqp : q.LM ∣ p.LM; simp [red_list_aux, hqp] at h ⊢, { by_cases hq : q = 0, { simp [reduction, hq], apply red_list_aux_red_plus_aux _ h.right, }, { apply rtc.base_trans (red_one_step.red_LM hp ⟨q, by simp [h.left], hq, hqp, rfl⟩) (red_list_aux_red_plus_aux (reduction p q) h.right), } }, {apply red_list_aux_red_plus_aux _ h.right} } end lemma red_list_aux_red_plus (p : mv_polynomial σ α) (l : list (mv_polynomial σ α)) : (p →[l.to_finset]+ red_list_aux p l) := red_list_aux_red_plus_aux p (by simp) lemma red_list_red_plus : ∀ (p : mv_polynomial σ α) (l : list (mv_polynomial σ α)), (p →[l.to_finset]+ red_list p l) | p l := begin unfold red_list, simp, by_cases hp₁ : red_list_aux p l = p; simp [hp₁], {exact rtc.refl'}, { by_cases hp₂ : p.LM = 0; simp [hp₂], { have h := red_plus_const hp₂ (red_list_aux_red_plus p l), simp [ne.symm hp₁] at h, simpa [h] using red_list_aux_red_plus p l, }, { let : (red_list_aux p l).LM < p.LM, from red_list_aux_LM_lt l p hp₂ hp₁, apply rtc.trans' (red_list_aux_red_plus p l) (red_list_red_plus _ l), } } end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, inv_image.wf (λ a, a.1.LM) _inst_6.wf⟩] , dec_tac := tactic.assumption } set_option class.instance_max_depth 50 lemma buchberger_buchplus : ∀ L : list (mv_polynomial σ α) × list (mv_polynomial σ α), buchstep_plus ⟨L.1, L.2, s_polys L.1⟩ ⟨buchberger ⟨L.1, L.2⟩, [], s_polys (buchberger ⟨L.1, L.2⟩)⟩ | ⟨l₁, []⟩ := by unfold buchberger; simp; apply rtc.refl' | ⟨l₁, (p :: l₂)⟩ := let lex := prod.lex ((>) : ideal (mv_polynomial σ α) → ideal (mv_polynomial σ α) → Prop) nat.lt in begin unfold buchberger, by_cases red_list p l₁ = 0; simp [h], { let : lex ⟨monomial_ideal l₁, l₂.length⟩ ⟨monomial_ideal l₁, (list.cons p l₂).length⟩ := by right; rw [list.length_cons]; apply nat.lt_succ_self, apply rtc.base_trans (buchstep.zero' h) (buchberger_buchplus ⟨l₁, l₂⟩), }, { let : lex ⟨monomial_ideal (list.cons (red_list p l₁) l₁), (s_polyL (red_list p l₁) l₁ ++ l₂).length⟩ ⟨monomial_ideal l₁, (list.cons p l₂).length⟩ := by left; exact ideal_increase l₁ p h, apply rtc.base_trans (buchstep.non_zero' h) (buchberger_buchplus ⟨red_list p l₁ :: l₁, s_polyL (red_list p l₁) l₁ ++ l₂⟩) } end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, inv_image.wf (λ ⟨l₁, l₂⟩, prod.mk (monomial_ideal l₁) l₂.length) (prod.lex_wf ideal_wf nat.lt_wf)⟩ ] , dec_tac := tactic.assumption } lemma buchstep_subset_or_red_eqz (L₁ L₂ : list (mv_polynomial σ α) × list (mv_polynomial σ α) × list (mv_polynomial σ α)) (h : buchstep_plus L₁ L₂) : (∀ a ∈ L₁.2.2, a ∈ L₁.2.1 ∨ (a →[L₁.1.to_finset]+ 0)) → ∀ a ∈ L₂.2.2, a ∈ L₂.2.1 ∨ (a →[L₂.1.to_finset]+ 0) := begin induction h with _ L₁ L₂ h L₁ L₂ L₃ h₁ h₂ ih₁ ih₂, {simp}, { cases h with p l₁ l₂ l₃ hp p l₁ l₂ l₃ hp, { simp_intros H a ha, rcases H a ha with ⟨h₁ | h₂⟩ | h₃, {right, simpa [hp, h₁] using red_list_red_plus p l₁}, {left, exact h₂}, {right, exact h₃}, }, { simp_intros H a' ha', cases ha', {simp [ha']}, { rcases H a' ha' with ⟨h₁ | h₂⟩ | h₃, { right, rw h₁, apply rtc.trans_base (red_plus_insert (red_list_red_plus p l₁) (red_list p l₁)), apply red_mem_S (finset.mem_insert_self _ _) hp, }, {simp [h₂]}, { right, apply red_plus_insert h₃, } } } }, { simp_intros H, exact ih₂ (ih₁ H), } end lemma s_poly_mem_s_polys : ∀ (l₁ l₂ : list (mv_polynomial σ α)), (∀ x : mv_polynomial σ α, x ∈ s_polys l₁ → (x →[l₂.to_finset]* 0)) → ∀ (p q : mv_polynomial σ α), p ∈ l₁ → q ∈ l₁ → (s_poly p q →[l₂.to_finset]* 0) | [] := by simp | (hd :: tl) := λ l₂ h p q hp hq, begin cases hp; cases hq, { simp [hp, hq, s_poly], refine ⟨rtc.refl', zero_not_reducible⟩, }, { apply h, simp [hp, s_polys, mem_s_polyL hq], }, { rw s_poly_comm, have H : (monomial 0 1 : mv_polynomial σ α) = C 1 := by simp [C], simpa [H] using red_star_zero_of_mul (h (s_poly q p) (by simp [s_polys, hq, mem_s_polyL hp])) 0 (-1), }, { apply s_poly_mem_s_polys tl _ (λ x hx, h x (by simp [s_polys, hx])) p q hp hq, } end lemma buch_confluent_aux (l : list (mv_polynomial σ α)) : ∀ (p q ∈ buchberger ⟨l, s_polys l⟩), (s_poly p q →[(buchberger ⟨l, s_polys l⟩).to_finset]* 0) := begin apply s_poly_mem_s_polys, simp [zero_not_reducible], have := buchstep_subset_or_red_eqz ⟨l, s_polys l, s_polys l⟩ ⟨buchberger ⟨l, s_polys l⟩, [], s_polys (buchberger ⟨l, s_polys l⟩)⟩ (buchberger_buchplus ⟨l, s_polys l⟩), simp at this, apply this, finish, end theorem buch_confluent (l : list (mv_polynomial σ α)) (p : mv_polynomial σ α) : ∀ {r t}, (p →[(buchberger ⟨l, s_polys l⟩).to_finset]* r) → (p →[(buchberger ⟨l, s_polys l⟩).to_finset]* t) → r = t := begin apply red_confluent, intros p q hp hq, apply buch_confluent_aux l p q (by simpa using hp) (by simpa using hq), end end step end buch
17263dadd09f5d4c8d21e9a0800687764f79b6f8
4727251e0cd73359b15b664c3170e5d754078599
/src/order/minimal.lean
0143de2bf631836f85044ff175f776901fc8c32b
[ "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
5,089
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.antichain /-! # Minimal/maximal elements of a set This file defines minimal and maximal of a set with respect to an arbitrary relation. ## Main declarations * `maximals r s`: Maximal elements of `s` with respect to `r`. * `minimals r s`: Minimal elements of `s` with respect to `r`. ## TODO Do we need a `finset` version? -/ open function set variables {α : Type*} (r r₁ r₂ : α → α → Prop) (s t : set α) (a : α) /-- Turns a set into an antichain by keeping only the "maximal" elements. -/ def maximals : set α := {a ∈ s | ∀ ⦃b⦄, b ∈ s → r a b → a = b} /-- Turns a set into an antichain by keeping only the "minimal" elements. -/ def minimals : set α := {a ∈ s | ∀ ⦃b⦄, b ∈ s → r b a → a = b} lemma maximals_subset : maximals r s ⊆ s := sep_subset _ _ lemma minimals_subset : minimals r s ⊆ s := sep_subset _ _ @[simp] lemma maximals_empty : maximals r ∅ = ∅ := sep_empty _ @[simp] lemma minimals_empty : minimals r ∅ = ∅ := sep_empty _ @[simp] lemma maximals_singleton : maximals r {a} = {a} := (maximals_subset _ _).antisymm $ singleton_subset_iff.2 $ ⟨rfl, λ b hb _, hb.symm⟩ @[simp] lemma minimals_singleton : minimals r {a} = {a} := maximals_singleton _ _ lemma maximals_swap : maximals (swap r) s = minimals r s := rfl lemma minimals_swap : minimals (swap r) s = maximals r s := rfl lemma maximals_antichain : is_antichain r (maximals r s) := λ a ha b hb hab h, hab $ ha.2 hb.1 h lemma minimals_antichain : is_antichain r (minimals r s) := (maximals_antichain _ _).swap lemma maximals_eq_minimals [is_symm α r] : maximals r s = minimals r s := by { congr, ext a b, exact comm } variables {r r₁ r₂ s t a} lemma set.subsingleton.maximals_eq (h : s.subsingleton) : maximals r s = s := h.induction_on (minimals_empty _) (maximals_singleton _) lemma set.subsingleton.minimals_eq (h : s.subsingleton) : minimals r s = s := h.maximals_eq lemma maximals_mono (h : ∀ a b, r₁ a b → r₂ a b) : maximals r₂ s ⊆ maximals r₁ s := λ a ha, ⟨ha.1, λ b hb, ha.2 hb ∘ h _ _⟩ lemma minimals_mono (h : ∀ a b, r₁ a b → r₂ a b) : minimals r₂ s ⊆ minimals r₁ s := λ a ha, ⟨ha.1, λ b hb, ha.2 hb ∘ h _ _⟩ lemma maximals_union : maximals r (s ∪ t) ⊆ maximals r s ∪ maximals r t := begin intros a ha, obtain h | h := ha.1, { exact or.inl ⟨h, λ b hb, ha.2 $ or.inl hb⟩ }, { exact or.inr ⟨h, λ b hb, ha.2 $ or.inr hb⟩ } end lemma minimals_union : minimals r (s ∪ t) ⊆ minimals r s ∪ minimals r t := maximals_union lemma maximals_inter_subset : maximals r s ∩ t ⊆ maximals r (s ∩ t) := λ a ha, ⟨⟨ha.1.1, ha.2⟩, λ b hb, ha.1.2 hb.1⟩ lemma minimals_inter_subset : minimals r s ∩ t ⊆ minimals r (s ∩ t) := maximals_inter_subset lemma inter_maximals_subset : s ∩ maximals r t ⊆ maximals r (s ∩ t) := λ a ha, ⟨⟨ha.1, ha.2.1⟩, λ b hb, ha.2.2 hb.2⟩ lemma inter_minimals_subset : s ∩ minimals r t ⊆ minimals r (s ∩ t) := inter_maximals_subset lemma _root_.is_antichain.maximals_eq (h : is_antichain r s) : maximals r s = s := (maximals_subset _ _).antisymm $ λ a ha, ⟨ha, λ b, h.eq ha⟩ lemma _root_.is_antichain.minimals_eq (h : is_antichain r s) : minimals r s = s := (minimals_subset _ _).antisymm $ λ a ha, ⟨ha, λ b, h.eq' ha⟩ @[simp] lemma maximals_idem : maximals r (maximals r s) = maximals r s := (maximals_antichain _ _).maximals_eq @[simp] lemma minimals_idem : minimals r (minimals r s) = minimals r s := maximals_idem /-- If `maximals r s` is included in but *shadows* the antichain `t`, then it is actually equal to `t`. -/ lemma is_antichain.max_maximals (ht : is_antichain r t) (h : maximals r s ⊆ t) (hs : ∀ ⦃a⦄, a ∈ t → ∃ b ∈ maximals r s, r b a) : maximals r s = t := begin refine h.antisymm (λ a ha, _), obtain ⟨b, hb, hr⟩ := hs ha, rwa of_not_not (λ hab, ht (h hb) ha (ne.symm hab) hr), end /-- If `minimals r s` is included in but *shadows* the antichain `t`, then it is actually equal to `t`. -/ lemma is_antichain.max_minimals (ht : is_antichain r t) (h : minimals r s ⊆ t) (hs : ∀ ⦃a⦄, a ∈ t → ∃ b ∈ minimals r s, r a b) : minimals r s = t := begin refine h.antisymm (λ a ha, _), obtain ⟨b, hb, hr⟩ := hs ha, rwa of_not_not (λ hab, ht ha (h hb) hab hr), end variables [partial_order α] lemma is_least.mem_minimals (h : is_least s a) : a ∈ minimals (≤) s := ⟨h.1, λ b hb, (h.2 hb).antisymm⟩ lemma is_greatest.mem_maximals (h : is_greatest s a) : a ∈ maximals (≤) s := ⟨h.1, λ b hb, (h.2 hb).antisymm'⟩ lemma is_least.minimals_eq (h : is_least s a) : minimals (≤) s = {a} := eq_singleton_iff_unique_mem.2 ⟨h.mem_minimals, λ b hb, hb.2 h.1 $ h.2 hb.1⟩ lemma is_greatest.maximals_eq (h : is_greatest s a) : maximals (≤) s = {a} := eq_singleton_iff_unique_mem.2 ⟨h.mem_maximals, λ b hb, hb.2 h.1 $ h.2 hb.1⟩
2eeed19110ff074048126b26f8d891836a866e94
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/special_functions/complex/arg.lean
bf39f95a2c34601f71a5f55dd9ed2cf5042e6035
[ "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,499
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.trigonometric.angle import analysis.special_functions.trigonometric.inverse /-! # The argument of a complex number. We define `arg : ℂ → ℝ`, returing a real number in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, while `arg 0` defaults to `0` -/ noncomputable theory namespace complex open_locale complex_conjugate real topological_space open filter set /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := begin have habs : 0 < abs x := abs_pos.2 hx, have him : |im x / abs x| ≤ 1, { rw [_root_.abs_div, abs_abs], exact div_le_one_of_le x.abs_im_le_abs x.abs_nonneg }, rw abs_le at him, rw arg, split_ifs with h₁ h₂ h₂, { rw [real.cos_arcsin]; field_simp [real.sqrt_sq, habs.le, *] }, { rw [real.cos_add_pi, real.cos_arcsin], { field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] }, { simpa [neg_div] using him.2 }, { simpa [neg_div, neg_le] using him.1 } }, { rw [real.cos_sub_pi, real.cos_arcsin], { field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] }, { simpa [neg_div] using him.2 }, { simpa [neg_div, neg_le] using him.1 } } end @[simp] lemma abs_mul_exp_arg_mul_I (x : ℂ) : ↑(abs x) * exp (arg x * I) = x := begin rcases eq_or_ne x 0 with (rfl|hx), { simp }, { have : abs x ≠ 0 := abs_ne_zero.2 hx, ext; field_simp [sin_arg, cos_arg hx, this, mul_comm (abs x)] } end @[simp] lemma abs_mul_cos_add_sin_mul_I (x : ℂ) : (abs x * (cos (arg x) + sin (arg x) * I) : ℂ) = x := by rw [← exp_mul_I, abs_mul_exp_arg_mul_I] @[simp] lemma range_exp_mul_I : range (λ x : ℝ, exp (x * I)) = metric.sphere 0 1 := begin simp only [metric.sphere, dist_eq, sub_zero], refine (range_subset_iff.2 $ λ x, _).antisymm (λ z (hz : abs z = 1), _), { exact abs_exp_of_real_mul_I _ }, { refine ⟨arg z, _⟩, calc exp (arg z * I) = abs z * exp (arg z * I) : by rw [hz, of_real_one, one_mul] ... = z : abs_mul_exp_arg_mul_I z } end lemma arg_mul_cos_add_sin_mul_I {r : ℝ} (hr : 0 < r) {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (r * (cos θ + sin θ * I)) = θ := begin have hπ := real.pi_pos, simp only [arg, abs_mul, abs_cos_add_sin_mul_I, abs_of_nonneg hr.le, mul_one], simp only [of_real_mul_re, of_real_mul_im, neg_im, ← of_real_cos, ← of_real_sin, ← mk_eq_add_mul_I, neg_div, mul_div_cancel_left _ hr.ne', mul_nonneg_iff_right_nonneg_of_pos hr], by_cases h₁ : θ ∈ Icc (-(π / 2)) (π / 2), { rw if_pos, exacts [real.arcsin_sin' h₁, real.cos_nonneg_of_mem_Icc h₁] }, { rw [mem_Icc, not_and_distrib, not_le, not_le] at h₁, cases h₁, { replace hθ := hθ.1, have hcos : real.cos θ < 0, { rw [← neg_pos, ← real.cos_add_pi], refine real.cos_pos_of_mem_Ioo ⟨_, _⟩; linarith }, have hsin : real.sin θ < 0 := real.sin_neg_of_neg_of_neg_pi_lt (by linarith) hθ, rw [if_neg, if_neg, ← real.sin_add_pi, real.arcsin_sin, add_sub_cancel]; [linarith, linarith, exact hsin.not_le, exact hcos.not_le] }, { replace hθ := hθ.2, have hcos : real.cos θ < 0 := real.cos_neg_of_pi_div_two_lt_of_lt h₁ (by linarith), have hsin : 0 ≤ real.sin θ := real.sin_nonneg_of_mem_Icc ⟨by linarith, hθ⟩, rw [if_neg, if_pos, ← real.sin_sub_pi, real.arcsin_sin, sub_add_cancel]; [linarith, linarith, exact hsin, exact hcos.not_le] } } end lemma arg_cos_add_sin_mul_I {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (cos θ + sin θ * I) = θ := by rw [← one_mul (_ + _), ← of_real_one, arg_mul_cos_add_sin_mul_I zero_lt_one hθ] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := by rw [← abs_mul_exp_arg_mul_I x, ← abs_mul_exp_arg_mul_I y, h₁, h₂] lemma ext_abs_arg_iff {x y : ℂ} : x = y ↔ abs x = abs y ∧ arg x = arg y := ⟨λ h, h ▸ ⟨rfl, rfl⟩, and_imp.2 ext_abs_arg⟩ lemma arg_mem_Ioc (z : ℂ) : arg z ∈ Ioc (-π) π := begin have hπ : 0 < π := real.pi_pos, rcases eq_or_ne z 0 with (rfl|hz), simp [hπ, hπ.le], rcases exists_unique_add_zsmul_mem_Ioc real.two_pi_pos (arg z) (-π) with ⟨N, hN, -⟩, rw [two_mul, neg_add_cancel_left, ← two_mul, zsmul_eq_mul] at hN, rw [← abs_mul_cos_add_sin_mul_I z, ← cos_add_int_mul_two_pi _ N, ← sin_add_int_mul_two_pi _ N], simp only [← of_real_one, ← of_real_bit0, ← of_real_mul, ← of_real_add, ← of_real_int_cast], rwa [arg_mul_cos_add_sin_mul_I (abs_pos.2 hz) hN] end @[simp] lemma range_arg : range arg = Ioc (-π) π := (range_subset_iff.2 arg_mem_Ioc).antisymm (λ x hx, ⟨_, arg_cos_add_sin_mul_I hx⟩) lemma arg_le_pi (x : ℂ) : arg x ≤ π := (arg_mem_Ioc x).2 lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := (arg_mem_Ioc x).1 @[simp] lemma arg_nonneg_iff {z : ℂ} : 0 ≤ arg z ↔ 0 ≤ z.im := begin rcases eq_or_ne z 0 with (rfl|h₀), { simp }, calc 0 ≤ arg z ↔ 0 ≤ real.sin (arg z) : ⟨λ h, real.sin_nonneg_of_mem_Icc ⟨h, arg_le_pi z⟩, by { contrapose!, intro h, exact real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_arg _) }⟩ ... ↔ _ : by rw [sin_arg, le_div_iff (abs_pos.2 h₀), zero_mul] end @[simp] lemma arg_neg_iff {z : ℂ} : arg z < 0 ↔ z.im < 0 := lt_iff_lt_of_le_iff_le arg_nonneg_iff lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := begin rcases eq_or_ne x 0 with (rfl|hx), { rw mul_zero }, conv_lhs { rw [← abs_mul_cos_add_sin_mul_I x, ← mul_assoc, ← of_real_mul, arg_mul_cos_add_sin_mul_I (mul_pos hr (abs_pos.2 hx)) x.arg_mem_Ioc] } end lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := begin simp only [ext_abs_arg_iff, abs_mul, abs_div, abs_of_real, abs_abs, div_mul_cancel _ (abs_ne_zero.2 hx), eq_self_iff_true, true_and], rw [← of_real_div, arg_real_mul], exact div_pos (abs_pos.2 hy) (abs_pos.2 hx) end @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] @[simp] lemma tan_arg (x : ℂ) : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] }, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right _ (abs_ne_zero.2 h)] end lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_eq_pi_iff {z : ℂ} : arg z = π ↔ z.re < 0 ∧ z.im = 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero.symm] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨h : x < 0, rfl : y = 0⟩, rw [← arg_neg_one, ← arg_real_mul (-1) (neg_pos.2 h)], simp [← of_real_def] } end lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := arg_eq_pi_iff.2 ⟨hx, rfl⟩ lemma arg_eq_pi_div_two_iff {z : ℂ} : arg z = π / 2 ↔ z.re = 0 ∧ 0 < z.im := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_div_two_pos.ne] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : 0 < y⟩, rw [← arg_I, ← arg_real_mul I hy, of_real_mul', I_re, I_im, mul_zero, mul_one] } end lemma arg_eq_neg_pi_div_two_iff {z : ℂ} : arg z = - (π / 2) ↔ z.re = 0 ∧ z.im < 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : y < 0⟩, rw [← arg_neg_I, ← arg_real_mul (-I) (neg_pos.2 hy), mk_eq_add_mul_I], simp } end lemma arg_of_re_nonneg {x : ℂ} (hx : 0 ≤ x.re) : arg x = real.arcsin (x.im / x.abs) := if_pos hx lemma arg_of_re_neg_of_im_nonneg {x : ℂ} (hx_re : x.re < 0) (hx_im : 0 ≤ x.im) : arg x = real.arcsin ((-x).im / x.abs) + π := by simp only [arg, hx_re.not_le, hx_im, if_true, if_false] lemma arg_of_re_neg_of_im_neg {x : ℂ} (hx_re : x.re < 0) (hx_im : x.im < 0) : arg x = real.arcsin ((-x).im / x.abs) - π := by simp only [arg, hx_re.not_le, hx_im.not_le, if_false] lemma arg_of_im_nonneg_of_ne_zero {z : ℂ} (h₁ : 0 ≤ z.im) (h₂ : z ≠ 0) : arg z = real.arccos (z.re / abs z) := by rw [← cos_arg h₂, real.arccos_cos (arg_nonneg_iff.2 h₁) (arg_le_pi _)] lemma arg_of_im_pos {z : ℂ} (hz : 0 < z.im) : arg z = real.arccos (z.re / abs z) := arg_of_im_nonneg_of_ne_zero hz.le (λ h, hz.ne' $ h.symm ▸ rfl) lemma arg_of_im_neg {z : ℂ} (hz : z.im < 0) : arg z = -real.arccos (z.re / abs z) := begin have h₀ : z ≠ 0, from mt (congr_arg im) hz.ne, rw [← cos_arg h₀, ← real.cos_neg, real.arccos_cos, neg_neg], exacts [neg_nonneg.2 (arg_neg_iff.2 hz).le, neg_le.2 (neg_pi_lt_arg z).le] end lemma arg_conj (x : ℂ) : arg (conj x) = if arg x = π then π else -arg x := begin simp_rw [arg_eq_pi_iff, arg, neg_im, conj_im, conj_re, abs_conj, neg_div, neg_neg, real.arcsin_neg, apply_ite has_neg.neg, neg_add, neg_sub, neg_neg, ←sub_eq_add_neg, sub_neg_eq_add, add_comm π], rcases lt_trichotomy x.re 0 with (hr|hr|hr); rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hr, hr.not_le, hi.le, hi.ne, not_le.2 hi] }, { simp [hr, hr.not_le, hi] }, { simp [hr, hr.not_le, hi.ne.symm, hi.le, not_le.2 hi] }, { simp [hr] }, { simp [hr] }, { simp [hr] }, { simp [hr, hr.le, hi.ne] }, { simp [hr, hr.le, hr.le.not_lt] }, { simp [hr, hr.le, hr.le.not_lt] }, end lemma arg_inv (x : ℂ) : arg x⁻¹ = if arg x = π then π else -arg x := begin rw [←arg_conj, inv_def, mul_comm], by_cases hx : x = 0, { simp [hx] }, { exact arg_real_mul (conj x) (by simp [hx]) } end @[simp] lemma arg_conj_coe_angle (x : ℂ) : (arg (conj x) : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_conj, h] end @[simp] lemma arg_inv_coe_angle (x : ℂ) : (arg x⁻¹ : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_inv, h] end lemma arg_neg_eq_arg_sub_pi_of_im_pos {x : ℂ} (hi : 0 < x.im) : arg (-x) = arg x - π := begin rw [arg_of_im_pos hi, arg_of_im_neg (show (-x).im < 0, from left.neg_neg_iff.2 hi)], simp [neg_div, real.arccos_neg] end lemma arg_neg_eq_arg_add_pi_of_im_neg {x : ℂ} (hi : x.im < 0) : arg (-x) = arg x + π := begin rw [arg_of_im_neg hi, arg_of_im_pos (show 0 < (-x).im, from left.neg_pos_iff.2 hi)], simp [neg_div, real.arccos_neg, add_comm, ←sub_eq_add_neg] end lemma arg_neg_eq_arg_sub_pi_iff {x : ℂ} : arg (-x) = arg x - π ↔ (0 < x.im ∨ x.im = 0 ∧ x.re < 0) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, hi.ne, hi.not_lt, arg_neg_eq_arg_add_pi_of_im_neg, sub_eq_add_neg, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr] }, { simp [hr, hi, real.pi_ne_zero] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr.not_lt, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] } }, { simp [hi, arg_neg_eq_arg_sub_pi_of_im_pos] } end lemma arg_neg_eq_arg_add_pi_iff {x : ℂ} : arg (-x) = arg x + π ↔ (x.im < 0 ∨ x.im = 0 ∧ 0 < x.re) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, arg_neg_eq_arg_add_pi_of_im_neg] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr.not_lt, ←two_mul, real.pi_ne_zero] }, { simp [hr, hi, real.pi_ne_zero.symm] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr] } }, { simp [hi, hi.ne.symm, hi.not_lt, arg_neg_eq_arg_sub_pi_of_im_pos, sub_eq_add_neg, ←add_eq_zero_iff_neg_eq, real.pi_ne_zero] } end lemma arg_neg_coe_angle {x : ℂ} (hx : x ≠ 0) : (arg (-x) : real.angle) = arg x + π := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { rw [arg_neg_eq_arg_add_pi_of_im_neg hi, real.angle.coe_add] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le, ←real.angle.coe_add, ←two_mul, real.angle.coe_two_pi, real.angle.coe_zero] }, { exact false.elim (hx (ext hr hi)) }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr), real.angle.coe_zero, zero_add] } }, { rw [arg_neg_eq_arg_sub_pi_of_im_pos hi, real.angle.coe_sub, real.angle.sub_coe_pi_eq_add_coe_pi] } end section continuity variables {x z : ℂ} lemma arg_eq_nhds_of_re_pos (hx : 0 < x.re) : arg =ᶠ[𝓝 x] λ x, real.arcsin (x.im / x.abs) := ((continuous_re.tendsto _).eventually (lt_mem_nhds hx)).mono $ λ y hy, arg_of_re_nonneg hy.le lemma arg_eq_nhds_of_re_neg_of_im_pos (hx_re : x.re < 0) (hx_im : 0 < x.im) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) + π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ 0 < y.im, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_nonneg hy.1 hy.2.le), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ 0 < x.im), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_zero continuous_im), end lemma arg_eq_nhds_of_re_neg_of_im_neg (hx_re : x.re < 0) (hx_im : x.im < 0) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) - π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ y.im < 0, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_neg hy.1 hy.2), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ x.im < 0), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_im continuous_zero), end lemma arg_eq_nhds_of_im_pos (hz : 0 < im z) : arg =ᶠ[𝓝 z] λ x, real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (lt_mem_nhds hz)).mono $ λ x, arg_of_im_pos lemma arg_eq_nhds_of_im_neg (hz : im z < 0) : arg =ᶠ[𝓝 z] λ x, -real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (gt_mem_nhds hz)).mono $ λ x, arg_of_im_neg lemma continuous_at_arg (h : 0 < x.re ∨ x.im ≠ 0) : continuous_at arg x := begin have h₀ : abs x ≠ 0, { rw abs_ne_zero, rintro rfl, simpa using h }, rw [← lt_or_lt_iff_ne] at h, rcases h with (hx_re|hx_im|hx_im), exacts [(real.continuous_at_arcsin.comp (continuous_im.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_re_pos hx_re).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).neg.congr (arg_eq_nhds_of_im_neg hx_im).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_im_pos hx_im).symm] end lemma tendsto_arg_nhds_within_im_neg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)) := begin suffices H : tendsto (λ x : ℂ, real.arcsin ((-x).im / x.abs) - π) (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)), { refine H.congr' _, have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_neg him.not_le], }, convert (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).sub tendsto_const_nhds, { simp [him] }, { lift z to ℝ using him, simpa using hre.ne } end lemma continuous_within_at_arg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : continuous_within_at arg {z : ℂ | 0 ≤ z.im} z := begin have : arg =ᶠ[𝓝[{z : ℂ | 0 ≤ z.im}] z] λ x, real.arcsin ((-x).im / x.abs) + π, { have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_pos him] }, refine continuous_within_at.congr_of_eventually_eq _ this _, { refine (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).add tendsto_const_nhds, lift z to ℝ using him, simpa using hre.ne }, { rw [arg, if_neg hre.not_le, if_pos him.ge] } end lemma tendsto_arg_nhds_within_im_nonneg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | 0 ≤ z.im}] z) (𝓝 π) := by simpa only [arg_eq_pi_iff.2 ⟨hre, him⟩] using (continuous_within_at_arg_of_re_neg_of_im_zero hre him).tendsto end continuity end complex
ff67a4be006296e0968b806d5bc5ce8ee1db30a5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/sigma/basic_auto.lean
cae93934383c5986f8d856e453e2b9b59e6efacb
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
12,004
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.natural_isomorphism import Mathlib.category_theory.eq_to_hom import Mathlib.data.sigma.basic import Mathlib.category_theory.pi.basic import Mathlib.PostPort universes w₁ v₁ u₁ l u₂ v₂ w₂ w₃ namespace Mathlib /-! # Disjoint union of categories We define the category structure on a sigma-type (disjoint union) of categories. -/ namespace category_theory namespace sigma /-- The type of morphisms of a disjoint union of categories: for `X : C i` and `Y : C j`, a morphism `(i, X) ⟶ (j, Y)` if `i = j` is just a morphism `X ⟶ Y`, and if `i ≠ j` there are no such morphisms. -/ inductive sigma_hom {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] : (sigma fun (i : I) => C i) → (sigma fun (i : I) => C i) → Type (max w₁ v₁ u₁) where | mk : {i : I} → {X Y : C i} → (X ⟶ Y) → sigma_hom (sigma.mk i X) (sigma.mk i Y) namespace sigma_hom /-- The identity morphism on an object. -/ def id {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) : sigma_hom X X := sorry protected instance inhabited {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) : Inhabited (sigma_hom X X) := { default := id X } /-- Composition of sigma homomorphisms. -/ def comp {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {X : sigma fun (i : I) => C i} {Y : sigma fun (i : I) => C i} {Z : sigma fun (i : I) => C i} : sigma_hom X Y → sigma_hom Y Z → sigma_hom X Z := sorry protected instance sigma.category_theory.category_struct {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] : category_struct (sigma fun (i : I) => C i) := category_struct.mk id fun (X Y Z : sigma fun (i : I) => C i) (f : X ⟶ Y) (g : Y ⟶ Z) => comp f g @[simp] theorem comp_def {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) (X : C i) (Y : C i) (Z : C i) (f : X ⟶ Y) (g : Y ⟶ Z) : comp (mk f) (mk g) = mk (f ≫ g) := rfl theorem assoc {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) (Z : sigma fun (i : I) => C i) (W : sigma fun (i : I) => C i) (f : X ⟶ Y) (g : Y ⟶ Z) (h : Z ⟶ W) : (f ≫ g) ≫ h = f ≫ g ≫ h := sorry theorem id_comp {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) (f : X ⟶ Y) : 𝟙 ≫ f = f := sorry theorem comp_id {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) (f : X ⟶ Y) : f ≫ 𝟙 = f := sorry end sigma_hom protected instance sigma {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] : category (sigma fun (i : I) => C i) := category.mk /-- The inclusion functor into the disjoint union of categories. -/ @[simp] theorem incl_map {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) (X : C i) (Y : C i) : ∀ (ᾰ : X ⟶ Y), functor.map (incl i) ᾰ = sigma_hom.mk ᾰ := fun (ᾰ : X ⟶ Y) => Eq.refl (functor.map (incl i) ᾰ) @[simp] theorem incl_obj {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {i : I} (X : C i) : functor.obj (incl i) X = sigma.mk i X := rfl protected instance incl.category_theory.full {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) : full (incl i) := full.mk fun (X Y : C i) (_x : functor.obj (incl i) X ⟶ functor.obj (incl i) Y) => sorry protected instance incl.category_theory.faithful {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) : faithful (incl i) := faithful.mk /-- To build a natural transformation over the sigma category, it suffices to specify it restricted to each subcategory. -/ def nat_trans {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] {F : (sigma fun (i : I) => C i) ⥤ D} {G : (sigma fun (i : I) => C i) ⥤ D} (h : (i : I) → incl i ⋙ F ⟶ incl i ⋙ G) : F ⟶ G := nat_trans.mk fun (_x : sigma fun (i : I) => C i) => sorry @[simp] theorem nat_trans_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] {F : (sigma fun (i : I) => C i) ⥤ D} {G : (sigma fun (i : I) => C i) ⥤ D} (h : (i : I) → incl i ⋙ F ⟶ incl i ⋙ G) (i : I) (X : C i) : nat_trans.app (nat_trans h) (sigma.mk i X) = nat_trans.app (h i) X := rfl /-- (Implementation). An auxiliary definition to build the functor `desc`. -/ def desc_map {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) : (X ⟶ Y) → (functor.obj (F (sigma.fst X)) (sigma.snd X) ⟶ functor.obj (F (sigma.fst Y)) (sigma.snd Y)) := sorry /-- Given a collection of functors `F i : C i ⥤ D`, we can produce a functor `(Σ i, C i) ⥤ D`. The produced functor `desc F` satisfies: `incl i ⋙ desc F ≅ F i`, i.e. restricted to just the subcategory `C i`, `desc F` agrees with `F i`, and it is unique (up to natural isomorphism) with this property. This witnesses that the sigma-type is the coproduct in Cat. -/ @[simp] theorem desc_obj {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (X : sigma fun (i : I) => C i) : functor.obj (desc F) X = functor.obj (F (sigma.fst X)) (sigma.snd X) := Eq.refl (functor.obj (desc F) X) @[simp] theorem desc_map_mk {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) {i : I} (X : C i) (Y : C i) (f : X ⟶ Y) : functor.map (desc F) (sigma_hom.mk f) = functor.map (F i) f := rfl /-- This shows that when `desc F` is restricted to just the subcategory `C i`, `desc F` agrees with `F i`. -/ -- We hand-generate the simp lemmas about this since they come out cleaner. def incl_desc {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (i : I) : incl i ⋙ desc F ≅ F i := nat_iso.of_components (fun (X : C i) => iso.refl (functor.obj (incl i ⋙ desc F) X)) sorry @[simp] theorem incl_desc_hom_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (i : I) (X : C i) : nat_trans.app (iso.hom (incl_desc F i)) X = 𝟙 := rfl @[simp] theorem incl_desc_inv_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (i : I) (X : C i) : nat_trans.app (iso.inv (incl_desc F i)) X = 𝟙 := rfl /-- If `q` when restricted to each subcategory `C i` agrees with `F i`, then `q` is isomorphic to `desc F`. -/ def desc_uniq {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (q : (sigma fun (i : I) => C i) ⥤ D) (h : (i : I) → incl i ⋙ q ≅ F i) : q ≅ desc F := nat_iso.of_components (fun (_x : sigma fun (i : I) => C i) => sorry) sorry @[simp] theorem desc_uniq_hom_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (q : (sigma fun (i : I) => C i) ⥤ D) (h : (i : I) → incl i ⋙ q ≅ F i) (i : I) (X : C i) : nat_trans.app (iso.hom (desc_uniq F q h)) (sigma.mk i X) = nat_trans.app (iso.hom (h i)) X := rfl @[simp] theorem desc_uniq_inv_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (q : (sigma fun (i : I) => C i) ⥤ D) (h : (i : I) → incl i ⋙ q ≅ F i) (i : I) (X : C i) : nat_trans.app (iso.inv (desc_uniq F q h)) (sigma.mk i X) = nat_trans.app (iso.inv (h i)) X := rfl /-- If `q₁` and `q₂` when restricted to each subcategory `C i` agree, then `q₁` and `q₂` are isomorphic. -/ @[simp] theorem nat_iso_inv {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] {q₁ : (sigma fun (i : I) => C i) ⥤ D} {q₂ : (sigma fun (i : I) => C i) ⥤ D} (h : (i : I) → incl i ⋙ q₁ ≅ incl i ⋙ q₂) : iso.inv (nat_iso h) = nat_trans fun (i : I) => iso.inv (h i) := Eq.refl (iso.inv (nat_iso h)) /-- A function `J → I` induces a functor `Σ j, C (g j) ⥤ Σ i, C i`. -/ def map {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) : (sigma fun (j : J) => C (g j)) ⥤ sigma fun (i : I) => C i := desc fun (j : J) => incl (g j) @[simp] theorem map_obj {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) (j : J) (X : C (g j)) : functor.obj (map C g) (sigma.mk j X) = sigma.mk (g j) X := rfl @[simp] theorem map_map {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) {j : J} {X : C (g j)} {Y : C (g j)} (f : X ⟶ Y) : functor.map (map C g) (sigma_hom.mk f) = sigma_hom.mk f := rfl /-- The functor `sigma.map C g` restricted to the subcategory `C j` acts as the inclusion of `g j`. -/ @[simp] theorem incl_comp_map_hom_app {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) (j : J) (X : C (g j)) : nat_trans.app (iso.hom (incl_comp_map C g j)) X = 𝟙 := Eq.refl 𝟙 /-- The functor `sigma.map` applied to the identity function is just the identity functor. -/ @[simp] theorem map_id_hom_app (I : Type w₁) (C : I → Type u₁) [(i : I) → category (C i)] (_x : sigma fun (i : I) => (fun (i : I) => (fun (i : I) => C (id i)) i) i) : nat_trans.app (iso.hom (map_id I C)) _x = nat_trans._match_1 (fun (i : I) => iso.hom (nat_iso.of_components (fun (X : C i) => iso.refl (sigma.mk i X)) (map_id._proof_1 I C i))) _x := sorry /-- The functor `sigma.map` applied to a composition is a composition of functors. -/ @[simp] theorem map_comp_hom_app {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} {K : Type w₃} (f : K → J) (g : J → I) (X : sigma fun (i : K) => (fun (j : K) => function.comp C g (f j)) i) : nat_trans.app (iso.hom (map_comp C f g)) X = iso.hom (desc_uniq._match_1 (fun (j : K) => incl (g (f j))) (map (C ∘ g) f ⋙ map C g) (fun (k : K) => iso_whisker_right (incl_comp_map (C ∘ g) f k) (map C g) ≪≫ incl_comp_map C g (f k)) X) := sorry namespace functor /-- Assemble an `I`-indexed family of functors into a functor between the sigma types. -/ def sigma {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : I → Type u₁} [(i : I) → category (D i)] (F : (i : I) → C i ⥤ D i) : (sigma fun (i : I) => C i) ⥤ sigma fun (i : I) => D i := desc fun (i : I) => F i ⋙ incl i end functor namespace nat_trans /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ def sigma {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : I → Type u₁} [(i : I) → category (D i)] {F : (i : I) → C i ⥤ D i} {G : (i : I) → C i ⥤ D i} (α : (i : I) → F i ⟶ G i) : functor.sigma F ⟶ functor.sigma G := nat_trans.mk fun (f : sigma fun (i : I) => C i) => sigma_hom.mk (nat_trans.app (α (sigma.fst f)) (sigma.snd f)) end Mathlib
07d870999e4e492303c300a0651f48e33544ad9c
4727251e0cd73359b15b664c3170e5d754078599
/src/combinatorics/simple_graph/metric.lean
9bc039fd1a8801e3238e6584a99c9015553156ac
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,542
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Vincent Beffara -/ import combinatorics.simple_graph.connectivity import data.nat.lattice /-! # Graph metric This module defines the `simple_graph.dist` function, which takes pairs of vertices to the length of the shortest walk between them. ## Main definitions - `simple_graph.dist` is the graph metric. ## Todo - Provide an additional computable version of `simple_graph.dist` for when `G` is connected. - Evaluate `nat` vs `enat` for the codomain of `dist`, or potentially having an additional `edist` when the objects under consideration are disconnected graphs. - When directed graphs exist, a directed notion of distance, likely `enat`-valued. ## Tags graph metric, distance -/ namespace simple_graph variables {V : Type*} (G : simple_graph V) /-! ## Metric -/ /-- The distance between two vertices is the length of the shortest walk between them. If no such walk exists, this uses the junk value of `0`. -/ noncomputable def dist (u v : V) : ℕ := Inf (set.range (walk.length : G.walk u v → ℕ)) variables {G} protected lemma reachable.exists_walk_of_dist {u v : V} (hr : G.reachable u v) : ∃ (p : G.walk u v), p.length = G.dist u v := nat.Inf_mem (set.range_nonempty_iff_nonempty.mpr hr) protected lemma connected.exists_walk_of_dist (hconn : G.connected) (u v : V) : ∃ (p : G.walk u v), p.length = G.dist u v := (hconn u v).exists_walk_of_dist lemma dist_le {u v : V} (p : G.walk u v) : G.dist u v ≤ p.length := nat.Inf_le ⟨p, rfl⟩ @[simp] lemma dist_eq_zero_iff_eq_or_not_reachable {u v : V} : G.dist u v = 0 ↔ u = v ∨ ¬ G.reachable u v := by simp [dist, nat.Inf_eq_zero, reachable] lemma dist_self {v : V} : dist G v v = 0 := by simp protected lemma reachable.dist_eq_zero_iff {u v : V} (hr : G.reachable u v) : G.dist u v = 0 ↔ u = v := by simp [hr] protected lemma reachable.pos_dist_of_ne {u v : V} (h : G.reachable u v) (hne : u ≠ v) : 0 < G.dist u v := nat.pos_of_ne_zero (by simp [h, hne]) protected lemma connected.dist_eq_zero_iff (hconn : G.connected) {u v : V} : G.dist u v = 0 ↔ u = v := by simp [hconn u v] protected lemma connected.pos_dist_of_ne {u v : V} (hconn : G.connected) (hne : u ≠ v) : 0 < G.dist u v := nat.pos_of_ne_zero (by simp [hconn.dist_eq_zero_iff, hne]) lemma dist_eq_zero_of_not_reachable {u v : V} (h : ¬ G.reachable u v) : G.dist u v = 0 := by simp [h] lemma nonempty_of_pos_dist {u v : V} (h : 0 < G.dist u v) : (set.univ : set (G.walk u v)).nonempty := by simpa [set.range_nonempty_iff_nonempty, set.nonempty_iff_univ_nonempty] using nat.nonempty_of_pos_Inf h protected lemma connected.dist_triangle (hconn : G.connected) {u v w : V} : G.dist u w ≤ G.dist u v + G.dist v w := begin obtain ⟨p, hp⟩ := hconn.exists_walk_of_dist u v, obtain ⟨q, hq⟩ := hconn.exists_walk_of_dist v w, rw [← hp, ← hq, ← walk.length_append], apply dist_le, end private lemma dist_comm_aux {u v : V} (h : G.reachable u v) : G.dist u v ≤ G.dist v u := begin obtain ⟨p, hp⟩ := h.symm.exists_walk_of_dist, rw [← hp, ← walk.length_reverse], apply dist_le, end lemma dist_comm {u v : V} : G.dist u v = G.dist v u := begin by_cases h : G.reachable u v, { apply le_antisymm (dist_comm_aux h) (dist_comm_aux h.symm), }, { have h' : ¬ G.reachable v u := λ h', absurd h'.symm h, simp [h, h', dist_eq_zero_of_not_reachable], }, end end simple_graph
a4ee5562fec88928b2507089407e2c32a172d05a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/unicode.lean
0b91f068c742df5aa268e7c683be924f7af0a794
[ "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
130
lean
constant N : Type constant α : N constant β₁ : N #check β₁ constant δ : N #check δ constant δ₁₁ : N #check δ₁₁
70ac58a01b7b48e67840daff60ff15ddab076826
57c233acf9386e610d99ed20ef139c5f97504ba3
/test/monotonicity.lean
3efb007c251f8879e3f875f7e554fd39513c5dfb
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
8,587
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity import tactic.norm_num import algebra.order.ring import measure_theory.measure.lebesgue import data.list.defs open list tactic tactic.interactive set example (h : 3 + 6 ≤ 4 + 5) : 1 + 3 + 2 + 6 ≤ 4 + 2 + 1 + 5 := begin ac_mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin ac_mono, mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin transitivity (1 + 3 + 2 - 5 : ℤ), { ac_mono }, { ac_mono }, end example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, norm_num end example (x y z a b : ℤ) (h : a ≤ (b : ℤ)) (h' : z ≤ y) : (1 + a + x) - y ≤ (1 + b + x) - z := begin transitivity (1 + a + x - z), { mono, }, { mono, mono, mono }, end example (x y z : ℤ) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin transitivity (1 + 3 + x - z), { mono }, { mono, mono, norm_num }, end example (x y z : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin ac_mono, mono* end @[simp] def list.le' {α : Type*} [has_le α] : list α → list α → Prop | (x::xs) (y::ys) := x ≤ y ∧ list.le' xs ys | [] [] := true | _ _ := false @[simp] instance list_has_le {α : Type*} [has_le α] : has_le (list α) := ⟨ list.le' ⟩ lemma list.le_refl {α : Type*} [preorder α] {xs : list α} : xs ≤ xs := begin induction xs with x xs, { trivial }, { simp [has_le.le,list.le], split, exact le_rfl, apply xs_ih } end -- @[trans] lemma list.le_trans {α : Type*} [preorder α] {xs zs : list α} (ys : list α) (h : xs ≤ ys) (h' : ys ≤ zs) : xs ≤ zs := begin revert ys zs, induction xs with x xs ; intros ys zs h h' ; cases ys with y ys ; cases zs with z zs ; try { cases h ; cases h' ; done }, { apply list.le_refl }, { simp [has_le.le,list.le], split, apply le_trans h.left h'.left, apply xs_ih _ h.right h'.right, } end @[mono] lemma list_le_mono_left {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : xs ++ zs ≤ ys ++ zs := begin revert ys, induction xs with x xs ; intros ys h, { cases ys, apply list.le_refl, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, revert h, apply and.imp_right, apply xs_ih } end @[mono] lemma list_le_mono_right {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : zs ++ xs ≤ zs ++ ys := begin revert ys zs, induction xs with x xs ; intros ys zs h, { cases ys, { simp, apply list.le_refl }, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, suffices : list.le' ((zs ++ [x]) ++ xs) ((zs ++ [y]) ++ ys), { refine cast _ this, simp, }, apply list.le_trans (zs ++ [y] ++ xs), { apply list_le_mono_left, induction zs with z zs, { simp [has_le.le,list.le], apply h.left }, { simp [has_le.le,list.le], split, exact le_rfl, apply zs_ih, } }, { apply xs_ih h.right, } } end lemma bar_bar' (h : [] ++ [3] ++ [2] ≤ [1] ++ [5] ++ [4]) : [] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end lemma bar_bar'' (h : [3] ++ [2] ++ [2] ≤ [5] ++ [4] ++ []) : [1] ++ ([3] ++ [2]) ++ [2] ≤ [1] ++ [5] ++ ([4] ++ []) := begin ac_mono, end lemma bar_bar (h : [3] ++ [2] ≤ [5] ++ [4]) : [1] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end def P (x : ℕ) := 7 ≤ x def Q (x : ℕ) := x ≤ 7 @[mono] lemma P_mono {x y : ℕ} (h : x ≤ y) : P x → P y := by { intro h', apply le_trans h' h } @[mono] lemma Q_mono {x y : ℕ} (h : y ≤ x) : Q x → Q y := by apply le_trans h example (x y z : ℕ) (h : x ≤ y) : P (x + z) → P (z + y) := begin ac_mono, ac_mono, end example (x y z : ℕ) (h : y ≤ x) : Q (x + z) → Q (z + y) := begin ac_mono, ac_mono, end example (x y z k m n : ℤ) (h₀ : z ≤ 0) (h₁ : y ≤ x) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : n + x + m ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono* : m + x + n ≤ y + n + m, transitivity ; [ skip , apply h₁ ], apply le_of_eq, ac_refl, end example (x y z k m n : ℤ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, success_if_fail { ac_mono }, admit }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono*, change 0 ≤ z, apply nat.zero_le, }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, change (m + x + n) * z ≤ z * (y + n + m), admit }, trivial, end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono^3, cc end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : z * (x + i + n + m) + k = z * (y + j + n + m) + k := begin congr, simp [h₁], end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono*, cc, end example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 1, end example {x y z : ℕ} : true := begin have : y + x ≤ y + z, { mono, guard_target' x ≤ z, admit }, trivial end example {x y z : ℕ} : true := begin suffices : x + y ≤ z + y, trivial, mono, guard_target' x ≤ z, admit, end example {x y z w : ℕ} : true := begin have : x + y ≤ z + w, { mono, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : ℕ} : true := begin have : x * y ≤ z * w, { mono with [0 ≤ z,0 ≤ y], { guard_target 0 ≤ z, admit }, { guard_target 0 ≤ y, admit }, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∧ y → z ∧ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∨ y → z ∨ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : ℤ} : true := begin suffices : x + y < w + z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, end example {x y z w : ℤ} : true := begin suffices : x * y < w * z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, { guard_target' 0 < y, admit }, { guard_target' 0 ≤ w, admit }, end open tactic example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 3 end example {α} [linear_order α] (a b c d e : α) : max a b ≤ e → b ≤ e := by { mono, apply le_max_right } example (a b c d e : Prop) (h : d → a) (h' : c → e) : (a ∧ b → c) ∨ d → (d ∧ b → e) ∨ a := begin mono, mono, mono, end example : ∫ x in Icc 0 1, real.exp x ≤ ∫ x in Icc 0 1, real.exp (x+1) := begin mono, { exact real.continuous_exp.integrable_on_compact is_compact_Icc }, { exact (real.continuous_exp.comp $ continuous_add_right 1).integrable_on_compact is_compact_Icc }, intro x, dsimp only, mono, linarith end
0c4c646489ff5db210ac3eda55e2150b2ab34c23
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/PrettyPrinter.lean
ecfec3a5b1d67f22830fc7df32dbf44a6832f768
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
4,283
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.PrettyPrinter import Lean.Compiler.LCNF.CompilerM import Lean.Compiler.LCNF.Internalize namespace Lean.Compiler.LCNF private abbrev indentD := Std.Format.indentD namespace PP abbrev M := ReaderT LocalContext CompilerM private def join (as : Array α) (f : α → M Format) : M Format := do if h : 0 < as.size then let mut result ← f as[0] for a in as[1:] do result := f!"{result} {← f a}" return result else return .nil private def prefixJoin (pre : Format) (as : Array α) (f : α → M Format) : M Format := do let mut result := .nil for a in as do result := f!"{result}{pre}{← f a}" return result def ppFVar (fvarId : FVarId) : M Format := try return format (← getBinderName fvarId) catch _ => return format fvarId.name def ppExpr (e : Expr) : M Format := do Meta.ppExpr e |>.run' { lctx := (← read) } def ppArg (e : Expr) : M Format := do if e.isFVar then ppFVar e.fvarId! else if pp.explicit.get (← getOptions) then if e.isConst || e.isProp || e.isType0 then ppExpr e else return Format.paren (← ppExpr e) else return "_" def ppArgs (args : Array Expr) : M Format := do join args ppArg def ppApp (e : Expr) : M Format := do return f!"{← ppExpr e.getAppFn} {← ppArgs e.getAppArgs}" def ppValue (e : Expr) : M Format := do match e with | .app .. => ppApp e | .fvar fvarId => ppFVar fvarId | .proj _ i e => return f!"{← ppArg e} # {i}" | _ => ppExpr e def ppParam (param : Param) : M Format := do let borrow := if param.borrow then "@&" else "" if pp.funBinderTypes.get (← getOptions) then return Format.paren f!"{param.binderName} : {borrow}{← ppExpr param.type}" else return format s!"{borrow}{param.binderName}" def ppParams (params : Array Param) : M Format := do prefixJoin " " params ppParam def ppLetDecl (letDecl : LetDecl) : M Format := do if pp.letVarTypes.get (← getOptions) then return f!"let {letDecl.binderName} : {← ppExpr letDecl.type} := {← ppValue letDecl.value}" else return f!"let {letDecl.binderName} := {← ppValue letDecl.value}" mutual partial def ppFunDecl (funDecl : FunDecl) : M Format := do return f!"{funDecl.binderName}{← ppParams funDecl.params} :={indentD (← ppCode funDecl.value)}" partial def ppAlt (alt : Alt) : M Format := do match alt with | .default k => return f!"| _ =>{indentD (← ppCode k)}" | .alt ctorName params k => return f!"| {ctorName}{← ppParams params} =>{indentD (← ppCode k)}" partial def ppCode (c : Code) : M Format := do match c with | .let decl k => return (← ppLetDecl decl) ++ .line ++ (← ppCode k) | .fun decl k => return f!"fun " ++ (← ppFunDecl decl) ++ .line ++ (← ppCode k) | .jp decl k => return f!"jp " ++ (← ppFunDecl decl) ++ .line ++ (← ppCode k) | .cases c => return f!"cases {← ppFVar c.discr}{← prefixJoin .line c.alts ppAlt}" | .return fvarId => ppFVar fvarId | .jmp fvarId args => return f!"goto {← ppFVar fvarId} {← ppArgs args}" | .unreach .. => return "⊥" end def run (x : M α) : CompilerM α := withOptions (pp.sanitizeNames.set · false) do x |>.run (← get).lctx.toLocalContext end PP def ppCode (code : Code) : CompilerM Format := PP.run <| PP.ppCode code def ppDecl (decl : Decl) : CompilerM Format := PP.run do return f!"def {decl.name}{← PP.ppParams decl.params} :={indentD (← PP.ppCode decl.value)}" def ppFunDecl (decl : FunDecl) : CompilerM Format := PP.run do return f!"fun {decl.binderName}{← PP.ppParams decl.params} :={indentD (← PP.ppCode decl.value)}" /-- Similar to `ppDecl`, but in `CoreM`, and it does not assume `decl` has already been internalized. This function is used for debugging purposes. -/ def ppDecl' (decl : Decl) : CoreM Format := do /- We save/restore the state to make sure we do not affect the next free variable id. -/ let s ← get try go |>.run {} finally set s where go : CompilerM Format := do let decl ← decl.internalize ppDecl decl end Lean.Compiler.LCNF
bb0db8386cdb5c739e09d4c182c84c5dd91b7b5f
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/normed_space/lattice_ordered_group.lean
58eb3fdf14a4545ce3db843d9bbf1f3229d41bc6
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
8,198
lean
/- Copyright (c) 2021 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import topology.order.lattice import analysis.normed.group.basic import algebra.order.lattice_group /-! # Normed lattice ordered groups Motivated by the theory of Banach Lattices, we then define `normed_lattice_add_comm_group` as a lattice with a covariant normed group addition satisfying the solid axiom. ## Main statements We show that a normed lattice ordered group is a topological lattice with respect to the norm topology. ## References * [Meyer-Nieberg, Banach lattices][MeyerNieberg1991] ## Tags normed, lattice, ordered, group -/ /-! ### Normed lattice orderd groups Motivated by the theory of Banach Lattices, this section introduces normed lattice ordered groups. -/ local notation `|`a`|` := abs a /-- Let `α` be a normed commutative group equipped with a partial order covariant with addition, with respect which `α` forms a lattice. Suppose that `α` is *solid*, that is to say, for `a` and `b` in `α`, with absolute values `|a|` and `|b|` respectively, `|a| ≤ |b|` implies `∥a∥ ≤ ∥b∥`. Then `α` is said to be a normed lattice ordered group. -/ class normed_lattice_add_comm_group (α : Type*) extends normed_group α, lattice α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (solid : ∀ a b : α, |a| ≤ |b| → ∥a∥ ≤ ∥b∥) lemma solid {α : Type*} [normed_lattice_add_comm_group α] {a b : α} (h : |a| ≤ |b|) : ∥a∥ ≤ ∥b∥ := normed_lattice_add_comm_group.solid a b h noncomputable instance : normed_lattice_add_comm_group ℝ := { add_le_add_left := λ _ _ h _, add_le_add le_rfl h, solid := λ _ _, id, } /-- A normed lattice ordered group is an ordered additive commutative group -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_to_ordered_add_comm_group {α : Type*} [h : normed_lattice_add_comm_group α] : ordered_add_comm_group α := { ..h } /-- Let `α` be a normed group with a partial order. Then the order dual is also a normed group. -/ @[priority 100] -- see Note [lower instance priority] instance {α : Type*} : Π [normed_group α], normed_group αᵒᵈ := id variables {α : Type*} [normed_lattice_add_comm_group α] open lattice_ordered_comm_group lemma dual_solid (a b : α) (h: b⊓-b ≤ a⊓-a) : ∥a∥ ≤ ∥b∥ := begin apply solid, rw abs_eq_sup_neg, nth_rewrite 0 ← neg_neg a, rw ← neg_inf_eq_sup_neg, rw abs_eq_sup_neg, nth_rewrite 0 ← neg_neg b, rwa [← neg_inf_eq_sup_neg, neg_le_neg_iff, @inf_comm _ _ _ b, @inf_comm _ _ _ a], end /-- Let `α` be a normed lattice ordered group, then the order dual is also a normed lattice ordered group. -/ @[priority 100] -- see Note [lower instance priority] instance : normed_lattice_add_comm_group αᵒᵈ := { add_le_add_left := λ a b, add_le_add_left, solid := dual_solid } lemma norm_abs_eq_norm (a : α) : ∥|a|∥ = ∥a∥ := (solid (abs_abs a).le).antisymm (solid (abs_abs a).symm.le) lemma norm_inf_sub_inf_le_add_norm (a b c d : α) : ∥a ⊓ b - c ⊓ d∥ ≤ ∥a - c∥ + ∥b - d∥ := begin rw [← norm_abs_eq_norm (a - c), ← norm_abs_eq_norm (b - d)], refine le_trans (solid _) (norm_add_le (|a - c|) (|b - d|)), rw abs_of_nonneg (|a - c| + |b - d|) (add_nonneg (abs_nonneg (a - c)) (abs_nonneg (b - d))), calc |a ⊓ b - c ⊓ d| = |a ⊓ b - c ⊓ b + (c ⊓ b - c ⊓ d)| : by rw sub_add_sub_cancel ... ≤ |a ⊓ b - c ⊓ b| + |c ⊓ b - c ⊓ d| : abs_add_le _ _ ... ≤ |a -c| + |b - d| : by { apply add_le_add, { exact abs_inf_sub_inf_le_abs _ _ _, }, { rw [@inf_comm _ _ c, @inf_comm _ _ c], exact abs_inf_sub_inf_le_abs _ _ _, } }, end lemma norm_sup_sub_sup_le_add_norm (a b c d : α) : ∥a ⊔ b - (c ⊔ d)∥ ≤ ∥a - c∥ + ∥b - d∥ := begin rw [← norm_abs_eq_norm (a - c), ← norm_abs_eq_norm (b - d)], refine le_trans (solid _) (norm_add_le (|a - c|) (|b - d|)), rw abs_of_nonneg (|a - c| + |b - d|) (add_nonneg (abs_nonneg (a - c)) (abs_nonneg (b - d))), calc |a ⊔ b - (c ⊔ d)| = |a ⊔ b - (c ⊔ b) + (c ⊔ b - (c ⊔ d))| : by rw sub_add_sub_cancel ... ≤ |a ⊔ b - (c ⊔ b)| + |c ⊔ b - (c ⊔ d)| : abs_add_le _ _ ... ≤ |a -c| + |b - d| : by { apply add_le_add, { exact abs_sup_sub_sup_le_abs _ _ _, }, { rw [@sup_comm _ _ c, @sup_comm _ _ c], exact abs_sup_sub_sup_le_abs _ _ _, } }, end lemma norm_inf_le_add (x y : α) : ∥x ⊓ y∥ ≤ ∥x∥ + ∥y∥ := begin have h : ∥x ⊓ y - 0 ⊓ 0∥ ≤ ∥x - 0∥ + ∥y - 0∥ := norm_inf_sub_inf_le_add_norm x y 0 0, simpa only [inf_idem, sub_zero] using h, end lemma norm_sup_le_add (x y : α) : ∥x ⊔ y∥ ≤ ∥x∥ + ∥y∥ := begin have h : ∥x ⊔ y - 0 ⊔ 0∥ ≤ ∥x - 0∥ + ∥y - 0∥ := norm_sup_sub_sup_le_add_norm x y 0 0, simpa only [sup_idem, sub_zero] using h, end /-- Let `α` be a normed lattice ordered group. Then the infimum is jointly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_has_continuous_inf : has_continuous_inf α := begin refine ⟨continuous_iff_continuous_at.2 $ λ q, tendsto_iff_norm_tendsto_zero.2 $ _⟩, have : ∀ p : α × α, ∥p.1 ⊓ p.2 - q.1 ⊓ q.2∥ ≤ ∥p.1 - q.1∥ + ∥p.2 - q.2∥, from λ _, norm_inf_sub_inf_le_add_norm _ _ _ _, refine squeeze_zero (λ e, norm_nonneg _) this _, convert (((continuous_fst.tendsto q).sub tendsto_const_nhds).norm).add (((continuous_snd.tendsto q).sub tendsto_const_nhds).norm), simp, end @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_has_continuous_sup {α : Type*} [normed_lattice_add_comm_group α] : has_continuous_sup α := order_dual.has_continuous_sup αᵒᵈ /-- Let `α` be a normed lattice ordered group. Then `α` is a topological lattice in the norm topology. -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_topological_lattice : topological_lattice α := topological_lattice.mk lemma norm_abs_sub_abs (a b : α) : ∥ |a| - |b| ∥ ≤ ∥a-b∥ := solid (lattice_ordered_comm_group.abs_abs_sub_abs_le _ _) lemma norm_sup_sub_sup_le_norm (x y z : α) : ∥x ⊔ z - (y ⊔ z)∥ ≤ ∥x - y∥ := solid (abs_sup_sub_sup_le_abs x y z) lemma norm_inf_sub_inf_le_norm (x y z : α) : ∥x ⊓ z - (y ⊓ z)∥ ≤ ∥x - y∥ := solid (abs_inf_sub_inf_le_abs x y z) lemma lipschitz_with_sup_right (z : α) : lipschitz_with 1 (λ x, x ⊔ z) := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [nonneg.coe_one, one_mul, dist_eq_norm, dist_eq_norm], exact norm_sup_sub_sup_le_norm x y z, } lemma lipschitz_with_pos : lipschitz_with 1 (has_pos_part.pos : α → α) := lipschitz_with_sup_right 0 lemma continuous_pos : continuous (has_pos_part.pos : α → α) := lipschitz_with.continuous lipschitz_with_pos lemma continuous_neg' : continuous (has_neg_part.neg : α → α) := continuous_pos.comp continuous_neg lemma is_closed_nonneg {E} [normed_lattice_add_comm_group E] : is_closed {x : E | 0 ≤ x} := begin suffices : {x : E | 0 ≤ x} = has_neg_part.neg ⁻¹' {(0 : E)}, by { rw this, exact is_closed.preimage continuous_neg' is_closed_singleton, }, ext1 x, simp only [set.mem_preimage, set.mem_singleton_iff, set.mem_set_of_eq, neg_eq_zero_iff], end lemma is_closed_le_of_is_closed_nonneg {G} [ordered_add_comm_group G] [topological_space G] [has_continuous_sub G] (h : is_closed {x : G | 0 ≤ x}) : is_closed {p : G × G | p.fst ≤ p.snd} := begin have : {p : G × G | p.fst ≤ p.snd} = (λ p : G × G, p.snd - p.fst) ⁻¹' {x : G | 0 ≤ x}, by { ext1 p, simp only [sub_nonneg, set.preimage_set_of_eq], }, rw this, exact is_closed.preimage (continuous_snd.sub continuous_fst) h, end @[priority 100] -- See note [lower instance priority] instance normed_lattice_add_comm_group.order_closed_topology {E} [normed_lattice_add_comm_group E] : order_closed_topology E := ⟨is_closed_le_of_is_closed_nonneg is_closed_nonneg⟩
cc28814663db09eed04c768578bf066b64be691a
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/order/conditionally_complete_lattice.lean
3791e20716329073845c38690abebee6a39ed52d
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
34,109
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Adapted from the corresponding theory for complete lattices. Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and non-emptyness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ import order.lattice order.complete_lattice order.bounds tactic.finish data.set.finite set_option old_structure_cmd true open preorder set lattice universes u v w variables {α : Type u} {β : Type v} {ι : Type w} section preorder variables [preorder α] [preorder β] {s t : set α} {a b : α} /-Sets bounded above and bounded below.-/ def bdd_above (s : set α) := ∃x, ∀y∈s, y ≤ x def bdd_below (s : set α) := ∃x, ∀y∈s, x ≤ y /-Introduction rules for boundedness above and below. Most of the time, it is more efficient to use ⟨w, P⟩ where P is a proof that all elements of the set are bounded by w. However, they are sometimes handy.-/ lemma bdd_above.mk (a : α) (H : ∀y∈s, y≤a) : bdd_above s := ⟨a, H⟩ lemma bdd_below.mk (a : α) (H : ∀y∈s, a≤y) : bdd_below s := ⟨a, H⟩ /-Empty sets and singletons are trivially bounded. For finite sets, we need a notion of maximum and minimum, i.e., a lattice structure, see later on.-/ @[simp] lemma bdd_above_empty : ∀ [nonempty α], bdd_above (∅ : set α) | ⟨x⟩ := ⟨x, by simp⟩ @[simp] lemma bdd_below_empty : ∀ [nonempty α], bdd_below (∅ : set α) | ⟨x⟩ := ⟨x, by simp⟩ @[simp] lemma bdd_above_singleton : bdd_above ({a} : set α) := ⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩ @[simp] lemma bdd_below_singleton : bdd_below ({a} : set α) := ⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩ /-If a set is included in another one, boundedness of the second implies boundedness of the first-/ lemma bdd_above_subset (st : s ⊆ t) : bdd_above t → bdd_above s | ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩ lemma bdd_below_subset (st : s ⊆ t) : bdd_below t → bdd_below s | ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩ /- Boundedness of intersections of sets, in different guises, deduced from the monotonicity of boundedness.-/ lemma bdd_above_inter_left : bdd_above s → bdd_above (s ∩ t) := bdd_above_subset (set.inter_subset_left _ _) lemma bdd_above_inter_right : bdd_above t → bdd_above (s ∩ t) := bdd_above_subset (set.inter_subset_right _ _) lemma bdd_below_inter_left : bdd_below s → bdd_below (s ∩ t) := bdd_below_subset (set.inter_subset_left _ _) lemma bdd_below_inter_right : bdd_below t → bdd_below (s ∩ t) := bdd_below_subset (set.inter_subset_right _ _) /--The image under a monotone function of a set which is bounded above is bounded above-/ lemma bdd_above_of_bdd_above_of_monotone {f : α → β} (hf : monotone f) : bdd_above s → bdd_above (f '' s) | ⟨C, hC⟩ := ⟨f C, by rintro y ⟨x, x_bnd, rfl⟩; exact hf (hC x x_bnd)⟩ /--The image under a monotone function of a set which is bounded below is bounded below-/ lemma bdd_below_of_bdd_below_of_monotone {f : α → β} (hf : monotone f) : bdd_below s → bdd_below (f '' s) | ⟨C, hC⟩ := ⟨f C, by rintro y ⟨x, x_bnd, rfl⟩; exact hf (hC x x_bnd)⟩ end preorder /--When there is a global maximum, every set is bounded above.-/ @[simp] lemma bdd_above_top [order_top α] (s : set α) : bdd_above s := ⟨⊤, by intros; apply order_top.le_top⟩ /--When there is a global minimum, every set is bounded below.-/ @[simp] lemma bdd_below_bot [order_bot α] (s : set α) : bdd_below s := ⟨⊥, by intros; apply order_bot.bot_le⟩ /-When there is a max (i.e., in the class semilattice_sup), then the union of two bounded sets is bounded, by the maximum of the bounds for the two sets. With this, we deduce that finite sets are bounded by induction, and that a finite union of bounded sets is bounded.-/ section semilattice_sup variables [semilattice_sup α] {s t : set α} {a b : α} /--The union of two sets is bounded above if and only if each of the sets is.-/ @[simp] lemma bdd_above_union : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨show bdd_above (s ∪ t) → (bdd_above s ∧ bdd_above t), from assume : bdd_above (s ∪ t), have S : bdd_above s, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_left], have T : bdd_above t, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_right], and.intro S T, show (bdd_above s ∧ bdd_above t) → bdd_above (s ∪ t), from assume H : bdd_above s ∧ bdd_above t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → y ≤ ws ht : ∀ (y : α), y ∈ s → y ≤ wt-/ have Bs : ∀b∈s, b ≤ ws ⊔ wt, by intros; apply le_trans (hs b ‹b ∈ s›) _; simp only [lattice.le_sup_left], have Bt : ∀b∈t, b ≤ ws ⊔ wt, by intros; apply le_trans (ht b ‹b ∈ t›) _; simp only [lattice.le_sup_right], show bdd_above (s ∪ t), begin apply bdd_above.mk (ws ⊔ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness above.-/ @[simp] lemma bdd_above_insert : bdd_above (insert a s) ↔ bdd_above s := ⟨bdd_above_subset (by simp only [set.subset_insert]), λ h, by rw [insert_eq, bdd_above_union]; exact ⟨bdd_above_singleton, h⟩⟩ /--A finite set is bounded above.-/ lemma bdd_above_finite [nonempty α] (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _, bdd_above_insert.2 /--A finite union of sets which are all bounded above is still bounded above.-/ lemma bdd_above_finite_union [nonempty α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := ⟨λ (bdd : bdd_above (⋃i∈I, S i)) i (hi : i ∈ I), bdd_above_subset (subset_bUnion_of_mem hi) bdd, show (∀i ∈ I, bdd_above (S i)) → (bdd_above (⋃i∈I, S i)), from finite.induction_on H (λ _, by rw bUnion_empty; exact bdd_above_empty) (λ x s hn hf IH h, by simp only [ set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h; rw [set.bUnion_insert, bdd_above_union]; exact ⟨h.1, IH h.2⟩)⟩ end semilattice_sup /-When there is a min (i.e., in the class semilattice_inf), then the union of two sets which are bounded from below is bounded from below, by the minimum of the bounds for the two sets. With this, we deduce that finite sets are bounded below by induction, and that a finite union of sets which are bounded below is still bounded below.-/ section semilattice_inf variables [semilattice_inf α] {s t : set α} {a b : α} /--The union of two sets is bounded below if and only if each of the sets is.-/ @[simp] lemma bdd_below_union : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := ⟨show bdd_below (s ∪ t) → (bdd_below s ∧ bdd_below t), from assume : bdd_below (s ∪ t), have S : bdd_below s, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_left], have T : bdd_below t, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_right], and.intro S T, show (bdd_below s ∧ bdd_below t) → bdd_below (s ∪ t), from assume H : bdd_below s ∧ bdd_below t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → ws ≤ y ht : ∀ (y : α), y ∈ s → wt ≤ y-/ have Bs : ∀b∈s, ws ⊓ wt ≤ b, by intros; apply le_trans _ (hs b ‹b ∈ s›); simp only [lattice.inf_le_left], have Bt : ∀b∈t, ws ⊓ wt ≤ b, by intros; apply le_trans _ (ht b ‹b ∈ t›); simp only [lattice.inf_le_right], show bdd_below (s ∪ t), begin apply bdd_below.mk (ws ⊓ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert : bdd_below (insert a s) ↔ bdd_below s := ⟨show bdd_below (insert a s) → bdd_below s, from bdd_below_subset (by simp only [set.subset_insert]), show bdd_below s → bdd_below (insert a s), by rw[insert_eq]; simp only [bdd_below_singleton, bdd_below_union, and_self, forall_true_iff] {contextual := tt}⟩ /--A finite set is bounded below.-/ lemma bdd_below_finite [nonempty α] (hs : finite s) : bdd_below s := finite.induction_on hs bdd_below_empty $ λ a s _ _, bdd_below_insert.2 /--A finite union of sets which are all bounded below is still bounded below.-/ lemma bdd_below_finite_union [nonempty α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := ⟨λ (bdd : bdd_below (⋃i∈I, S i)) i (hi : i ∈ I), bdd_below_subset (subset_bUnion_of_mem hi) bdd, show (∀i ∈ I, bdd_below (S i)) → (bdd_below (⋃i∈I, S i)), from finite.induction_on H (λ _, by rw bUnion_empty; exact bdd_below_empty) (λ x s hn hf IH h, by simp only [ set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h; rw [set.bUnion_insert, bdd_below_union]; exact ⟨h.1, IH h.2⟩)⟩ end semilattice_inf namespace lattice /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of non-emptyness or boundedness.-/ class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀s a, s ≠ ∅ → (∀b∈s, b ≤ a) → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, s ≠ ∅ → (∀b∈s, a ≤ b) → a ≤ Inf s) class conditionally_complete_linear_order (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α class conditionally_complete_linear_order_bot (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α, order_bot α := (cSup_empty : Sup ∅ = ⊥) /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α›} instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]: conditionally_complete_linear_order α := { ..lattice.conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s ≠ ∅) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s ≠ ∅) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s ≠ ∅) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹s ≠ ∅› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ :s ≠ ∅) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹s ≠ ∅› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) theorem cSup_le_iff (_ : bdd_above s) (_ : s ≠ ∅) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨assume (_ : Sup s ≤ a) (b) (_ : b ∈ s), le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) ‹Sup s ≤ a›, cSup_le ‹s ≠ ∅›⟩ theorem le_cInf_iff (_ : bdd_below s) (_ : s ≠ ∅) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨assume (_ : a ≤ Inf s) (b) (_ : b ∈ s), le_trans ‹a ≤ Inf s› (cInf_le ‹bdd_below s› ‹b ∈ s›), le_cInf ‹s ≠ ∅›⟩ lemma cSup_upper_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s ≠ ∅) : Sup {a | ∀x∈s, a ≤ x} = Inf s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cSup_le (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, le_cInf hs ha) (le_cSup ⟨a, assume y hy, hy a ha⟩ $ assume x hx, cInf_le h hx) lemma cInf_lower_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s ≠ ∅) : Inf {a | ∀x∈s, x ≤ a} = Sup s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cInf_le ⟨a, assume y hy, hy a ha⟩ $ assume x hx, le_cSup h hx) (le_cInf (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, cSup_le hs ha) /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any w<b.-/ theorem cSup_intro (_ : s ≠ ∅) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹s ≠ ∅› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any w>b.-/ theorem cInf_intro (_ : s ≠ ∅) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹s ≠ ∅› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--When an element a of a set s is larger than all elements of the set, it is Sup s-/ theorem cSup_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, w ≤ a) : Sup s = a := have bdd_above s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : a ≤ Sup s := le_cSup ‹bdd_above s› ‹a ∈ s›, have B : Sup s ≤ a := cSup_le ‹s ≠ ∅› ‹∀w∈s, w ≤ a›, le_antisymm B A /--When an element a of a set s is smaller than all elements of the set, it is Inf s-/ theorem cInf_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, a ≤ w) : Inf s = a := have bdd_below s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : Inf s ≤ a := cInf_le ‹bdd_below s› ‹a ∈ s›, have B : a ≤ Inf s := le_cInf ‹s ≠ ∅› ‹∀w∈s, a ≤ w›, le_antisymm A B /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b s when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := have A : a ≤ Sup {a} := by apply le_cSup _ _; simp only [set.mem_singleton,bdd_above_singleton], have B : Sup {a} ≤ a := by apply cSup_le _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm B A /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := have A : Inf {a} ≤ a := by apply cInf_le _ _; simp only [set.mem_singleton,bdd_below_singleton], have B : a ≤ Inf {a} := by apply le_cInf _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm A B /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (_ : bdd_below s) (_ : bdd_above s) (_ : s ≠ ∅) : Inf s ≤ Sup s := let ⟨w, hw⟩ := exists_mem_of_ne_empty ‹s ≠ ∅› in /-hw : w ∈ s-/ have Inf s ≤ w := cInf_le ‹bdd_below s› ‹w ∈ s›, have w ≤ Sup s := le_cSup ‹bdd_above s› ‹w ∈ s›, le_trans ‹Inf s ≤ w› ‹w ≤ Sup s› /--The sup of a union of sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (_ : bdd_above s) (_ : s ≠ ∅) (_ : bdd_above t) (_ : t ≠ ∅) : Sup (s ∪ t) = Sup s ⊔ Sup t := have A : Sup (s ∪ t) ≤ Sup s ⊔ Sup t := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, b ≤ Sup s ⊔ Sup t := begin intros, cases H, apply le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) _, simp only [lattice.le_sup_left], apply le_trans (le_cSup ‹bdd_above t› ‹b ∈ t›) _, simp only [lattice.le_sup_right] end, cSup_le this F, have B : Sup s ⊔ Sup t ≤ Sup (s ∪ t) := have Sup s ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹s ≠ ∅›; simp only [bdd_above_union,set.subset_union_left]; finish, have Sup t ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹t ≠ ∅›; simp only [bdd_above_union,set.subset_union_right]; finish, by simp only [lattice.sup_le_iff]; split; assumption; assumption, le_antisymm A B /--The inf of a union of sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (_ : bdd_below s) (_ : s ≠ ∅) (_ : bdd_below t) (_ : t ≠ ∅) : Inf (s ∪ t) = Inf s ⊓ Inf t := have A : Inf s ⊓ Inf t ≤ Inf (s ∪ t) := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, Inf s ⊓ Inf t ≤ b := begin intros, cases H, apply le_trans _ (cInf_le ‹bdd_below s› ‹b ∈ s›), simp only [lattice.inf_le_left], apply le_trans _ (cInf_le ‹bdd_below t› ‹b ∈ t›), simp only [lattice.inf_le_right] end, le_cInf this F, have B : Inf (s ∪ t) ≤ Inf s ⊓ Inf t := have Inf (s ∪ t) ≤ Inf s := by apply cInf_le_cInf _ ‹s ≠ ∅›; simp only [bdd_below_union,set.subset_union_left]; finish, have Inf (s ∪ t) ≤ Inf t := by apply cInf_le_cInf _ ‹t ≠ ∅›; simp only [bdd_below_union,set.subset_union_right]; finish, by simp only [lattice.le_inf_iff]; split; assumption; assumption, le_antisymm B A /--The supremum of an intersection of sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (_ : s ∩ t ≠ ∅) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le ‹s ∩ t ≠ ∅› _, simp only [lattice.le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (_ : s ∩ t ≠ ∅) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf ‹s ∩ t ≠ ∅› _, simp only [and_imp, set.mem_inter_eq, lattice.sup_le_iff], intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (_ : bdd_above s) (_ : s ≠ ∅) : Sup (insert a s) = a ⊔ Sup s := calc Sup (insert a s) = Sup ({a} ∪ s) : by rw [insert_eq] ... = Sup {a} ⊔ Sup s : by apply cSup_union _ _ ‹bdd_above s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_above_singleton] ... = a ⊔ Sup s : by simp only [eq_self_iff_true, lattice.cSup_singleton] /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (_ : bdd_below s) (_ : s ≠ ∅) : Inf (insert a s) = a ⊓ Inf s := calc Inf (insert a s) = Inf ({a} ∪ s) : by rw [insert_eq] ... = Inf {a} ⊓ Inf s : by apply cInf_union _ _ ‹bdd_below s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_below_singleton] ... = a ⊓ Inf s : by simp only [eq_self_iff_true, lattice.cInf_singleton] @[simp] lemma cInf_interval [conditionally_complete_lattice α] : Inf {b | a ≤ b} = a := cInf_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) @[simp] lemma cSup_interval [conditionally_complete_lattice α] : Sup {b | b ≤ a} = a := cSup_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_le_csupr {f g : β → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) : supr f ≤ supr g := begin classical, by_cases nonempty β, { have Rf : range f ≠ ∅, {simpa}, apply cSup_le Rf, rintros y ⟨x, rfl⟩, have : g x ∈ range g := ⟨x, rfl⟩, exact le_cSup_of_le B this (H x) }, { have Rf : range f = ∅, {simpa}, have Rg : range g = ∅, {simpa}, unfold supr, rw [Rf, Rg] } end /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c := cSup_le (by simp [not_not_intro ne]) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : β → α} (H : bdd_above (range f)) {c : β} : f c ≤ supr f := le_cSup H (mem_range_self _) /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_le_cinfi {f g : β → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) : infi f ≤ infi g := begin classical, by_cases nonempty β, { have Rg : range g ≠ ∅, {simpa}, apply le_cInf Rg, rintros y ⟨x, rfl⟩, have : f x ∈ range f := ⟨x, rfl⟩, exact cInf_le_of_le B this (H x) }, { have Rf : range f = ∅, {simpa}, have Rg : range g = ∅, {simpa}, unfold infi, rw [Rf, Rg] } end /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f := le_cInf (by simp [not_not_intro ne]) (by rwa forall_range_iff) /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : β → α} (H : bdd_below (range f)) {c : β} : infi f ≤ f c := cInf_le H (mem_range_self _) lemma is_lub_cSup {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : is_lub s (Sup s) := ⟨assume x, le_cSup H, assume x, cSup_le ne⟩ lemma is_glb_cInf {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : is_glb s (Inf s) := ⟨assume x, cInf_le H, assume x, le_cInf ne⟩ @[simp] theorem cinfi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := begin rcases exists_mem_of_nonempty ι with ⟨x, _⟩, refine le_antisymm (@cinfi_le _ _ _ _ _ x) (le_cinfi (λi, _root_.le_refl _)), rw range_const, exact bdd_below_singleton end @[simp] theorem csupr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := begin rcases exists_mem_of_nonempty ι with ⟨x, _⟩, refine le_antisymm (csupr_le (λi, _root_.le_refl _)) (@le_csupr _ _ _ (λ b:ι, a) _ x), rw range_const, exact bdd_above_singleton end end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /--When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_lt_cSup (_ : s ≠ ∅) (_ : b < Sup s) : ∃a∈s, b < a := begin classical, by_contra h, have : Sup s ≤ b := by apply cSup_le ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›) end /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (_ : s ≠ ∅) (_ : Inf s < b) : ∃a∈s, a < b := begin classical, by_contra h, have : b ≤ Inf s := by apply le_cInf ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›) end /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_intro' (_ : s ≠ ∅) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := le_antisymm (show Sup s ≤ b, from cSup_le ‹s ≠ ∅› h_is_ub) (show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_linear_order section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot α] lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty α end conditionally_complete_linear_order_bot section local attribute [instance] classical.prop_decidable noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := infer_instance noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_nat_def (ne_empty_iff_exists_mem.1 hs)]; exact hb _ (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ), .. (infer_instance : decidable_linear_order ℕ) } end end lattice /-end of namespace lattice-/ namespace with_top open lattice local attribute [instance] classical.prop_decidable variables [conditionally_complete_linear_order_bot α] lemma has_lub (s : set (with_top α)) : ∃a, is_lub s a := begin by_cases hs : s = ∅, { subst hs, exact ⟨⊥, is_lub_empty⟩, }, rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hxs⟩, by_cases bnd : ∃b:α, ↑b ∈ upper_bounds s, { rcases bnd with ⟨b, hb⟩, have bdd : bdd_above {a : α | ↑a ∈ s}, from ⟨b, assume y hy, coe_le_coe.1 $ hb _ hy⟩, refine ⟨(Sup {a : α | ↑a ∈ s} : α), _, _⟩, { assume a has, rcases (le_coe_iff _ _).1 (hb _ has) with ⟨a, rfl, h⟩, exact (coe_le_coe.2 $ le_cSup bdd has) }, { assume a hs, rcases (le_coe_iff _ _).1 (hb _ hxs) with ⟨x, rfl, h⟩, refine (coe_le_iff _ _).2 (assume c hc, _), subst hc, exact (cSup_le (ne_empty_of_mem hxs) $ assume b (hbs : ↑b ∈ s), coe_le_coe.1 $ hs _ hbs), } }, exact ⟨⊤, assume a _, le_top, assume a, match a with | some a, ha := (bnd ⟨a, ha⟩).elim | none, ha := _root_.le_refl ⊤ end⟩ end lemma has_glb (s : set (with_top α)) : ∃a, is_glb s a := begin by_cases hs : ∃x:α, ↑x ∈ s, { rcases hs with ⟨x, hxs⟩, refine ⟨(Inf {a : α | ↑a ∈ s} : α), _, _⟩, exact (assume a has, (coe_le_iff _ _).2 $ assume x hx, cInf_le (bdd_below_bot _) $ show ↑x ∈ s, from hx ▸ has), { assume a has, rcases (le_coe_iff _ _).1 (has _ hxs) with ⟨x, rfl, h⟩, exact (coe_le_coe.2 $ le_cInf (ne_empty_of_mem hxs) $ assume b hbs, coe_le_coe.1 $ has _ hbs) } }, exact ⟨⊤, assume a, match a with | some a, ha := (hs ⟨a, ha⟩).elim | none, ha := _root_.le_refl _ end, assume a _, le_top⟩ end noncomputable instance : has_Sup (with_top α) := ⟨λs, classical.some $ has_lub s⟩ noncomputable instance : has_Inf (with_top α) := ⟨λs, classical.some $ has_glb s⟩ lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := classical.some_spec _ lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := classical.some_spec _ noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, decidable_le := classical.dec_rel _, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) := begin by_cases hs : s = ∅, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, lattice.supr_bot, lattice.supr_false], refl }, apply le_antisymm, { refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s ≠ ∅) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) := let ⟨x, hx⟩ := ne_empty_iff_exists_mem.1 hs in have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (bdd_below_bot s) ha) begin refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq ▸ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top section order_dual open lattice instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice (order_dual α) := { le_cSup := @cInf_le α _, cSup_le := @le_cInf α _, le_cInf := @cSup_le α _, cInf_le := @le_cSup α _, ..order_dual.lattice.has_Inf α, ..order_dual.lattice.has_Sup α, ..order_dual.lattice.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order (order_dual α) := { ..order_dual.lattice.conditionally_complete_lattice α, ..order_dual.decidable_linear_order α } end order_dual
e19cc51d7a9ba3842e1fed863e7a9d3debbff11a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/converter/apply_congr.lean
cf77f977cfb2d4d771427e5a0db83c1f8c05ce96
[ "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,368
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison -/ import tactic.interactive import tactic.converter.interactive /-! ## Introduce the `apply_congr` conv mode tactic. `apply_congr` will apply congruence lemmas inside `conv` mode. It is particularly useful when the automatically generated congruence lemmas are not of the optimal shape. An example, described in the doc-string is rewriting inside the operand of a `finset.sum`. -/ open tactic namespace conv.interactive open interactive interactive.types lean.parser local postfix (name := parser.optional) `?`:9001 := optional /-- Apply a congruence lemma inside `conv` mode. When called without an argument `apply_congr` will try applying all lemmas marked with `@[congr]`. Otherwise `apply_congr e` will apply the lemma `e`. Recall that a goal that appears as `∣ X` in `conv` mode represents a goal of `⊢ X = ?m`, i.e. an equation with a metavariable for the right hand side. To successfully use `apply_congr e`, `e` will need to be an equation (possibly after function arguments), which can be unified with a goal of the form `X = ?m`. The right hand side of `e` will then determine the metavariable, and `conv` will subsequently replace `X` with that right hand side. As usual, `apply_congr` can create new goals; any of these which are _not_ equations with a metavariable on the right hand side will be hard to deal with in `conv` mode. Thus `apply_congr` automatically calls `intros` on any new goals, and fails if they are not then equations. In particular it is useful for rewriting inside the operand of a `finset.sum`, as it provides an extra hypothesis asserting we are inside the domain. For example: ```lean example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.sum S f = finset.sum S g := begin conv_lhs { -- If we just call `congr` here, in the second goal we're helpless, -- because we are only given the opportunity to rewrite `f`. -- However `apply_congr` uses the appropriate `@[congr]` lemma, -- so we get to rewrite `f x`, in the presence of the crucial `H : x ∈ S` hypothesis. apply_congr, skip, simp [h, H], } end ``` In the above example, when the `apply_congr` tactic is called it gives the hypothesis `H : x ∈ S` which is then used to rewrite the `f x` to `g x`. -/ meta def apply_congr (q : parse texpr?) : conv unit := do congr_lemmas ← match q with -- If the user specified a lemma, use that one, | some e := do gs ← get_goals, e ← to_expr e, -- to_expr messes with the goals? (see tests) set_goals gs, return [e] -- otherwise, look up everything tagged `@[congr]` | none := do congr_lemma_names ← attribute.get_instances `congr, congr_lemma_names.mmap mk_const end, -- For every lemma: congr_lemmas.any_of (λ n, -- Call tactic.eapply seq' (tactic.eapply n >> tactic.skip) -- and then call `intros` on each resulting goal, and require that afterwards it's an equation. (tactic.intros >> (do `(_ = _) ← target, tactic.skip))) add_tactic_doc { name := "apply_congr", category := doc_category.tactic, decl_names := [`conv.interactive.apply_congr], tags := ["conv", "congruence", "rewriting"] } end conv.interactive
a081fa6cd577d7a0c399bc07c4e8938b92789fc1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/pp_opt_param.lean
cb22ed0a1a4af3020f9c4472c4ae3344ba19bf94
[ "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
110
lean
#check expr #check expr ff def f (x := 3) (y : nat) := y #check f 3 4 set_option pp.implicit true #check expr
7ffb1a705ae2a42f4ea913aa377bbd59cb00028e
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/polynomial/monomial.lean
442c3b7c8cca7ed13f1d8e547358fff147807902
[ "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
2,103
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.basic /-! # Univariate monomials Preparatory lemmas for degree_basic. -/ noncomputable theory open finsupp namespace polynomial universes u variables {R : Type u} {a b : R} {m n : ℕ} variables [semiring R] {p q r : polynomial R} /-- `C a` is the constant polynomial `a`. `C` is provided as a ring homomorphism. -/ def C : R →+* polynomial R := add_monoid_algebra.algebra_map' (ring_hom.id R) @[simp] lemma monomial_zero_left (a : R) : monomial 0 a = C a := rfl lemma C_0 : C (0 : R) = 0 := single_zero lemma C_1 : C (1 : R) = 1 := rfl lemma C_mul : C (a * b) = C a * C b := C.map_mul a b lemma C_add : C (a + b) = C a + C b := C.map_add a b @[simp] lemma C_bit0 : C (bit0 a) = bit0 (C a) := C_add @[simp] lemma C_bit1 : C (bit1 a) = bit1 (C a) := by simp [bit1, C_bit0] lemma C_pow : C (a ^ n) = C a ^ n := C.map_pow a n @[simp] lemma C_eq_nat_cast (n : ℕ) : C (n : R) = (n : polynomial R) := C.map_nat_cast n @[simp] lemma sum_C_index {a} {β} [add_comm_monoid β] {f : ℕ → R → β} (h : f 0 0 = 0) : (C a).sum f = f 0 a := sum_single_index h lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by { convert coeff_monomial using 2, simp [eq_comm], } @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_monomial theorem nonzero.of_polynomial_ne (h : p ≠ q) : nontrivial R := ⟨⟨0, 1, λ h01 : 0 = 1, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero] ⟩⟩ lemma single_eq_C_mul_X : ∀{n}, monomial n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc monomial (n + 1) a = monomial n a * X : by { rw [X, monomial_mul_monomial, mul_one], } ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ end polynomial
1ca9d476605ab4387acdb175edcc37ed12bca319
618003631150032a5676f229d13a079ac875ff77
/src/tactic/apply.lean
8dfb5201dd57ef86721457df466febacdaff3e9e
[ "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
7,900
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import tactic.core /-! This file provides an alternative implementation for `apply` to fix the so-called "apply bug". The issue arises when the goals is a Π-type -- whether it is visible or hidden behind a definition. For instance, consider the following proof: ``` example {α β} (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := begin apply le_trans, end ``` Because `x ≤ z` is definitionally equal to `∀ i, x i ≤ z i`, `apply` will fail. The alternative definition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise, a different strategy is deployed -/ namespace tactic /-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy `new_g` to rearrange the dependent goals to either drop them, push them to the end of the list or leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/ def reorder_goals {α} (gs : list (bool × α)) : new_goals → list α | new_goals.non_dep_first := (gs.filter $ coe ∘ bnot ∘ prod.fst).map prod.snd ++ (gs.filter $ coe ∘ prod.fst).map prod.snd | new_goals.non_dep_only := (gs.filter (coe ∘ bnot ∘ prod.fst)).map prod.snd | new_goals.all := gs.map prod.snd private meta def has_opt_auto_param_inst_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, b ← is_class type, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2 || b) ff private meta def try_apply_opt_auto_param_instance_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_inst_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> try apply_instance >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs private meta def retry_apply_aux : Π (e : expr) (cfg : apply_cfg), list (bool × name × expr) → tactic (list (name × expr)) | e cfg gs := focus1 (do { tgt : expr ← target, t ← infer_type e, unify t tgt, exact e, gs' ← get_goals, let r := reorder_goals gs cfg.new_goals, set_goals (gs' ++ r.map prod.snd), return r }) <|> do (expr.pi n bi d b) ← infer_type e >>= whnf | apply_core e cfg, v ← mk_meta_var d, let b := b.has_var, e ← head_beta $ e v, retry_apply_aux e cfg ((b, n, v) :: gs) private meta def retry_apply (e : expr) (cfg : apply_cfg) : tactic (list (name × expr)) := apply_core e cfg <|> retry_apply_aux e cfg [] /-- `apply'` mimics the behavior of `apply_core`. When `apply_core` fails, it is retried by providing the term with meta variables as additional arguments. The meta variables can then become new goals depending on the `cfg.new_goals` policy. `apply'` also finds instances and applies opt_params and auto_params. -/ meta def apply' (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← retry_apply e cfg, try_apply_opt_auto_param_instance_for_apply cfg r, return r /-- Same as `apply'` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply' (e : expr) : tactic (list (name × expr)) := apply' e {new_goals := new_goals.all} /-- Same as `apply'` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply' (e : expr) : tactic (list (name × expr)) := apply' e {new_goals := new_goals.non_dep_only} /-- `relation_tactic` finds a proof rule for the relation found in the goal and uses `apply'` to make one proof step. -/ private meta def relation_tactic (md : transparency) (op_for : environment → name → option name) (tac_name : string) : tactic unit := do tgt ← target >>= instantiate_mvars, env ← get_env, let r := expr.get_app_fn tgt, match op_for env (expr.const_name r) with | (some refl) := do r ← mk_const refl, retry_apply r {md := md, new_goals := new_goals.non_dep_only }, return () | none := fail $ tac_name ++ " tactic failed, target is not a relation application with the expected property." end /-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply` -/ meta def reflexivity' (md := semireducible) : tactic unit := relation_tactic md environment.refl_for "reflexivity" /-- Similar to `symmetry` with the difference that `apply'` is used instead of `apply` -/ meta def symmetry' (md := semireducible) : tactic unit := relation_tactic md environment.symm_for "symmetry" /-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply` -/ meta def transitivity' (md := semireducible) : tactic unit := relation_tactic md environment.trans_for "transitivity" namespace interactive setup_tactic_parser /-- Similarly to `apply`, the `apply'` tactic tries to match the current goal against the conclusion of the type of term. It differs from `apply` in that it does not unfold definition in order to find out what the assumptions of the provided term is. It is especially useful when defining relations on function spaces (e.g. `≤`) so that rules like transitivity on `le : (α → β) → (α → β) → (α → β)` will be considered to have three parameters and two assumptions (i.e. `f g h : α → β`, `H₀ : f ≤ g`, `H₁ : g ≤ h`) instead of three parameters, two assumptions and then one more parameter (i.e. `f g h : α → β`, `H₀ : f ≤ g`, `H₁ : g ≤ h`, `x : α`). Whereas `apply` would expect the goal `f x ≤ h x`, `apply'` will work with the goal `f ≤ h`. -/ meta def apply' (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply' h) /-- Similar to the `apply'` tactic, but does not reorder goals. -/ meta def fapply' (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply') /-- Similar to the `apply'` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply' (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply') /-- Similar to the `apply'` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with' (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e cfg) /-- Similar to the `apply'` tactic, but uses matching instead of unification. `mapply' t` is equivalent to `apply_with' t {unify := ff}` -/ meta def mapply' (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e {unify := ff}) /-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply`. -/ meta def reflexivity' : tactic unit := tactic.reflexivity' /-- Shorter name for the tactic `reflexivity'`. -/ meta def refl' : tactic unit := tactic.reflexivity' /-- `symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry to assumption `h` -/ meta def symmetry' : parse location → tactic unit | l@loc.wildcard := l.try_apply symmetry_hyp tactic.symmetry' | (loc.ns hs) := (loc.ns hs.reverse).apply symmetry_hyp tactic.symmetry' /-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply`. -/ meta def transitivity' (q : parse texpr?) : tactic unit := tactic.transitivity' >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, t ← infer_type lhs, i_to_expr ``(%%q : %%t) >>= unify rhs end end interactive end tactic
75dedfd3b75190e7a9ee3fad4ac91c407690b65f
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/src/Lean/PrettyPrinter/Delaborator/Builtins.lean
cd051b11ac195697ffb49c79235abab7a7257ef3
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,776
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.PrettyPrinter.Delaborator.Basic import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.PrettyPrinter.Delaborator.TopDownAnalyze import Lean.Parser namespace Lean.PrettyPrinter.Delaborator open Lean.Meta open Lean.Parser.Term open SubExpr def maybeAddBlockImplicit (ident : Syntax) : DelabM Syntax := do if ← getPPOption getPPAnalysisBlockImplicit then `(@$ident:ident) else ident def unfoldMDatas : Expr → Expr | Expr.mdata _ e _ => unfoldMDatas e | e => e @[builtinDelab fvar] def delabFVar : Delab := do let Expr.fvar id _ ← getExpr | unreachable! try let l ← getLocalDecl id maybeAddBlockImplicit (mkIdent l.userName) catch _ => -- loose free variable, use internal name maybeAddBlockImplicit $ mkIdent id.name -- loose bound variable, use pseudo syntax @[builtinDelab bvar] def delabBVar : Delab := do let Expr.bvar idx _ ← getExpr | unreachable! pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx @[builtinDelab mvar] def delabMVar : Delab := do let Expr.mvar n _ ← getExpr | unreachable! let mvarDecl ← getMVarDecl n let n := match mvarDecl.userName with | Name.anonymous => n.name.replacePrefix `_uniq `m | n => n `(?$(mkIdent n)) @[builtinDelab sort] def delabSort : Delab := do let Expr.sort l _ ← getExpr | unreachable! match l with | Level.zero _ => `(Prop) | Level.succ (Level.zero _) _ => `(Type) | _ => match l.dec with | some l' => `(Type $(Level.quote l' max_prec)) | none => `(Sort $(Level.quote l max_prec)) def unresolveNameGlobal (n₀ : Name) : DelabM Name := do if n₀.hasMacroScopes then return n₀ let mut initialNames := #[] if !(← getPPOption getPPFullNames) then initialNames := initialNames ++ getRevAliases (← getEnv) n₀ initialNames := initialNames.push (rootNamespace ++ n₀) for initialName in initialNames do match (← unresolveNameCore initialName) with | none => continue | some n => return n return n₀ -- if can't resolve, return the original where unresolveNameCore (n : Name) : DelabM (Option Name) := do let mut revComponents := n.components' let mut candidate := Name.anonymous for i in [:revComponents.length] do match revComponents with | [] => return none | cmpt::rest => candidate := cmpt ++ candidate; revComponents := rest match (← resolveGlobalName candidate) with | [(potentialMatch, _)] => if potentialMatch == n₀ then return some candidate else continue | _ => continue return none -- NOTE: not a registered delaborator, as `const` is never called (see [delab] description) def delabConst : Delab := do let Expr.const c₀ ls _ ← getExpr | unreachable! let ctx ← read let c₀ := if (← getPPOption getPPPrivateNames) then c₀ else (privateToUserName? c₀).getD c₀ let mut c ← unresolveNameGlobal c₀ let stx ← if ls.isEmpty || !(← getPPOption getPPUniverses) then if (← getLCtx).usesUserName c then -- `c` is also a local declaration if c == c₀ && !(← read).inPattern then -- `c` is the fully qualified named. So, we append the `_root_` prefix c := `_root_ ++ c else c := c₀ return mkIdent c else `($(mkIdent c).{$[$(ls.toArray.map quote)],*}) maybeAddBlockImplicit stx structure ParamKind where name : Name bInfo : BinderInfo defVal : Option Expr := none isAutoParam : Bool := false def ParamKind.isRegularExplicit (param : ParamKind) : Bool := param.bInfo.isExplicit && !param.isAutoParam && param.defVal.isNone /-- Return array with n-th element set to kind of n-th parameter of `e`. -/ partial def getParamKinds : DelabM (Array ParamKind) := do let e ← getExpr try withTransparency TransparencyMode.all do forallTelescopeArgs e.getAppFn e.getAppArgs fun params _ => do params.mapM fun param => do let l ← getLocalDecl param.fvarId! pure { name := l.userName, bInfo := l.binderInfo, defVal := l.type.getOptParamDefault?, isAutoParam := l.type.isAutoParam } catch _ => pure #[] -- recall that expr may be nonsensical where forallTelescopeArgs f args k := do forallBoundedTelescope (← inferType f) args.size fun xs b => if xs.isEmpty || xs.size == args.size then -- we still want to consider optParams forallTelescopeReducing b fun ys b => k (xs ++ ys) b else forallTelescopeArgs (mkAppN f $ args.shrink xs.size) (args.extract xs.size args.size) fun ys b => k (xs ++ ys) b @[builtinDelab app] def delabAppExplicit : Delab := whenPPOption getPPExplicit do let paramKinds ← getParamKinds let (fnStx, _, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let needsExplicit := paramKinds.any (fun param => !param.isRegularExplicit) && stx.getKind != `Lean.Parser.Term.explicit let stx ← if needsExplicit then `(@$stx) else pure stx pure (stx, paramKinds.toList, #[])) (fun ⟨fnStx, paramKinds, argStxs⟩ => do let isInstImplicit := match paramKinds with | [] => false | param :: _ => param.bInfo == BinderInfo.instImplicit let argStx ← if ← getPPOption getPPAnalysisHole then `(_) else if isInstImplicit == true then let stx ← if ← getPPOption getPPInstances then delab else `(_) if ← getPPOption getPPInstanceTypes then let typeStx ← withType delab `(($stx : $typeStx)) else stx else delab pure (fnStx, paramKinds.tailD [], argStxs.push argStx)) Syntax.mkApp fnStx argStxs def shouldShowMotive (motive : Expr) (opts : Options) : MetaM Bool := do getPPMotivesAll opts <||> (← getPPMotivesPi opts <&&> returnsPi motive) <||> (← getPPMotivesNonConst opts <&&> isNonConstFun motive) def withMDataOptions [Inhabited α] (x : DelabM α) : DelabM α := do match ← getExpr with | Expr.mdata m .. => let mut posOpts := (← read).optionsPerPos let pos ← getPos for (k, v) in m do if (`pp).isPrefixOf k then let opts := posOpts.find? pos |>.getD {} posOpts := posOpts.insert pos (opts.insert k v) withReader ({ · with optionsPerPos := posOpts }) $ withMDataExpr x | _ => x partial def withMDatasOptions [Inhabited α] (x : DelabM α) : DelabM α := do if (← getExpr).isMData then withMDataOptions (withMDatasOptions x) else x def isRegularApp : DelabM Bool := do let e ← getExpr if not (unfoldMDatas e.getAppFn).isConst then return false if ← withNaryFn (withMDatasOptions (getPPOption getPPUniverses <||> getPPOption getPPAnalysisBlockImplicit)) then return false for i in [:e.getAppNumArgs] do if ← withNaryArg i (getPPOption getPPAnalysisNamedArg) then return false return true def unexpandRegularApp (stx : Syntax) : Delab := do let Expr.const c .. ← pure (unfoldMDatas (← getExpr).getAppFn) | unreachable! let fs ← appUnexpanderAttribute.getValues (← getEnv) c fs.firstM fun f => match f stx |>.run () with | EStateM.Result.ok stx _ => pure stx | _ => failure -- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β -- abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a def unexpandCoe (stx : Syntax) : Delab := whenPPOption getPPCoercions do if not (← isCoe (← getExpr)) then failure let e ← getExpr match stx with | `($fn $arg) => arg | `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*) | _ => failure def unexpandStructureInstance (stx : Syntax) : Delab := whenPPOption getPPStructureInstances do let env ← getEnv let e ← getExpr let some s ← pure $ e.isConstructorApp? env | failure guard $ isStructure env s.induct; /- If implicit arguments should be shown, and the structure has parameters, we should not pretty print using { ... }, because we will not be able to see the parameters. -/ let fieldNames := getStructureFields env s.induct let mut fields := #[] guard $ fieldNames.size == stx[1].getNumArgs let args := e.getAppArgs let fieldVals := args.extract s.numParams args.size for idx in [:fieldNames.size] do let fieldName := fieldNames[idx] let fieldId := mkIdent fieldName let fieldPos ← nextExtraPos let fieldId := annotatePos fieldPos fieldId addFieldInfo fieldPos (s.induct ++ fieldName) fieldName fieldId fieldVals[idx] let field ← `(structInstField|$fieldId:ident := $(stx[1][idx]):term) fields := fields.push field let tyStx ← withType do if (← getPPOption getPPStructureInstanceType) then delab >>= pure ∘ some else pure none if fields.isEmpty then `({ $[: $tyStx]? }) else let lastField := fields.back fields := fields.pop `({ $[$fields, ]* $lastField $[: $tyStx]? }) @[builtinDelab app] def delabAppImplicit : Delab := do -- TODO: always call the unexpanders, make them guard on the right # args? let paramKinds ← getParamKinds if ← getPPOption getPPExplicit then if paramKinds.any (fun param => !param.isRegularExplicit) then failure let (fnStx, _, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab pure (stx, paramKinds.toList, #[])) (fun (fnStx, paramKinds, argStxs) => do let arg ← getExpr let opts ← getOptions let mkNamedArg (name : Name) (argStx : Syntax) : DelabM Syntax := do `(Parser.Term.namedArgument| ($(← mkIdent name):ident := $argStx:term)) let argStx? : Option Syntax ← if ← getPPOption getPPAnalysisSkip then pure none else if ← getPPOption getPPAnalysisHole then `(_) else match paramKinds with | [] => delab | param :: rest => if param.defVal.isSome && rest.isEmpty then let v := param.defVal.get! if !v.hasLooseBVars && v == arg then none else delab else if !param.isRegularExplicit && param.defVal.isNone then if ← getPPOption getPPAnalysisNamedArg <||> (param.name == `motive <&&> shouldShowMotive arg opts) then mkNamedArg param.name (← delab) else none else delab let argStxs := match argStx? with | none => argStxs | some stx => argStxs.push stx pure (fnStx, paramKinds.tailD [], argStxs)) let stx := Syntax.mkApp fnStx argStxs if ← isRegularApp then (guard (← getPPOption getPPNotation) *> unexpandRegularApp stx) <|> (guard (← getPPOption getPPStructureInstances) *> unexpandStructureInstance stx) <|> (guard (← getPPOption getPPNotation) *> unexpandCoe stx) <|> pure stx else pure stx /-- State for `delabAppMatch` and helpers. -/ structure AppMatchState where info : MatcherInfo matcherTy : Expr params : Array Expr := #[] motive : Option (Syntax × Expr) := none motiveNamed : Bool := false discrs : Array Syntax := #[] varNames : Array (Array Name) := #[] rhss : Array Syntax := #[] -- additional arguments applied to the result of the `match` expression moreArgs : Array Syntax := #[] /-- Extract arguments of motive applications from the matcher type. For the example below: `#[#[`([])], #[`(a::as)]]` -/ private partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) := withReader (fun ctx => { ctx with inPattern := true, optionsPerPos := {} }) do let ty ← instantiateForall st.matcherTy st.params forallTelescope ty fun params _ => do -- skip motive and discriminators let alts := Array.ofSubarray params[1 + st.discrs.size:] alts.mapIdxM fun idx alt => do let ty ← inferType alt -- TODO: this is a hack; we are accessing the expression out-of-sync with the position -- Currently, we reset `optionsPerPos` at the beginning of `delabPatterns` to avoid -- incorrectly considering annotations. withTheReader SubExpr ({ · with expr := ty }) $ usingNames st.varNames[idx] do withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (← delab)) where usingNames {α} (varNames : Array Name) (x : DelabM α) : DelabM α := usingNamesAux 0 varNames x usingNamesAux {α} (i : Nat) (varNames : Array Name) (x : DelabM α) : DelabM α := if i < varNames.size then withBindingBody varNames[i] <| usingNamesAux (i+1) varNames x else x /-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/ private partial def skippingBinders {α} (numParams : Nat) (x : Array Name → DelabM α) : DelabM α := loop numParams #[] where loop : Nat → Array Name → DelabM α | 0, varNames => x varNames | n+1, varNames => do let rec visitLambda : DelabM α := do let varName ← (← getExpr).bindingName!.eraseMacroScopes -- Pattern variables cannot shadow each other if varNames.contains varName then let varName := (← getLCtx).getUnusedName varName withBindingBody varName do loop n (varNames.push varName) else withBindingBodyUnusedName fun id => do loop n (varNames.push id.getId) let e ← getExpr if e.isLambda then visitLambda else -- eta expand `e` let e ← forallTelescopeReducing (← inferType e) fun xs _ => do if xs.size == 1 && (← inferType xs[0]).isConstOf ``Unit then -- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable. -- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable. -- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure -- it adds an annotation to distinguish these two cases. mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit)) else mkLambdaFVars xs (mkAppN e xs) withTheReader SubExpr (fun ctx => { ctx with expr := e }) visitLambda /-- Delaborate applications of "matchers" such as ``` List.map.match_1 : {α : Type _} → (motive : List α → Sort _) → (x : List α) → (Unit → motive List.nil) → ((a : α) → (as : List α) → motive (a :: as)) → motive x ``` -/ @[builtinDelab app] def delabAppMatch : Delab := whenPPOption getPPNotation <| whenPPOption getPPMatch do -- incrementally fill `AppMatchState` from arguments let st ← withAppFnArgs (do let (Expr.const c us _) ← getExpr | failure let (some info) ← getMatcherInfo? c | failure { matcherTy := (← getConstInfo c).instantiateTypeLevelParams us, info := info : AppMatchState }) (fun st => do if st.params.size < st.info.numParams then pure { st with params := st.params.push (← getExpr) } else if st.motive.isNone then -- store motive argument separately let lamMotive ← getExpr let piMotive ← lambdaTelescope lamMotive fun xs body => mkForallFVars xs body -- TODO: pp.analyze has not analyzed `piMotive`, only `lamMotive` -- Thus the binder types won't have any annotations let piStx ← withTheReader SubExpr (fun cfg => { cfg with expr := piMotive }) delab let named ← getPPOption getPPAnalysisNamedArg pure { st with motive := (piStx, lamMotive), motiveNamed := named } else if st.discrs.size < st.info.numDiscrs then pure { st with discrs := st.discrs.push (← delab) } else if st.rhss.size < st.info.altNumParams.size then /- We save the variables names here to be able to implement safe_shadowing. The pattern delaboration must use the names saved here. -/ let (varNames, rhs) ← skippingBinders st.info.altNumParams[st.rhss.size] fun varNames => do let rhs ← delab return (varNames, rhs) pure { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames } else pure { st with moreArgs := st.moreArgs.push (← delab) }) if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then -- underapplied failure match st.discrs, st.rhss with | #[discr], #[] => let stx ← `(nomatch $discr) Syntax.mkApp stx st.moreArgs | _, #[] => failure | _, _ => let pats ← delabPatterns st let stx ← do let (piStx, lamMotive) := st.motive.get! let opts ← getOptions -- TODO: disable the match if other implicits are needed? if ← st.motiveNamed <||> shouldShowMotive lamMotive opts then `(match $[$st.discrs:term],* : $piStx with $[| $pats,* => $st.rhss]*) else `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*) Syntax.mkApp stx st.moreArgs /-- Delaborate applications of the form `(fun x => b) v` as `let_fun x := v; b` -/ def delabLetFun : Delab := do let stxV ← withAppArg delab withAppFn do let Expr.lam n t b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxB ← withBindingBody n delab if ← getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then let stxT ← withBindingDomain delab `(let_fun $(mkIdent n) : $stxT := $stxV; $stxB) else `(let_fun $(mkIdent n) := $stxV; $stxB) @[builtinDelab mdata] def delabMData : Delab := do if let some _ := Lean.Meta.Match.inaccessible? (← getExpr) then let s ← withMDataExpr delab if (← read).inPattern then `(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns else return s else if isLetFun (← getExpr) then withMDataExpr <| delabLetFun else if let some _ := isLHSGoal? (← getExpr) then withMDataExpr <| withAppFn <| withAppArg <| delab else withMDataOptions delab /-- Check for a `Syntax.ident` of the given name anywhere in the tree. This is usually a bad idea since it does not check for shadowing bindings, but in the delaborator we assume that bindings are never shadowed. -/ partial def hasIdent (id : Name) : Syntax → Bool | Syntax.ident _ _ id' _ => id == id' | Syntax.node _ args => args.any (hasIdent id) | _ => false /-- Return `true` iff current binder should be merged with the nested binder, if any, into a single binder group: * both binders must have same binder info and domain * they cannot be inst-implicit (`[a b : A]` is not valid syntax) * `pp.binderTypes` must be the same value for both terms * prefer `fun a b` over `fun (a b)` -/ private def shouldGroupWithNext : DelabM Bool := do let e ← getExpr let ppEType ← getPPOption (getPPBinderTypes e) let go (e' : Expr) := do let ppE'Type ← withBindingBody `_ $ getPPOption (getPPBinderTypes e) pure $ e.binderInfo == e'.binderInfo && e.bindingDomain! == e'.bindingDomain! && e'.binderInfo != BinderInfo.instImplicit && ppEType == ppE'Type && (e'.binderInfo != BinderInfo.default || ppE'Type) match e with | Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e' | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e' | _ => pure false where getPPBinderTypes (e : Expr) := if e.isForall then getPPPiBinderTypes else getPPFunBinderTypes private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types. | curNames => do if ← shouldGroupWithNext then -- group with nested binder => recurse immediately withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN) else -- don't group => delab body and prepend current binder group let (stx, stxN) ← withBindingBodyUnusedName fun stxN => do (← delab, stxN) delabGroup (curNames.push stxN) stx @[builtinDelab lam] def delabLam : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let stxT ← withBindingDomain delab let ppTypes ← getPPOption getPPFunBinderTypes let expl ← getPPOption getPPExplicit let usedDownstream ← curNames.any (fun n => hasIdent n.getId stxBody) -- leave lambda implicit if possible -- TODO: for now we just always block implicit lambdas when delaborating. We can revisit. -- Note: the current issue is that it requires state, i.e. if *any* previous binder was implicit, -- it doesn't seem like we can leave a subsequent binder implicit. let blockImplicitLambda := true /- let blockImplicitLambda := expl || e.binderInfo == BinderInfo.default || -- Note: the following restriction fixes many issues with roundtripping, -- but this condition may still not be perfectly in sync with the elaborator. e.binderInfo == BinderInfo.instImplicit || Elab.Term.blockImplicitLambda stxBody || usedDownstream -/ if !blockImplicitLambda then pure stxBody else let group ← match e.binderInfo, ppTypes with | BinderInfo.default, true => -- "default" binder group is the only one that expects binder names -- as a term, i.e. a single `Syntax.ident` or an application thereof let stxCurNames ← if curNames.size > 1 then `($(curNames.get! 0) $(curNames.eraseIdx 0)*) else pure $ curNames.get! 0; `(funBinder| ($stxCurNames : $stxT)) | BinderInfo.default, false => pure curNames.back -- here `curNames.size == 1` | BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT}) | BinderInfo.implicit, false => `(funBinder| {$curNames*}) | BinderInfo.strictImplicit, true => `(funBinder| ⦃$curNames* : $stxT⦄) | BinderInfo.strictImplicit, false => `(funBinder| ⦃$curNames*⦄) | BinderInfo.instImplicit, _ => if usedDownstream then `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1` else `(funBinder| [$stxT]) | _ , _ => unreachable!; match stxBody with | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody) | _ => `(fun $group => $stxBody) @[builtinDelab forallE] def delabForall : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let prop ← try isProp e catch _ => false let stxT ← withBindingDomain delab let group ← match e.binderInfo with | BinderInfo.implicit => `(bracketedBinderF|{$curNames* : $stxT}) | BinderInfo.strictImplicit => `(bracketedBinderF|⦃$curNames* : $stxT⦄) -- here `curNames.size == 1` | BinderInfo.instImplicit => `(bracketedBinderF|[$curNames.back : $stxT]) | _ => -- heuristic: use non-dependent arrows only if possible for whole group to avoid -- noisy mix like `(α : Type) → Type → (γ : Type) → ...`. let dependent := curNames.any $ fun n => hasIdent n.getId stxBody -- NOTE: non-dependent arrows are available only for the default binder info if dependent then if prop && !(← getPPOption getPPPiBinderTypes) then return ← `(∀ $curNames:ident*, $stxBody) else `(bracketedBinderF|($curNames* : $stxT)) else return ← curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody if prop then match stxBody with | `(∀ $groups*, $stxBody) => `(∀ $group $groups*, $stxBody) | _ => `(∀ $group, $stxBody) else `($group:bracketedBinder → $stxBody) @[builtinDelab letE] def delabLetE : Delab := do let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxV ← descend v 1 delab let stxB ← withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 delab if ← getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then let stxT ← descend t 0 delab `(let $(mkIdent n) : $stxT := $stxV; $stxB) else `(let $(mkIdent n) := $stxV; $stxB) @[builtinDelab lit] def delabLit : Delab := do let Expr.lit l _ ← getExpr | unreachable! match l with | Literal.natVal n => pure $ quote n | Literal.strVal s => pure $ quote s -- `@OfNat.ofNat _ n _` ~> `n` @[builtinDelab app.OfNat.ofNat] def delabOfNat : Delab := whenPPOption getPPCoercions do let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) ← getExpr | failure return quote n -- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true` @[builtinDelab app.OfScientific.ofScientific] def delabOfScientific : Delab := whenPPOption getPPCoercions do let expr ← getExpr guard <| expr.getAppNumArgs == 5 let Expr.lit (Literal.natVal m) _ ← pure (expr.getArg! 2) | failure let Expr.lit (Literal.natVal e) _ ← pure (expr.getArg! 4) | failure let s ← match expr.getArg! 3 with | Expr.const `Bool.true _ _ => pure true | Expr.const `Bool.false _ _ => pure false | _ => failure let str := toString m if s && e == str.length then return Syntax.mkScientificLit ("0." ++ str) else if s && e < str.length then let mStr := str.extract 0 (str.length - e) let eStr := str.extract (str.length - e) str.length return Syntax.mkScientificLit (mStr ++ "." ++ eStr) else return Syntax.mkScientificLit (str ++ "e" ++ (if s then "-" else "") ++ toString e) /-- Delaborate a projection primitive. These do not usually occur in user code, but are pretty-printed when e.g. `#print`ing a projection function. -/ @[builtinDelab proj] def delabProj : Delab := do let Expr.proj _ idx _ _ ← getExpr | unreachable! let e ← withProj delab -- not perfectly authentic: elaborates to the `idx`-th named projection -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual -- `proj`. let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1)); `($(e).$idx:fieldIdx) /-- Delaborate a call to a projection function such as `Prod.fst`. -/ @[builtinDelab app] def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do let e@(Expr.app fn _ _) ← getExpr | failure let Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure let env ← getEnv let some info ← pure $ env.getProjectionFnInfo? c | failure -- can't use with classes since the instance parameter is implicit guard $ !info.fromClass -- projection function should be fully applied (#struct params + 1 instance parameter) -- TODO: support over-application guard $ e.getAppNumArgs == info.numParams + 1 -- If pp.explicit is true, and the structure has parameters, we should not -- use field notation because we will not be able to see the parameters. let expl ← getPPOption getPPExplicit guard $ !expl || info.numParams == 0 let appStx ← withAppArg delab `($(appStx).$(mkIdent f):ident) @[builtinDelab app.dite] def delabDIte : Delab := whenPPOption getPPNotation do -- Note: we keep this as a delaborator for now because it actually accesses the expression. guard $ (← getExpr).getAppNumArgs == 5 let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab let (t, h) ← withAppFn $ withAppArg $ delabBranch none let (e, _) ← withAppArg $ delabBranch h `(if $(mkIdent h):ident : $c then $t else $e) where delabBranch (h? : Option Name) : DelabM (Syntax × Name) := do let e ← getExpr guard e.isLambda let h ← match h? with | some h => return (← withBindingBody h delab, h) | none => withBindingBodyUnusedName fun h => do return (← delab, h.getId) @[builtinDelab app.namedPattern] def delabNamedPattern : Delab := do -- Note: we keep this as a delaborator because it accesses the DelabM context guard (← read).inPattern guard $ (← getExpr).getAppNumArgs == 3 let x ← withAppFn $ withAppArg delab let p ← withAppArg delab guard x.isIdent `($x:ident@$p:term) -- Sigma and PSigma delaborators def delabSigmaCore (sigma : Bool) : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 2 guard $ (← getExpr).appArg!.isLambda withAppArg do let α ← withBindingDomain delab let bodyExpr := (← getExpr).bindingBody! withBindingBodyUnusedName fun n => do let b ← delab if bodyExpr.hasLooseBVars then if sigma then `(($n:ident : $α) × $b) else `(($n:ident : $α) ×' $b) else if sigma then `((_ : $α) × $b) else `((_ : $α) ×' $b) @[builtinDelab app.Sigma] def delabSigma : Delab := delabSigmaCore (sigma := true) @[builtinDelab app.PSigma] def delabPSigma : Delab := delabSigmaCore (sigma := false) partial def delabDoElems : DelabM (List Syntax) := do let e ← getExpr if e.isAppOfArity `Bind.bind 6 then -- Bind.bind.{u, v} : {m : Type u → Type v} → [self : Bind m] → {α β : Type u} → m α → (α → m β) → m β let α := e.getAppArgs[2] let ma ← withAppFn $ withAppArg delab withAppArg do match (← getExpr) with | Expr.lam _ _ body _ => withBindingBodyUnusedName fun n => do if body.hasLooseBVars then prependAndRec `(doElem|let $n:term ← $ma:term) else if α.isConstOf `Unit || α.isConstOf `PUnit then prependAndRec `(doElem|$ma:term) else prependAndRec `(doElem|let _ ← $ma:term) | _ => failure else if e.isLet then let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxT ← descend t 0 delab let stxV ← descend v 1 delab withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 $ prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV) else let stx ← delab [←`(doElem|$stx:term)] where prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems @[builtinDelab app.Bind.bind] def delabDo : Delab := whenPPOption getPPNotation do guard <| (← getExpr).isAppOfArity `Bind.bind 6 let elems ← delabDoElems let items ← elems.toArray.mapM (`(doSeqItem|$(·):doElem)) `(do $items:doSeqItem*) def reifyName : Expr → DelabM Name | Expr.const ``Lean.Name.anonymous .. => Name.anonymous | Expr.app (Expr.app (Expr.const ``Lean.Name.mkStr ..) n _) (Expr.lit (Literal.strVal s) _) _ => do (← reifyName n).mkStr s | Expr.app (Expr.app (Expr.const ``Lean.Name.mkNum ..) n _) (Expr.lit (Literal.natVal i) _) _ => do (← reifyName n).mkNum i | _ => failure @[builtinDelab app.Lean.Name.mkStr] def delabNameMkStr : Delab := whenPPOption getPPNotation do let n ← reifyName (← getExpr) -- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!"`{n}"] @[builtinDelab app.Lean.Name.mkNum] def delabNameMkNum : Delab := delabNameMkStr end Lean.PrettyPrinter.Delaborator
57703efb6ca473a2b9e3f1d3203676be9b895ed9
b29f946a2f0afd23ef86b9219116968babbb9f4f
/src/examples/scratch.lean
120b6a6fd0cd8e4330154206f82b25f8a07b1275
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M1P1-lean
58be7394fded719d95e45e6b10e1ecf2ed3c7c4c
3723468cc50f8bebd00a9811caf25224a578de17
refs/heads/master
1,587,063,867,779
1,572,727,164,000
1,572,727,164,000
165,845,802
14
4
Apache-2.0
1,549,730,698,000
1,547,554,675,000
Lean
UTF-8
Lean
false
false
194
lean
import data.real.basic tactic.ring example (a b l m : ℝ) : abs(a + (b + (-l - m))) = abs(a + (-l + (b - m))) := -- by ring -- I think this used to work but now it doesn't by congr' 1; ring
2a307b6bf5cb6e46566d353ecdffb3b8ab161820
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/topology/uniform_space/basic.lean
f7b79f21ce458c68e69bda6da093f6a428176c67
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
41,956
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, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter.basic order.filter.lift topology.separation open set lattice filter classical open_locale classical set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, {p | prod.swap p ∈ r} ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[extensionality] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), comp_rel s s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := assume s hs, show {x | (a, a) ∈ s} ∈ f, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, comp_rel t t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), comp_rel t t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (comp_rel s s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (comp_rel s s)) = ((𝓤 α).lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : s ∈ nhds x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : nhds x = (𝓤 α).comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, (𝓤 α).sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, (𝓤 α).sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ nhds x := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ nhds y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ nhds (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, {x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b (𝓤 α) lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf end uniform_space end open_locale uniformity section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₂, exact (mem_singleton_iff.1 h).symm ▸ h₁ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, begin rw [infi_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, (@nhds_eq_uniformity α (u i) a).symm), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (le_infi $ assume i, to_topological_space_mono $ infi_le _ _) (have infi u = ⊤, from top_unique $ le_infi $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (infi u) = ⊤, from this.symm ▸ to_topological_space_top, this.symm ▸ le_top)) lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi, to_topological_space_infi], apply congr rfl, funext x, exact to_topological_space_infi end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ nhds a) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod (𝓤 α) (𝓤 β)) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invarant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] local notation f `∘₂` g := function.bicompr f g def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry' f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry' f) := iff.rfl lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [←uncurry'_curry f] {occs := occurrences.pos [2]} ; refl lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ comp_rel tα tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ comp_rel tβ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂
0e84201d6dcb6e9dff6f34855dae7a9a275f5dfa
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/filter/curry.lean
e5aeb997aca00c0b2dc5dd17113be02486bf5508
[ "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
3,667
lean
/- Copyright (c) 2022 Kevin H. Wilson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin H. Wilson -/ import order.filter.prod /-! # Curried Filters This file provides an operation (`filter.curry`) on filters which provides the equivalence `∀ᶠ a in l, ∀ᶠ b in l', p (a, b) ↔ ∀ᶠ c in (l.curry l'), p c` (see `filter.eventually_curry_iff`). To understand when this operation might arise, it is helpful to think of `∀ᶠ` as a combination of the quantifiers `∃ ∀`. For instance, `∀ᶠ n in at_top, p n ↔ ∃ N, ∀ n ≥ N, p n`. A curried filter yields the quantifier order `∃ ∀ ∃ ∀`. For instance, `∀ᶠ n in at_top.curry at_top, p n ↔ ∃ M, ∀ m ≥ M, ∃ N, ∀ n ≥ N, p (m, n)`. This is different from a product filter, which instead yields a quantifier order `∃ ∃ ∀ ∀`. For instance, `∀ᶠ n in at_top ×ᶠ at_top, p n ↔ ∃ M, ∃ N, ∀ m ≥ M, ∀ n ≥ N, p (m, n)`. This makes it clear that if something eventually occurs on the product filter, it eventually occurs on the curried filter (see `filter.curry_le_prod` and `filter.eventually.curry`), but the converse is not true. Another way to think about the curried versus the product filter is that tending to some limit on the product filter is a version of uniform convergence (see `tendsto_prod_filter_iff`) whereas tending to some limit on a curried filter is just iterated limits (see `tendsto.curry`). ## Main definitions * `filter.curry`: A binary operation on filters which represents iterated limits ## Main statements * `filter.eventually_curry_iff`: An alternative definition of a curried filter * `filter.curry_le_prod`: Something that is eventually true on the a product filter is eventually true on the curried filter ## Tags uniform convergence, curried filters, product filters -/ namespace filter variables {α β γ : Type*} /-- This filter is characterized by `filter.eventually_curry_iff`: `(∀ᶠ (x : α × β) in f.curry g, p x) ↔ ∀ᶠ (x : α) in f, ∀ᶠ (y : β) in g, p (x, y)`. Useful in adding quantifiers to the middle of `tendsto`s. See `has_fderiv_at_of_tendsto_uniformly_on_filter`. -/ def curry (f : filter α) (g : filter β) : filter (α × β) := { sets := { s | ∀ᶠ (a : α) in f, ∀ᶠ (b : β) in g, (a, b) ∈ s }, univ_sets := (by simp only [set.mem_set_of_eq, set.mem_univ, eventually_true]), sets_of_superset := begin intros x y hx hxy, simp only [set.mem_set_of_eq] at hx ⊢, exact hx.mono (λ a ha, ha.mono(λ b hb, set.mem_of_subset_of_mem hxy hb)), end, inter_sets := begin intros x y hx hy, simp only [set.mem_set_of_eq, set.mem_inter_eq] at hx hy ⊢, exact (hx.and hy).mono (λ a ha, (ha.1.and ha.2).mono (λ b hb, hb)), end, } lemma eventually_curry_iff {f : filter α} {g : filter β} {p : α × β → Prop} : (∀ᶠ (x : α × β) in f.curry g, p x) ↔ ∀ᶠ (x : α) in f, ∀ᶠ (y : β) in g, p (x, y) := iff.rfl lemma curry_le_prod {f : filter α} {g : filter β} : f.curry g ≤ f.prod g := begin intros u hu, rw ←eventually_mem_set at hu ⊢, rw eventually_curry_iff, exact hu.curry, end lemma tendsto.curry {f : α → β → γ} {la : filter α} {lb : filter β} {lc : filter γ} : (∀ᶠ a in la, tendsto (λ b : β, f a b) lb lc) → tendsto ↿f (la.curry lb) lc := begin intros h, rw tendsto_def, simp only [curry, filter.mem_mk, set.mem_set_of_eq, set.mem_preimage], simp_rw tendsto_def at h, refine (λ s hs, h.mono (λ a ha, eventually_iff.mpr _)), simpa [function.has_uncurry.uncurry, set.preimage] using ha s hs, end end filter
69c91dfcd83b5ebae49d09066164a0d7cd40c398
f4bff2062c030df03d65e8b69c88f79b63a359d8
/ideas/sup_inf_world.lean
2efdd96b70b8a0fdd23330ca55885639e50a6495
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
100
lean
-- world 1 import data.real.basic definition is_ub (X : set ℝ) (b : ℝ) := ∀ x ∈ X, x ≤ b
c48aad667a2e3f366d86a7e8148b9fe6dfefbc8c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/tuple.lean
6cffe335c6387380a82e318e613f8b56e61f5252
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
156
lean
import data.prod open nat prod set_option pp.universes true definition tuple (A : Type) (n : nat) : Type := nat.rec_on n A (λ n r, r × A) check @tuple
4c82d5170ca89968ef5cd992274280c23dd43641
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/linear_algebra/direct_sum_module.lean
3e0ccf03d9855b04c9879f85e0eda2323bd6d6ff
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
3,512
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of modules over commutative rings, indexed by a discrete type. -/ import algebra.direct_sum import linear_algebra.basic universes u v w u₁ variables (R : Type u) [ring R] variables (ι : Type v) [decidable_eq ι] (M : ι → Type w) variables [Π i, add_comm_group (M i)] [Π i, module R (M i)] include R namespace direct_sum variables {R ι M} instance : module R (direct_sum ι M) := dfinsupp.to_module variables R ι M def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.1) →ₗ[R] direct_sum ι M := dfinsupp.lmk M R def lof : Π i : ι, M i →ₗ[R] direct_sum ι M := dfinsupp.lsingle M R variables {ι M} lemma single_eq_lof (i : ι) (b : M i) : dfinsupp.single i b = lof R ι M i b := rfl theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x := (lmk R ι M s).map_smul c x theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x := (lof R ι M i).map_smul c x variables {N : Type u₁} [add_comm_group N] [module R N] variables (φ : Π i, M i →ₗ[R] N) variables (ι N φ) def to_module : direct_sum ι M →ₗ[R] N := { to_fun := to_group (λ i, φ i), add := to_group_add _, smul := λ c x, direct_sum.induction_on x (by rw [smul_zero, to_group_zero, smul_zero]) (λ i x, by rw [← of_smul, to_group_of, to_group_of, (φ i).map_smul c x]) (λ x y ihx ihy, by rw [smul_add, to_group_add, ihx, ihy, to_group_add, smul_add]) } variables {ι N φ} @[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x := to_group_of (λ i, φ i) i x variables (ψ : direct_sum ι M →ₗ[R] N) theorem to_module.unique (f : direct_sum ι M) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f := to_group.unique ψ f variables {ψ} {ψ' : direct_sum ι M →ₗ[R] N} theorem to_module.ext (H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) (f : direct_sum ι M) : ψ f = ψ' f := by rw [to_module.unique R ψ, to_module.unique R ψ', funext H] def lset_to_set (S T : set ι) (H : S ⊆ T) : direct_sum S (M ∘ subtype.val) →ₗ direct_sum T (M ∘ subtype.val) := to_module R _ _ $ λ i, lof R T (M ∘ @subtype.val _ T) ⟨i.1, H i.2⟩ protected def lid (M : Type v) [add_comm_group M] [module R M] : direct_sum punit (λ _, M) ≃ₗ M := { .. direct_sum.id M, .. to_module R punit M (λ i, linear_map.id) } variables (ι M) def component (i : ι) : direct_sum ι M →ₗ[R] M i := { to_fun := λ f, f i, add := λ _ _, dfinsupp.add_apply, smul := λ _ _, dfinsupp.smul_apply } variables {ι M} @[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b := by rw [lof, dfinsupp.lsingle_apply, dfinsupp.single_apply, dif_pos rfl] lemma apply_eq_component (f : direct_sum ι M) (i : ι) : f i = component R ι M i f := rfl @[simp] lemma component.lof_self (i : ι) (b : M i) : component R ι M i ((lof R ι M i) b) = b := lof_apply R i b lemma component.of (i j : ι) (b : M j) : component R ι M i ((lof R ι M j) b) = if h : j = i then eq.rec_on h b else 0 := dfinsupp.single_apply @[extensionality] lemma ext {f g : direct_sum ι M} (h : ∀ i, component R ι M i f = component R ι M i g) : f = g := dfinsupp.ext h lemma ext_iff {f g : direct_sum ι M} : f = g ↔ ∀ i, component R ι M i f = component R ι M i g := ⟨λ h _, by rw h, ext R⟩ end direct_sum
bf5cbf6aa82fb707f0c8b03b8a7bb5e116970c5f
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
/order/order_iso.lean
ce0b92ab36bc0930782d9191c2867bd195ace771
[ "Apache-2.0" ]
permissive
louisanu/mathlib
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
refs/heads/master
1,617,706,993,439
1,523,163,654,000
1,523,163,654,000
124,519,997
0
0
Apache-2.0
1,520,588,283,000
1,520,588,283,000
null
UTF-8
Lean
false
false
12,546
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 order.basic logic.embedding open function universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} structure order_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (ord : ∀ {a b}, r a b ↔ s (to_embedding a) (to_embedding b)) infix ` ≼o `:50 := order_embedding /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage namespace order_embedding instance : has_coe_to_fun (r ≼o s) := ⟨λ _, α → β, λ o, o.to_embedding⟩ theorem ord' : ∀ (f : r ≼o s) {a b}, r a b ↔ s (f a) (f b) | ⟨f, o⟩ := @o @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@order_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ≼o s) : (f.to_embedding : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≼o s}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by congr; exact h @[refl] protected def refl (r : α → α → Prop) : r ≼o r := ⟨embedding.refl _, λ a b, iff.rfl⟩ @[trans] protected def trans : r ≼o s → s ≼o t → r ≼o t | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ := ⟨f₁.trans f₂, λ a b, by rw [o₁, o₂]; simp⟩ @[simp] theorem refl_apply (x : α) : order_embedding.refl r x = x := rfl @[simp] theorem trans_apply : ∀ (f : r ≼o s) (g : s ≼o t) (a : α), (f.trans g) a = g (f a) | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ a := rfl /-- An order embedding is also an order embedding between dual orders. -/ def rsymm (f : r ≼o s) : swap r ≼o swap s := ⟨f.to_embedding, λ a b, f.ord'⟩ /-- If `f` is injective, then it is an order embedding from the preimage order of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ≼o s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ≼o s) : r = f ⁻¹'o s := by funext a b; exact propext f.ord' protected theorem is_irrefl : ∀ (f : r ≼o s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o.1 h)⟩ protected theorem is_refl : ∀ (f : r ≼o s) [is_refl β s], is_refl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a, o.2 (H _)⟩ protected theorem is_symm : ∀ (f : r ≼o s) [is_symm β s], is_symm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h, o.2 (H _ _ (o.1 h))⟩ protected theorem is_asymm : ∀ (f : r ≼o s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o.1 h₁) (o.1 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ≼o s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_trans : ∀ (f : r ≼o s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.2 (H _ _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_total : ∀ (f : r ≼o s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).2 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ≼o s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ≼o s) [is_partial_order β s], is_partial_order α r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : ∀ (f : r ≼o s) [is_linear_order β s], is_linear_order α r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : ∀ (f : r ≼o s) [is_strict_order β s], is_strict_order α r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : ∀ (f : r ≼o s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff.symm o)).2 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ≼o s) [is_strict_total_order' β s], is_strict_total_order' α r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r ≼o s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.ord'.1 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ≼o s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ≼o s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- It suffices to prove `f` is monotone between strict orders to show it is an order embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ≼o s := begin haveI := @is_irrefl_of_is_asymm β s _, refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨H _ _, λ h, _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) : (@of_monotone _ _ r s _ _ f H : α → β) = f := rfl theorem nat_lt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f n) (f (n+1))) : ((<) : ℕ → ℕ → Prop) ≼o r := of_monotone f $ λ a b h, begin induction b with b IH, {exact (nat.not_lt_zero _ h).elim}, cases nat.lt_succ_iff_lt_or_eq.1 h with h e, { exact trans (IH h) (H _) }, { subst b, apply H } end theorem nat_gt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f (n+1)) (f n)) : ((>) : ℕ → ℕ → Prop) ≼o r := by haveI := is_strict_order.swap r; exact rsymm (nat_lt f H) theorem well_founded_iff_no_descending_seq [is_strict_order α r] : well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ≼o r) := ⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩, suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl, λ a ac, begin induction ac with a _ IH, intros n h, subst a, exact IH (f (n+1)) (o.1 (nat.lt_succ_self _)) _ rfl end, λ N, ⟨λ a, classical.by_contradiction $ λ na, let ⟨f, h⟩ := classical.axiom_of_choice $ show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1, from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $ ⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in N ⟨nat_gt (λ n, (n.foldr f ⟨a, na⟩).1) $ λ n, h _⟩⟩⟩ end order_embedding /-- The inclusion map `fin n → ℕ` is an order embedding. -/ def fin.val.order_embedding (n) : @order_embedding (fin n) ℕ (<) (<) := ⟨⟨fin.val, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The inclusion map `fin m → fin n` is an order embedding. -/ def fin_fin.order_embedding {m n} (h : m ≤ n) : @order_embedding (fin m) (fin n) (<) (<) := ⟨⟨λ ⟨x, h'⟩, ⟨x, lt_of_lt_of_le h' h⟩, λ ⟨a, _⟩ ⟨b, _⟩ h, by congr; injection h⟩, by intros; cases a; cases b; refl⟩ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (fin.val.order_embedding _).is_well_order /-- An order isomorphism is an equivalence that is also an order embedding. -/ structure order_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (ord : ∀ {a b}, r a b ↔ s (to_equiv a) (to_equiv b)) infix ` ≃o `:50 := order_iso namespace order_iso def to_order_embedding (f : r ≃o s) : r ≼o s := ⟨f.to_equiv.to_embedding, f.ord⟩ instance : has_coe (r ≃o s) (r ≼o s) := ⟨to_order_embedding⟩ @[simp] theorem coe_coe_fn (f : r ≃o s) : ((f : r ≼o s) : α → β) = f := rfl theorem ord' : ∀ (f : r ≃o s) {a b}, r a b ↔ s (f a) (f b) | ⟨f, o⟩ := @o @[simp] theorem coe_fn_mk (f : α ≃ β) (o) : (@order_iso.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃o s) : (f.to_equiv : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≃o s}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by congr; exact equiv.eq_of_to_fun_eq h @[refl] protected def refl (r : α → α → Prop) : r ≃o r := ⟨equiv.refl _, λ a b, iff.rfl⟩ @[symm] protected def symm (f : r ≃o s) : s ≃o r := ⟨f.to_equiv.symm, λ a b, by cases f with f o; rw o; simp⟩ @[trans] protected def trans (f₁ : r ≃o s) (f₂ : s ≃o t) : r ≃o t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, by cases f₁ with f₁ o₁; cases f₂ with f₂ o₂; rw [o₁, o₂]; simp⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@order_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem refl_apply (x : α) : order_iso.refl r x = x := rfl @[simp] theorem trans_apply : ∀ (f : r ≃o s) (g : s ≃o t) (a : α), (f.trans g) a = g (f a) | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ a := equiv.trans_apply _ _ _ @[simp] theorem apply_inverse_apply : ∀ (e : r ≃o s) (x : β), e (e.symm x) = x | ⟨f₁, o₁⟩ x := by simp @[simp] theorem inverse_apply_apply : ∀ (e : r ≃o s) (x : α), e.symm (e x) = x | ⟨f₁, o₁⟩ x := by simp /-- Any equivalence lifts to an order isomorphism between `s` and its preimage. -/ def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃o s := ⟨f, λ a b, iff.rfl⟩ noncomputable def of_surjective (f : r ≼o s) (H : surjective f) : r ≃o s := ⟨equiv.of_bijective ⟨f.inj, H⟩, by simp [f.ord']⟩ @[simp] theorem of_surjective_coe (f : r ≼o s) (H) : (of_surjective f H : α → β) = f := by delta of_surjective; simp theorem sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : sum.lex r₁ s₁ ≃o sum.lex r₂ s₂ := ⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b, by cases e₁ with f hf; cases e₂ with g hg; cases a; cases b; simp [hf, hg]⟩ theorem prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : prod.lex r₁ s₁ ≃o prod.lex r₂ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, begin cases e₁ with f hf; cases e₂ with g hg, cases a with a₁ a₂; cases b with b₁ b₂, suffices : prod.lex r₁ s₁ (a₁, a₂) (b₁, b₂) ↔ prod.lex r₂ s₂ (f a₁, g a₂) (f b₁, g b₂), {simpa [hf, hg]}, split, { intro h, cases h with _ _ _ _ h _ _ _ h, { left, exact hf.1 h }, { right, exact hg.1 h } }, { generalize e : f b₁ = fb₁, intro h, cases h with _ _ _ _ h _ _ _ h, { subst e, left, exact hf.2 h }, { have := f.bijective.1 e, subst b₁, right, exact hg.2 h } } end⟩ end order_iso /-- A subset `p : set α` embeds into `α` -/ def set_coe_embedding {α : Type*} (p : set α) : p ↪ α := ⟨subtype.val, @subtype.eq _ _⟩ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := @subtype.val _ p ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel protected def order_embedding (r : α → α → Prop) (p : set α) : subrel r p ≼o r := ⟨set_coe_embedding _, λ a b, iff.rfl⟩ @[simp] theorem order_embedding_apply (r : α → α → Prop) (p a) : subrel.order_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := order_embedding.is_well_order (subrel.order_embedding r p) end subrel /-- Restrict the codomain of an order embedding -/ def order_embedding.cod_restrict (p : set β) (f : r ≼o s) (H : ∀ a, f a ∈ p) : r ≼o subrel s p := ⟨f.to_embedding.cod_restrict p H, f.ord⟩ @[simp] theorem order_embedding.cod_restrict_apply (p) (f : r ≼o s) (H a) : order_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl
169fac68daf325a36cda07e80db1d3a0e734f1ab
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Elab/Tactic/Conv/Basic.lean
8cbab09c70e0c86055c7969dcdf5741231fdf345
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,424
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Replace import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.BuiltinTactic namespace Lean.Elab.Tactic.Conv open Meta def mkConvGoalFor (lhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhs ← mkFreshExprMVar lhsType let targetNew := mkLHSGoal (← mkEq lhs rhs) let newGoal ← mkFreshExprSyntheticOpaqueMVar targetNew return (rhs, newGoal) def markAsConvGoal (mvarId : MVarId) : MetaM MVarId := do let target ← getMVarType mvarId if isLHSGoal? target |>.isSome then return mvarId -- it is already tagged as LHS goal replaceTargetDefEq mvarId (mkLHSGoal (← getMVarType mvarId)) def convert (lhs : Expr) (conv : TacticM Unit) : TacticM (Expr × Expr) := do let (rhs, newGoal) ← mkConvGoalFor lhs let savedGoals ← getGoals try setGoals [newGoal.mvarId!] conv for mvarId in (← getGoals) do try applyRefl mvarId catch _ => pure () pruneSolvedGoals unless (← getGoals).isEmpty do throwError "convert tactic failed, there are unsolved goals\n{goalsToMessageData (← getGoals)}" pure () finally setGoals savedGoals return (← instantiateMVars rhs, ← instantiateMVars newGoal) def getLhsRhsCore (mvarId : MVarId) : MetaM (Expr × Expr) := withMVarContext mvarId do let some (_, lhs, rhs) ← matchEq? (← getMVarType mvarId) | throwError "invalid 'conv' goal" return (lhs, rhs) def getLhsRhs : TacticM (Expr × Expr) := do getLhsRhsCore (← getMainGoal) def getLhs : TacticM Expr := return (← getLhsRhs).1 def getRhs : TacticM Expr := return (← getLhsRhs).2 /-- `⊢ lhs = rhs` ~~> `⊢ lhs' = rhs` using `h : lhs = lhs'`. -/ def updateLhs (lhs' : Expr) (h : Expr) : TacticM Unit := do let rhs ← getRhs let newGoal ← mkFreshExprSyntheticOpaqueMVar (mkLHSGoal (← mkEq lhs' rhs)) assignExprMVar (← getMainGoal) (← mkEqTrans h newGoal) replaceMainGoal [newGoal.mvarId!] /-- Replace `lhs` with the definitionally equal `lhs'`. -/ def changeLhs (lhs' : Expr) : TacticM Unit := do let rhs ← getRhs liftMetaTactic1 fun mvarId => do replaceTargetDefEq mvarId (mkLHSGoal (← mkEq lhs' rhs)) @[builtinTactic Lean.Parser.Tactic.Conv.whnf] def evalWhnf : Tactic := fun stx => withMainContext do let lhs ← getLhs changeLhs (← whnf lhs) @[builtinTactic Lean.Parser.Tactic.Conv.convSeq1Indented] def evalConvSeq1Indented : Tactic := fun stx => do evalTacticSeq1Indented stx @[builtinTactic Lean.Parser.Tactic.Conv.convSeqBracketed] def evalConvSeqBracketed : Tactic := fun stx => do let initInfo ← mkInitialTacticInfo stx[0] withRef stx[2] <| closeUsingOrAdmit do -- save state before/after entering focus on `{` withInfoContext (pure ()) initInfo evalManyTacticOptSemi stx[1] evalTactic (← `(tactic| allGoals (try rfl))) @[builtinTactic Lean.Parser.Tactic.Conv.nestedConv] def evalNestedConv : Tactic := fun stx => do evalConvSeqBracketed stx[0] @[builtinTactic Lean.Parser.Tactic.Conv.convSeq] def evalConvSeq : Tactic := fun stx => do evalTactic stx[0] @[builtinTactic Lean.Parser.Tactic.Conv.paren] def evalParen : Tactic := fun stx => evalTactic stx[1] /-- Mark goals of the form `⊢ a = ?m ..` with the conv goal annotation -/ def remarkAsConvGoal : TacticM Unit := do let newGoals ← (← getUnsolvedGoals).mapM fun mvarId => withMVarContext mvarId do let target ← getMVarType mvarId if let some (_, lhs, rhs) ← matchEq? target then if rhs.getAppFn.isMVar then replaceTargetDefEq mvarId (mkLHSGoal target) else return mvarId else return mvarId setGoals newGoals @[builtinTactic Lean.Parser.Tactic.Conv.nestedTacticCore] def evalNestedTacticCore : Tactic := fun stx => do let seq := stx[2] evalTactic seq; remarkAsConvGoal @[builtinTactic Lean.Parser.Tactic.Conv.nestedTactic] def evalNestedTactic : Tactic := fun stx => do let seq := stx[2] let target ← getMainTarget if let some _ := isLHSGoal? target then liftMetaTactic1 fun mvarId => replaceTargetDefEq mvarId target.mdataExpr! focus do evalTactic seq; remarkAsConvGoal private def convTarget (conv : Syntax) : TacticM Unit := withMainContext do let target ← getMainTarget let (targetNew, proof) ← convert target (evalTactic conv) liftMetaTactic1 fun mvarId => replaceTargetEq mvarId targetNew proof evalTactic (← `(tactic| try rfl)) private def convLocalDecl (conv : Syntax) (hUserName : Name) : TacticM Unit := withMainContext do let localDecl ← getLocalDeclFromUserName hUserName let (typeNew, proof) ← convert localDecl.type (evalTactic conv) liftMetaTactic1 fun mvarId => return some (← replaceLocalDecl mvarId localDecl.fvarId typeNew proof).mvarId @[builtinTactic Lean.Parser.Tactic.Conv.conv] def evalConv : Tactic := fun stx => do match stx with | `(tactic| conv $[at $loc?]? in $p => $code) => evalTactic (← `(tactic| conv $[at $loc?]? => pattern $p; ($code:convSeq))) | `(tactic| conv $[at $loc?]? => $code) => if let some loc := loc? then convLocalDecl code loc.getId else convTarget code | _ => throwUnsupportedSyntax end Lean.Elab.Tactic.Conv
82680b9aa1af4b14b87ff58d600303b574520338
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/meta/interactive.lean
ee649985ee3f361185dbefe13ad9d48eb6e8a9be
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
30,459
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.category.combinators import init.meta.lean.parser init.meta.quote open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace interactive /-- (parse p) as the parameter type of an interactive tactic will instruct the Lean parser to run `p` when parsing the parameter and to pass the parsed value as an argument to the tactic. -/ @[reducible] meta def parse {α : Type} [has_quote α] (p : parser α) : Type := α namespace types variables {α β : Type} -- optimized pretty printer meta def brackets (l r : string) (p : parser α) := tk l *> p <* tk r meta def list_of (p : parser α) := brackets "[" "]" $ sep_by (skip_info (tk ",")) p /-- A 'tactic expression', which uses right-binding power 2 so that it is terminated by '<|>' (rbp 2), ';' (rbp 1), and ',' (rbp 0). It should be used for any (potentially) trailing expression parameters. -/ meta def texpr := qexpr 2 /-- Parse an identifier or a '_' -/ meta def ident_ : parser name := ident <|> tk "_" *> return `_ meta def using_ident := (tk "using" *> ident)? meta def with_ident_list := (tk "with" *> ident_*) <|> return [] meta def without_ident_list := (tk "without" *> ident*) <|> return [] meta def location := (tk "at" *> ident*) <|> return [] meta def qexpr_list := list_of (qexpr 0) meta def opt_qexpr_list := qexpr_list <|> return [] meta def qexpr_list_or_texpr := qexpr_list <|> list.ret <$> texpr end types /-- Use `desc` as the interactive description of `p`. -/ meta def with_desc {α : Type} (desc : format) (p : parser α) : parser α := p open expr format tactic types private meta def maybe_paren : list format → format | [] := "" | [f] := f | fs := paren (join fs) private meta def unfold (e : expr) : tactic expr := do (expr.const f_name f_lvls) ← return e.get_app_fn | failed, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, head_beta (expr.mk_app new_f e.get_app_args) private meta def concat (f₁ f₂ : list format) := if f₁.empty then f₂ else if f₂.empty then f₁ else f₁ ++ [" "] ++ f₂ private meta def parser_desc_aux : expr → tactic (list format) | ```(ident) := return ["id"] | ```(ident_) := return ["id"] | ```(qexpr) := return ["expr"] | ```(tk %%c) := list.ret <$> to_fmt <$> eval_expr string c | ```(cur_pos) := return [] | ```(return ._) := return [] | ```(._ <$> %%p) := parser_desc_aux p | ```(skip_info %%p) := parser_desc_aux p | ```(set_goal_info_pos %%p) := parser_desc_aux p | ```(with_desc %%desc %%p) := list.ret <$> eval_expr format desc | ```(%%p₁ <*> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | ```(%%p₁ <* %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | ```(%%p₁ *> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | ```(many %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "*"] | ```(optional %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "?"] | ```(sep_by %%sep %%p) := do f₁ ← parser_desc_aux sep, f₂ ← parser_desc_aux p, return [maybe_paren f₂ ++ join f₁, " ..."] | ```(%%p₁ <|> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ if f₁.empty then [maybe_paren f₂ ++ "?"] else if f₂.empty then [maybe_paren f₁ ++ "?"] else [paren $ join $ f₁ ++ [to_fmt " | "] ++ f₂] | ```(brackets %%l %%r %%p) := do f ← parser_desc_aux p, l ← eval_expr string l, r ← eval_expr string r, -- much better than the naive [l, " ", f, " ", r] return [to_fmt l ++ join f ++ to_fmt r] | e := do e' ← (do e' ← unfold e, guard $ e' ≠ e, return e') <|> (do f ← pp e, fail $ to_fmt "don't know how to pretty print " ++ f), parser_desc_aux e' meta def param_desc : expr → tactic format | ```(parse %%p) := join <$> parser_desc_aux p | ```(opt_param %%t ._) := (++ "?") <$> pp t | e := if is_constant e ∧ (const_name e).components.ilast = `itactic then return $ to_fmt "{ tactic }" else paren <$> pp e end interactive namespace tactic meta def report_resolve_name_failure {α : Type} (e : expr) (n : name) : tactic α := if e.is_choice_macro then fail ("failed to resolve name '" ++ to_string n ++ "', it is overloaded") else fail ("failed to resolve name '" ++ to_string n ++ "', unexpected result") /- allows metavars and report errors -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- doesn't allows metavars and report errors -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff namespace interactive open interactive interactive.types expr /- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit /-- This tactic applies to a goal that is either a Pi/forall or starts with a let binder. If the current goal is a Pi/forall `∀ x:T, U` (resp `let x:=t in U`) then intro puts `x:T` (resp `x:=t`) in the local context. The new subgoal target is `U`. If the goal is an arrow `T → U`, then it puts in the local context either `h:T`, and the new goal target is `U`. If the goal is neither a Pi/forall nor starting with a let definition, the tactic `intro` applies the tactic `whnf` until the tactic `intro` can be applied or the goal is not `head-reducible`. -/ meta def intro : parse ident_? → tactic unit | none := intro1 >> skip | (some h) := tactic.intro h >> skip /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h_1 ... h_n` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := tactic.intros >> skip | hs := intro_lst hs >> skip /-- The tactic `rename h₁ h₂` renames hypothesis `h₁` into `h₂` in the current local context. -/ meta def rename : parse ident → parse ident → tactic unit := tactic.rename /-- This tactic applies to any goal. The argument term is a term well-formed in the local context of the main goal. The tactic apply tries to match the current goal against the conclusion of the type of term. If it succeeds, then the tactic returns as many subgoals as the number of non-dependent premises that have not been fixed by type inference or type class resolution. The tactic `apply` uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.apply /-- Similar to the `apply` tactic, but it also creates subgoals for dependent premises that have not been fixed by type inference or type class resolution. -/ meta def fapply (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.fapply /-- This tactic tries to close the main goal `... |- U` using type class resolution. It succeeds if it generates a term of type `U` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic applies to any goal. It behaves like `exact` with a big difference: the user can leave some holes `_` in the term. `refine` will generate as many subgoals as there are holes in the term. Note that some holes may be implicit. The type of holes must be either synthesized by the system or declared by an explicit type ascription like (e.g., `(_ : nat → Prop)`). -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for an hypothesis which type is equal to the goal target. If it is the case, the subgoal is proved. Otherwise, it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- This tactic applies to any goal. `change U` replaces the main goal target `T` with `U` providing that `U` is well-formed with respect to the main goal local context, and `T` and `U` are definitionally equal. -/ meta def change (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.change /-- This tactic applies to any goal. It gives directly the exact proof term of the goal. Let `T` be our goal, let `p` be a term of type `U` then `exact p` succeeds iff `T` and `U` are definitionally equal. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse qexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts private meta def get_locals : list name → tactic (list expr) | [] := return [] | (n::ns) := do h ← get_local n, hs ← get_locals ns, return (h::hs) /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and its dependencies to the goal target. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := do hs ← get_locals ids, revert_lst hs, skip private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p.to_raw_expr with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ private meta def to_expr' (p : pexpr) : tactic expr := let e := p.to_raw_expr in match e with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | _ := i_to_expr p end meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta instance rw_rule_has_quote : has_quote rw_rule := ⟨λ ⟨p, s, r⟩, ``(rw_rule.mk %%(quote p) %%(quote s) %%(quote r))⟩ private meta def rw_goal (m : transparency) (rs : list rw_rule) : tactic unit := rs.mfor' $ λ r, save_info r.pos >> to_expr' r.rule >>= rewrite_core m tt tt occurrences.all r.symm private meta def rw_hyp (m : transparency) (rs : list rw_rule) (hname : name) : tactic unit := rs.mfor' $ λ r, do h ← get_local hname, save_info r.pos, e ← to_expr' r.rule, rewrite_at_core m tt tt occurrences.all r.symm e h private meta def rw_hyps (m : transparency) (rs : list rw_rule) (hs : list name) : tactic unit := hs.mfor' (rw_hyp m rs) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (tk "-")?) <*> ep meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) meta instance rw_rules_t_has_quote : has_quote rw_rules_t := ⟨λ ⟨rs, p⟩, ``(rw_rules_t.mk %%(quote rs) %%(quote p))⟩ -- accepts the same content as `qexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (qexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (m : transparency) (rs : parse rw_rules) (loc : parse location) : tactic unit := match loc with | [] := rw_goal m rs.rules | hs := rw_hyps m rs.rules hs end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) meta def rewrite : parse rw_rules → parse location → tactic unit := rw_core reducible meta def rw : parse rw_rules → parse location → tactic unit := rewrite /- rewrite followed by assumption -/ meta def rwa (q : parse rw_rules) (l : parse location) : tactic unit := rewrite q l >> try assumption meta def erewrite : parse rw_rules → parse location → tactic unit := rw_core semireducible meta def erw : parse rw_rules → parse location → tactic unit := erewrite private meta def get_type_name (e : expr) : tactic name := do e_type ← infer_type e >>= whnf, (const I ls) ← return $ get_app_fn e_type, return I precedence `generalizing` : 0 meta def induction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do e ← i_to_expr p, locals ← get_locals $ revert.get_or_else [], n ← revert_lst locals, tactic.induction e ids rec_name, all_goals (intron n) meta def cases (p : parse texpr) (ids : parse with_ident_list) : tactic unit := do e ← i_to_expr p, tactic.cases e ids private meta def find_case (goals : list expr) (ty : name) (idx : nat) (num_indices : nat) : option expr → expr → option (expr × expr) | case e := if e.has_meta_var then match e with | (mvar _ _) := do case ← case, guard $ e ∈ goals, pure (case, e) | (app _ _) := let idx := match e.get_app_fn with | const (name.mk_string rec ty') _ := guard (ty' = ty) >> match mk_simple_name rec with | `drec := some idx | `rec := some idx -- indices + major premise | `dcases_on := some (idx + num_indices + 1) | `cases_on := some (idx + num_indices + 1) | _ := none end | _ := none end in match idx with | none := list.foldl (<|>) none $ e.get_app_args.map (find_case case) | some idx := let args := e.get_app_args in do arg ← args.nth idx, args.enum.foldl (λ acc ⟨i, arg⟩, match acc with | some _ := acc | _ := if i ≠ idx then find_case none arg else none end) -- start recursion with likely case (find_case (some arg) arg) end | (lam _ _ _ e) := find_case case e | (macro _ n f) := list.foldl (<|>) none $ list.map (find_case case) $ macro_args_to_list n f | _ := none end else none private meta def rename_lams : expr → list name → tactic unit | (lam n _ _ e) (n'::ns) := (rename n n' >> rename_lams e ns) <|> rename_lams e (n'::ns) | _ _ := skip /-- Focuses on the `induction`/`cases` subgoal corresponding to the given introduction rule, optionally renaming introduced locals. -/ meta def case (ctor : parse ident) (ids : parse ident*) (tac : itactic) : tactic unit := do r ← result, env ← get_env, ctor ← resolve_constant ctor <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), ty ← (env.inductive_type_of ctor).to_monad <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), let ctors := env.constructors_of ty, let idx := env.inductive_num_params ty + /- motive -/ 1 + list.find ctor ctors, gs ← get_goals, (case, g) ← (find_case gs ty idx (env.inductive_num_indices ty) none r ).to_monad <|> fail "could not find open goal of given case", set_goals $ g :: gs.filter (≠ g), rename_lams case ids, solve1 tac meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct meta def generalize (p : parse qexpr) (x : parse ident) : tactic unit := do e ← i_to_expr p, tactic.generalize e x meta def generalize2 (p : parse qexpr) (x : parse ident) (h : parse ident) : tactic unit := do tgt ← target, e ← to_expr p, let e' := tgt^.replace $ λa _, if a = e then some (var 1) else none, to_expr `(Π x, %%p = x → %%e') >>= assert h, swap, t ← get_local h, exact `(%%t %%p rfl), intro x, intro h meta def ginduction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) : tactic unit := do x ← mk_fresh_name, let (h, hs) := (match ids with | [] := (`_h, []) | (h :: hs) := (h, hs) end : name × list name), generalize2 p x h, t ← get_local x, induction (to_pexpr t) rec_name hs ([] : list name) meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := tactic.admit /-- This tactic applies to any goal. The contradiction tactic attempts to find in the current local context an hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction meta def repeat : itactic → tactic unit := tactic.repeat meta def try : itactic → tactic unit := tactic.try meta def skip : tactic unit := tactic.skip meta def solve1 : itactic → tactic unit := tactic.solve1 meta def abstract (id : parse ident? ) (tac : itactic) : tactic unit := tactic.abstract tac id meta def all_goals : itactic → tactic unit := tactic.all_goals meta def any_goals : itactic → tactic unit := tactic.any_goals meta def focus (tac : itactic) : tactic unit := tactic.focus [tac] /-- This tactic applies to any goal. `assert h : T` adds a new hypothesis of name `h` and type `T` to the current goal and opens a new subgoal with target `T`. The new subgoal becomes the main goal. -/ meta def assert (h : parse ident) (q : parse $ tk ":" *> texpr) : tactic unit := do e ← i_to_expr_strict q, tactic.assert h e meta def define (h : parse ident) (q : parse $ tk ":" *> texpr) : tactic unit := do e ← i_to_expr_strict q, tactic.define h e /-- This tactic applies to any goal. `assertv h : T := p` adds a new hypothesis of name `h` and type `T` to the current goal if `p` a term of type `T`. -/ meta def assertv (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (q₂ : parse $ tk ":=" *> texpr) : tactic unit := do t ← i_to_expr_strict q₁, v ← i_to_expr_strict ``(%%q₂ : %%t), tactic.assertv h t v meta def definev (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (q₂ : parse $ tk ":=" *> texpr) : tactic unit := do t ← i_to_expr_strict q₁, v ← i_to_expr_strict ``(%%q₂ : %%t), tactic.definev h t v meta def note (h : parse ident) (q : parse $ tk ":=" *> texpr) : tactic unit := do p ← i_to_expr_strict q, tactic.note h p meta def pose (h : parse ident) (q : parse $ tk ":=" *> texpr) : tactic unit := do p ← i_to_expr_strict q, tactic.pose h p /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a meta def existsi (e : parse texpr) : tactic unit := i_to_expr e >>= tactic.existsi /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := tactic.constructor meta def left : tactic unit := tactic.left meta def right : tactic unit := tactic.right meta def split : tactic unit := tactic.split meta def exfalso : tactic unit := tactic.exfalso /-- The injection tactic is based on the fact that constructors of inductive datatypes 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 to new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` an `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail ("invalid simplification lemma '" ++ to_string n ++ "' (use command 'set_option trace.simp_lemmas true' for more details)") private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (n : name) (ref : expr) : tactic simp_lemmas := do p ← resolve_name n, match p.to_raw_expr with | const n _ := (do b ← is_valid_simp_lemma_cnst reducible n, guard b, save_const_type_info n ref, s.add_simp n) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, add_simps s eqns) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr p, b ← is_valid_simp_lemma reducible e, guard b, try (save_type_info e ref), s.add e) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (p : pexpr) : tactic simp_lemmas := let e := p.to_raw_expr in match e with | (const c []) := simp_lemmas.resolve_and_add s c e | (local_const c _ _ _) := simp_lemmas.resolve_and_add s c e | _ := do new_e ← i_to_expr p, s.add new_e end private meta def simp_lemmas.append_pexprs : simp_lemmas → list pexpr → tactic simp_lemmas | s [] := return s | s (l::ls) := do new_s ← simp_lemmas.add_pexpr s l, simp_lemmas.append_pexprs new_s ls private meta def mk_simp_set (attr_names : list name) (hs : list pexpr) (ex : list name) : tactic simp_lemmas := do s₀ ← join_user_simp_lemmas attr_names, s₁ ← simp_lemmas.append_pexprs s₀ hs, -- add equational lemmas, if any ex ← ex.mfor (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return $ simp_lemmas.erase s₁ $ ex.join private meta def simp_goal (cfg : simp_config) : simp_lemmas → tactic unit | s := do (new_target, Heq) ← target >>= simplify_core cfg s `eq, tactic.assert `Htarget new_target, swap, Ht ← get_local `Htarget, mk_eq_mpr Heq Ht >>= tactic.exact private meta def simp_hyp (cfg : simp_config) (s : simp_lemmas) (h_name : name) : tactic unit := do h ← get_local h_name, htype ← infer_type h, (new_htype, eqpr) ← simplify_core cfg s `eq htype, tactic.assert (expr.local_pp_name h) new_htype, mk_eq_mp eqpr h >>= tactic.exact, try $ tactic.clear h private meta def simp_hyps (cfg : simp_config) : simp_lemmas → list name → tactic unit | s [] := skip | s (h::hs) := simp_hyp cfg s h >> simp_hyps s hs private meta def simp_core (cfg : simp_config) (ctx : list expr) (hs : list pexpr) (attr_names : list name) (ids : list name) (loc : list name) : tactic unit := do s ← mk_simp_set attr_names hs ids, s ← s.append ctx, match loc : _ → tactic unit with | [] := simp_goal cfg s | _ := simp_hyps cfg s loc end, try tactic.triv, try (tactic.reflexivity reducible) /-- This 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_1, ..., h_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h_i`s. The `h_i`'s are terms. If a `h_i` is a definition `f`, then the equational lemmas associated with `f` are used. This is a convenient way to "unfold" `f`. - `simp without id_1 ... id_n` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id_i`s. - `simp at h` simplifies the non dependent hypothesis `h : T`. The tactic fails if the target or another hypothesis depends on `h`. - `simp with attr` simplifies the main goal target using the lemmas tagged with the attribute `[attr]`. -/ meta def simp (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (loc : parse location) (cfg : simp_config := {}) : tactic unit := simp_core cfg [] hs attr_names ids loc /-- Similar to the `simp` tactic, but adds all applicable hypotheses as simplification rules. -/ meta def simp_using_hs (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : tactic unit := do ctx ← collect_ctx_simps, simp_core cfg ctx hs attr_names ids [] meta def simph (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : tactic unit := simp_using_hs hs attr_names ids cfg meta def simp_intros (ids : parse ident_*) (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (wo_ids : parse without_ident_list) (cfg : simp_config := {}) : tactic unit := do s ← mk_simp_set attr_names hs wo_ids, match ids with | [] := simp_intros_using s cfg | ns := simp_intro_lst_using ns s cfg end, try triv >> try (reflexivity reducible) meta def simph_intros (ids : parse ident_*) (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (wo_ids : parse without_ident_list) (cfg : simp_config := {}) : tactic unit := do s ← mk_simp_set attr_names hs wo_ids, match ids with | [] := simph_intros_using s cfg | ns := simph_intro_lst_using ns s cfg end, try triv >> try (reflexivity reducible) private meta def dsimp_hyps (s : simp_lemmas) : list name → tactic unit | [] := skip | (h::hs) := get_local h >>= dsimp_at_core s meta def dsimp (es : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) : parse location → tactic unit | [] := do s ← mk_simp_set attr_names es ids, tactic.dsimp_core s | hs := do s ← mk_simp_set attr_names es ids, dsimp_hyps s hs /-- This tactic applies to a goal that has the form `t ~ u` where `~` is a reflexive relation. That is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity meta def symmetry : tactic unit := tactic.symmetry meta def transitivity : tactic unit := tactic.transitivity meta def ac_reflexivity : tactic unit := tactic.ac_refl meta def ac_refl : tactic unit := tactic.ac_refl meta def cc : tactic unit := tactic.cc meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) private meta def dunfold_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= dunfold_at cs >> dunfold_hyps cs hs meta def dunfold : parse ident* → parse location → tactic unit | cs [] := do new_cs ← to_qualified_names cs, tactic.dunfold new_cs | cs hs := do new_cs ← to_qualified_names cs, dunfold_hyps new_cs hs /- TODO(Leo): add support for non-refl lemmas -/ meta def unfold : parse ident* → parse location → tactic unit := dunfold private meta def dunfold_hyps_occs : name → occurrences → list name → tactic unit | c occs [] := skip | c occs (h::hs) := get_local h >>= dunfold_core_at occs [c] >> dunfold_hyps_occs c occs hs meta def dunfold_occs : parse ident → parse location → list nat → tactic unit | c [] ps := do new_c ← to_qualified_name c, tactic.dunfold_occs_of ps new_c | c hs ps := do new_c ← to_qualified_name c, dunfold_hyps_occs new_c (occurrences.pos ps) hs /- TODO(Leo): add support for non-refl lemmas -/ meta def unfold_occs : parse ident → parse location → list nat → tactic unit := dunfold_occs private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_at cs >> dunfold_hyps cs hs meta def delta : parse ident* → parse location → tactic unit | cs [] := do new_cs ← to_qualified_names cs, tactic.delta new_cs | cs hs := do new_cs ← to_qualified_names cs, delta_hyps new_cs hs meta def apply_opt_param : tactic unit := tactic.apply_opt_param meta def apply_auto_param : tactic unit := tactic.apply_auto_param meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv t e) meta def guard_target (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq t p meta def by_cases (q : parse texpr) : tactic unit := do p ← tactic.to_expr_strict q, tactic.by_cases p meta def by_contradiction : tactic unit := tactic.by_contradiction >> return () meta def by_contra : tactic unit := tactic.by_contradiction >> return () end interactive end tactic
c22092b80c8d5d47bfd5161f8e73171ebab61d73
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/tactic/structure_helper.lean
971af589575ea9f25c68c55bf4ca5b615f0cd592
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
4,525
lean
import data.string data.list.defs import tactic.core def {u v w} list.mfilter_map {m : Type u → Type v} [alternative m] [monad m] {α : Type w} {β : Type u} (f : α → m β) : list α → m (list β) | [] := return [] | (h :: t) := do h' ← (f h >>= λ v, pure $ list.cons v []) <|> pure [], t' ← list.mfilter_map t, return (h' ++ t') namespace tactic private meta def attempt_instance_build (n : name) (ns : list name) : tactic unit := do sorries ← ns.mmap $ λ _, to_pexpr <$> mk_sorry, let s : structure_instance_info := { struct := some n, field_names := ns, field_values := sorries, }, to_expr $ pexpr.mk_structure_instance s, tactic.skip private meta def capture_failure_message (tac : tactic unit) : tactic (option string) := λ s, match tac s with | result.success a s' := result.success none s | result.exception (some msg) _ s' := result.success (to_string $ msg ()) s | result.exception none pos s' := result.exception (some $ λ _, format!"no fail msg") pos s end private meta def find_explicit_constructor_args_core (n : name) : list name → tactic (list name) | ns := do msg ← capture_failure_message $ attempt_instance_build n ns, do { msg ← msg, newn ← (msg.split_on '\'').nth 1, find_explicit_constructor_args_core (newn :: ns) } <|> return ns meta def find_explicit_structure_args (n : name) : tactic (list name) := do env ← get_env, match env.structure_fields n with | none := fail format!"'{n}' not a structure!" | some _ := list.reverse <$> find_explicit_constructor_args_core n [] end meta inductive constructor_arg | default (n : name) | implicit | auto (tac : tactic unit) | opt (v : expr) namespace constructor_arg meta def to_tactic_format : constructor_arg → tactic format | (default n) := pure format!"(default {n})" | (implicit) := pure format!"(implicit)" | (auto tac) := pure format!"(auto)" | (opt v) := do v ← pp v, pure format!"(opt {v})" meta instance : has_to_tactic_format constructor_arg := ⟨to_tactic_format⟩ meta def classify (n : name) : binder_info → expr → tactic constructor_arg | binder_info.default `(opt_param %%t %%v) := return $ constructor_arg.opt v | binder_info.default `(auto_param %%t %%tac) := do tac ← eval_expr name tac, tac ← resolve_name tac >>= to_expr >>= eval_expr (tactic unit), return $ constructor_arg.auto tac | binder_info.default e := return $ constructor_arg.default n | _ _ := return constructor_arg.implicit meta def dispatch (ens : list name) : constructor_arg → tactic (name × pexpr) | (default n) := if n ∈ ens then do r ← resolve_name n, return (n, r) else failed | _ := failed end constructor_arg meta def parse_constructor_args : expr → tactic (list constructor_arg) | (expr.pi n bi t b) := do m ← mk_meta_var t, h ← constructor_arg.classify n bi t, list.cons h <$> parse_constructor_args (b.instantiate_var m) | _ := return [] end tactic namespace environment meta def get_constructor_type (e : environment) (n : name) : tactic expr := do r ← e.get n, match r with | declaration.cnst _ _ t _ := pure t | _ := tactic.fail "not a constructor" end end environment namespace tactic meta def instantiate_with_minimal (n : name) : tactic unit := do l ← find_explicit_structure_args n, let placeholders := l.map $ λ _, pexpr.mk_placeholder, let s : structure_instance_info := { struct := n, field_names := l, field_values := placeholders, }, tactic.refine $ pexpr.mk_structure_instance s meta def structure_helper : tactic unit := do t ← target, env ← get_env, match t with | expr.app (expr.const sn _) e := match env.structure_fields sn with | some l := do args ← lock_tactic_state $ do { tactic.fsplit, ty ← env.get_constructor_type (sn ++ `mk), args ← parse_constructor_args ty, ens ← find_explicit_structure_args sn, args.mfilter_map $ constructor_arg.dispatch ens }, let s : structure_instance_info := { struct := sn, field_names := args.map prod.fst, field_values := args.map prod.snd, }, to_expr (pexpr.mk_structure_instance s) >>= exact | none := fail "goal not a structure" end | _ := fail "unsupported goal" end run_cmd add_interactive [`structure_helper] end tactic
a8d9561e4b6526769685f93334dbd121ed0b48bf
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/instances/ennreal.lean
e3879975852f52954314d405f2f81a13de53e822
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
33,426
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 Extended non-negative reals -/ import topology.instances.nnreal data.real.ennreal noncomputable theory open classical set lattice filter metric open_locale classical variables {α : Type*} {β : Type*} {γ : Type*} open_locale ennreal namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} section topological_space open topological_space /-- Topology on `ennreal`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ennreal := topological_space.generate_from {s | ∃a, s = {b | a < b} ∨ s = {b | b < a}} instance : orderable_topology ennreal := ⟨rfl⟩ instance : t2_space ennreal := by apply_instance instance : second_countable_topology ennreal := ⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}}, countable_bUnion (countable_encodable _) $ assume a ha, countable_insert (countable_singleton _), le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : nnreal → ennreal) := ⟨⟨begin refine le_antisymm _ _, { rw [orderable_topology.topology_eq_generate_intervals ennreal, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : nnreal | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : nnreal | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [orderable_topology.topology_eq_generate_intervals nnreal], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨{b : ennreal | ↑a < b}, @is_open_lt' ennreal ennreal.topological_space _ _ _, by simp⟩, exact ⟨{b : ennreal | b < ↑a}, @is_open_gt' ennreal ennreal.topological_space _ _ _, by simp⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} := is_open_neg (is_closed_eq continuous_id continuous_const) lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma coe_range_mem_nhds : range (coe : nnreal → ennreal) ∈ nhds (r : ennreal) := have {a : ennreal | a ≠ ⊤} = range (coe : nnreal → ennreal), from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe], this ▸ mem_nhds_sets is_open_ne_top coe_ne_top lemma tendsto_coe {f : filter α} {m : α → nnreal} {a : nnreal} : tendsto (λa, (m a : ennreal)) f (nhds ↑a) ↔ tendsto m f (nhds a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe {α} [topological_space α] {f : α → nnreal} : continuous (λa, (f a : ennreal)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : nnreal} : nhds (r : ennreal) = (nhds r).map coe := by rw [embedding_coe.induced, map_nhds_induced_eq coe_range_mem_nhds] lemma nhds_coe_coe {r p : nnreal} : nhds ((r : ennreal), (p : ennreal)) = (nhds (r, p)).map (λp:nnreal×nnreal, (p.1, p.2)) := begin rw [(embedding_coe.prod_mk embedding_coe).map_nhds_eq], rw [← prod_range_range_eq], exact prod_mem_nhds_sets coe_range_mem_nhds coe_range_mem_nhds end lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (nhds a)) : tendsto (λa, ennreal.of_real (m a)) f (nhds (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_nnreal) (nhds a) (nhds a.to_nnreal) := begin cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)], exact tendsto_id end lemma tendsto_nhds_top {m : α → ennreal} {f : filter α} (h : ∀n:ℕ, {a | ↑n < m a} ∈ f) : tendsto m f (nhds ⊤) := tendsto_nhds_generate_from $ assume s hs, match s, hs with | _, ⟨none, or.inl rfl⟩, hr := (lt_irrefl ⊤ hr).elim | _, ⟨some r, or.inl rfl⟩, hr := let ⟨n, hrn⟩ := exists_nat_gt r in mem_sets_of_superset (h n) $ assume a hnma, show ↑r < m a, from lt_trans (show (r : ennreal) < n, from (coe_nat n) ▸ coe_lt_coe.2 hrn) hnma | _, ⟨a, or.inr rfl⟩, hr := (not_top_lt $ show ⊤ < a, from hr).elim end lemma nhds_top : nhds ∞ = ⨅a:{a:ennreal // a ≠ ⊤}, principal (Ioi a) := begin rw nhds_generate_from, refine le_antisymm (infi_le_infi2 _) (le_infi $ assume s, le_infi $ assume hs, _), { rintros ⟨a, ha⟩, use {b : ennreal | a < b}, refine infi_le_of_le _ _, { simp only [mem_set_of_eq], split, { rwa lt_top_iff_ne_top }, { use a, exact or.inl rfl } }, { simp only [mem_principal_sets, le_principal_iff], assume a, simp } }, { rcases hs with ⟨ht, ⟨a, hs⟩⟩, cases hs, case or.inl { rw [hs, mem_set_of_eq, lt_top_iff_ne_top] at ht, refine infi_le_of_le ⟨a, ht⟩ _, simp only [mem_principal_sets, le_principal_iff], assume x, simp [hs] }, case or.inr { rw [hs, mem_set_of_eq, lt_iff_not_ge] at ht, have := le_top, contradiction } } end lemma nhds_zero : nhds (0 : ennreal) = ⨅a:{a:ennreal // a ≠ 0}, principal (Iio a) := begin rw nhds_generate_from, refine le_antisymm (infi_le_infi2 _) (le_infi $ assume s, le_infi $ assume hs, _), { rintros ⟨a, ha⟩, use {b : ennreal | b < a}, refine infi_le_of_le _ _, { simp only [mem_set_of_eq], split, { rwa zero_lt_iff_ne_zero }, { use a, exact or.inr rfl } }, { simp only [mem_principal_sets, le_principal_iff], assume a, simp } }, { rcases hs with ⟨hz, ⟨a, hs⟩⟩, cases hs, case or.inr { rw [hs, mem_set_of_eq, zero_lt_iff_ne_zero] at hz, refine infi_le_of_le ⟨a, hz⟩ _, simp only [mem_principal_sets, le_principal_iff], assume x, simp [hs] }, case or.inl { rw [hs, mem_set_of_eq, lt_iff_not_ge] at hz, have := zero_le a, contradiction } } end -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ nhds x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds : x ≠ ⊤ → ε > 0 → Icc (x - ε) (x + ε) ∈ nhds x := begin assume xt ε0, rw mem_nhds_sets_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top : x ≠ ⊤ → nhds x = ⨅ε:{ε:ennreal // ε > 0}, principal (Icc (x - ε) (x + ε)) := begin assume xt, refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff, subtype.forall], assume ε ε0, exact Icc_mem_nhds xt ε0, -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩, cases ha, { rw ha at *, rcases dense xs with ⟨b, ⟨ab, bx⟩⟩, have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx), refine infi_le_of_le ⟨x - b, xb_pos⟩ _, simp only [mem_principal_sets, le_principal_iff, subtype.coe_mk], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rw ha at *, rcases dense xs with ⟨b, ⟨xb, ba⟩⟩, have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb, have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb), refine infi_le_of_le ⟨b - x, bx_pos⟩ _, simp only [mem_principal_sets, le_principal_iff, subtype.coe_mk], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end protected theorem tendsto_nhds {f : filter α} {u : α → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto u f (nhds a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, (u x) ∈ Icc (a - ε) (a + ε) := by { simp only [nhds_of_ne_top ha, tendsto_infi, subtype.forall, tendsto_principal, mem_Icc], refine forall_congr (assume ε, forall_congr $ assume hε, exists_sets_subset_iff.symm) } protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto f at_top (nhds a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by { simp only [nhds_of_ne_top ha, tendsto_infi, subtype.forall, tendsto_at_top_principal], refl } lemma tendsto_coe_nnreal_nhds_top {α} {l : filter α} {f : α → nnreal} (h : tendsto f l at_top) : tendsto (λa, (f a : ennreal)) l (nhds (⊤:ennreal)) := tendsto_nhds_top $ assume n, have {a : α | ↑(n+1) ≤ f a} ∈ l := h $ mem_at_top _, mem_sets_of_superset this $ assume a (ha : ↑(n+1) ≤ f a), begin rw [← coe_nat], dsimp, exact coe_lt_coe.2 (lt_of_lt_of_le (nat.cast_lt.2 (nat.lt_succ_self _)) ha) end instance : topological_add_monoid ennreal := ⟨ continuous_iff_continuous_at.2 $ have hl : ∀a:ennreal, tendsto (λ (p : ennreal × ennreal), p.fst + p.snd) (nhds (⊤, a)) (nhds ⊤), from assume a, tendsto_nhds_top $ assume n, have set.prod {a | ↑n < a } univ ∈ nhds ((⊤:ennreal), a), from prod_mem_nhds_sets (lt_mem_nhds $ coe_nat n ▸ coe_lt_top) univ_mem_sets, show {a : ennreal × ennreal | ↑n < a.fst + a.snd} ∈ nhds (⊤, a), begin filter_upwards [this] assume ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, lt_of_lt_of_le h₁ (le_add_right $ le_refl _) end, begin rintro ⟨a₁, a₂⟩, cases a₁, { simp [continuous_at, none_eq_top, hl a₂], }, cases a₂, { simp [continuous_at, none_eq_top, some_eq_coe, nhds_swap (a₁ : ennreal) ⊤, tendsto_map'_iff, (∘), hl ↑a₁] }, simp [continuous_at, some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_add.symm, tendsto_coe, tendsto_add'] end ⟩ protected lemma tendsto_mul' (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds (a, b)) (nhds (a * b)) := have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds ((⊤:ennreal), b)) (nhds ⊤), begin refine assume b hb, tendsto_nhds_top $ assume n, _, rcases dense (zero_lt_iff_ne_zero.2 hb) with ⟨ε', hε', hεb'⟩, rcases ennreal.lt_iff_exists_coe.1 hεb' with ⟨ε, rfl, h⟩, rcases exists_nat_gt (↑n / ε) with ⟨m, hm⟩, have hε : ε > 0, from coe_lt_coe.1 hε', refine mem_sets_of_superset (prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top m) (lt_mem_nhds $ h)) _, rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, calc (n:ennreal) = ↑(((n:nnreal) / ε) * ε) : begin simp [nnreal.div_def], rw [mul_assoc, ← coe_mul, nnreal.inv_mul_cancel, coe_one, ← coe_nat, mul_one], exact zero_lt_iff_ne_zero.1 hε end ... < (↑m * ε : nnreal) : coe_lt_coe.2 $ mul_lt_mul hm (le_refl _) hε (nat.cast_nonneg _) ... ≤ a₁ * a₂ : by rw [coe_mul]; exact canonically_ordered_semiring.mul_le_mul (le_of_lt h₁) (le_of_lt h₂) end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, have ha' : a ≠ 0, from mt coe_eq_coe.2 ha, simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul'] end protected lemma tendsto_mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (nhds a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (nhds (a * b)) := show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (nhds (a * b)), from tendsto.comp (ennreal.tendsto_mul' ha hb) (tendsto_prod_mk_nhds hma hmb) protected lemma tendsto_mul_right {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (nhds (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto_mul tendsto_const_nhds (or.inl ha) hm hb) lemma Sup_add {s : set ennreal} (hs : s ≠ ∅) : Sup s + a = ⨆b∈s, b + a := have Sup ((λb, b + a) '' s) = Sup s + a, from is_lub_iff_Sup_eq.mp $ is_lub_of_is_lub_of_tendsto (assume x _ y _ h, add_le_add' h (le_refl _)) is_lub_Sup hs (tendsto_add (tendsto_id' inf_le_left) tendsto_const_nhds), by simp [Sup_image, -add_comm] at this; exact this.symm lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by simp [Sup_range] ... = (⨆b∈range s, b + a) : Sup_add $ ne_empty_iff_exists_mem.mpr ⟨s x, x, rfl⟩ ... = _ : by simp [supr_range, -mem_range] lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp lemma supr_add_supr {ι : Sort*} {f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add' (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ennreal, (⨆i, f i) = 0 := assume f, bot_unique (supr_le $ assume i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ennreal} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add' (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal} (hf : ∀a, monotone (f a)) : s.sum (λa, supr (f a)) = (⨆ n, s.sum (λa, f a n)) := begin refine finset.induction_on s _ _, { simp, exact (bot_unique $ supr_le $ assume i, le_refl ⊥).symm }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end section priority -- for some reason the next proof fails without changing the priority of this instance local attribute [instance, priority 1000] classical.prop_decidable lemma mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ennreal), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₀ : s ≠ ∅ := not_eq_empty_iff_exists.2 ⟨x, hx⟩, have s₁ : Sup s ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub_iff_Sup_eq.mp (is_lub_of_is_lub_of_tendsto (assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h) is_lub_Sup s₀ (ennreal.tendsto_mul_right (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end end priority lemma mul_supr {ι : Sort*} {f : ι → ennreal} {a : ennreal} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ennreal} {a : ennreal} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (nhds b) (nhds (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact nnreal.tendsto_sub tendsto_const_nhds tendsto_id }, simp, exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨i⟩ := hι in let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb_iff_Inf_eq.mp $ is_glb_of_is_lub_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) is_lub_supr (ne_empty_of_mem ⟨i, rfl⟩) (tendsto.comp ennreal.tendsto_coe_sub (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ end topological_space section tsum variables {f g : α → ennreal} protected lemma has_sum_coe {f : α → nnreal} {r : nnreal} : has_sum (λa, (f a : ennreal)) ↑r ↔ has_sum f r := have (λs:finset α, s.sum (coe ∘ f)) = (coe : nnreal → ennreal) ∘ (λs:finset α, s.sum f), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → nnreal} (h : has_sum f r) : (∑a, (f a : ennreal)) = r := tsum_eq_has_sum $ ennreal.has_sum_coe.2 $ h protected lemma tsum_coe {f : α → nnreal} : summable f → (∑a, (f a : ennreal)) = ↑(tsum f) | ⟨r, hr⟩ := by rw [tsum_eq_has_sum hr, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, s.sum f) := tendsto_orderable.2 ⟨assume a' ha', let ⟨s, hs⟩ := lt_supr_iff.mp ha' in mem_at_top_sets.mpr ⟨s, assume t ht, lt_of_lt_of_le hs $ finset.sum_le_sum_of_subset ht⟩, assume a' ha', univ_mem_sets' $ assume s, have s.sum f ≤ ⨆(s : finset α), s.sum f, from le_supr (λ(s : finset α), s.sum f) s, lt_of_le_of_lt this ha'⟩ @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ protected lemma tsum_eq_supr_sum : (∑a, f a) = (⨆s:finset α, s.sum f) := tsum_eq_has_sum ennreal.has_sum protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) : (∑p:Σa, β a, f p.1 p.2) = (∑a b, f a b) := tsum_sigma (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ennreal} : (∑p:α×β, f p.1 p.2) = (∑a, ∑b, f a b) := let j : α × β → (Σa:α, β) := λp, sigma.mk p.1 p.2 in let i : (Σa:α, β) → α × β := λp, (p.1, p.2) in let f' : (Σa:α, β) → ennreal := λp, f p.1 p.2 in calc (∑p:α×β, f' (j p)) = (∑p:Σa:α, β, f p.1 p.2) : tsum_eq_tsum_of_iso j i (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl) ... = (∑a, ∑b, f a b) : ennreal.tsum_sigma f protected lemma tsum_comm {f : α → β → ennreal} : (∑a, ∑b, f a b) = (∑b, ∑a, f a b) := let f' : α×β → ennreal := λp, f p.1 p.2 in calc (∑a, ∑b, f a b) = (∑p:α×β, f' p) : ennreal.tsum_prod.symm ... = (∑p:β×α, f' (prod.swap p)) : (tsum_eq_tsum_of_iso prod.swap (@prod.swap α β) (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)).symm ... = (∑b, ∑a, f' (prod.swap (b, a))) : @ennreal.tsum_prod β α (λb a, f' (prod.swap (b, a))) protected lemma tsum_add : (∑a, f a + g a) = (∑a, f a) + (∑a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : (∑a, f a) ≤ (∑a, g a) := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} : (∑i:ℕ, f i) = (⨆i:ℕ, (finset.range i).sum f) := calc _ = (⨆s:finset ℕ, s.sum f) : ennreal.tsum_eq_supr_sum ... = (⨆i:ℕ, (finset.range i).sum f) : le_antisymm (supr_le_supr2 $ assume s, let ⟨n, hn⟩ := finset.exists_nat_subset_range s in ⟨n, finset.sum_le_sum_of_subset hn⟩) (supr_le_supr2 $ assume i, ⟨finset.range i, le_refl _⟩) protected lemma le_tsum (a : α) : f a ≤ (∑a, f a) := calc f a = ({a} : finset α).sum f : by simp ... ≤ (⨆s:finset α, s.sum f) : le_supr (λs:finset α, s.sum f) _ ... = (∑a, f a) : by rw [ennreal.tsum_eq_supr_sum] protected lemma mul_tsum : (∑i, a * f i) = a * (∑i, f i) := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := classical.not_forall.mp h in have sum_ne_0 : (∑i, f i) ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ (∑i, f i) : ennreal.le_tsum _, have tendsto (λs:finset α, s.sum ((*) a ∘ f)) at_top (nhds (a * (∑i, f i))), by rw [← show (*) a ∘ (λs:finset α, s.sum f) = λs, s.sum ((*) a ∘ f), from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto_mul_right (has_sum_tsum ennreal.summable) (or.inl sum_ne_0), tsum_eq_has_sum this protected lemma tsum_mul : (∑i, f i * a) = (∑i, f i) * a := by simp [mul_comm, ennreal.mul_tsum] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} : (∑b:α, ⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc s.sum (λb, ⨆ (h : a = b), f b) ≤ (finset.singleton a).sum (λb, ⨆ (h : a = b), f b) : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) := begin refine ⟨tendsto_sum_nat_of_has_sum, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact has_sum_tsum ennreal.summable }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end end tsum end ennreal namespace nnreal lemma exists_le_has_sum_of_le {f g : β → nnreal} {r : nnreal} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have (∑b, (g b : ennreal)) ≤ r, begin refine has_sum_le (assume b, _) (has_sum_tsum ennreal.summable) (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ has_sum_tsum ennreal.summable⟩ lemma summable_of_le {f g : β → nnreal} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in summable_spec hp lemma has_sum_iff_tendsto_nat {f : ℕ → nnreal} (r : nnreal) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end end nnreal lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := let f' (b : β) : nnreal := ⟨f b, le_trans (hg b) (hgf b)⟩ in let g' (b : β) : nnreal := ⟨g b, hg b⟩ in have summable f', from nnreal.summable_coe.1 hf, have summable g', from nnreal.summable_of_le (assume b, (@nnreal.coe_le (g' b) (f' b)).2 $ hgf b) this, show summable (λb, g' b : β → ℝ), from nnreal.summable_coe.2 this lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) := ⟨tendsto_sum_nat_of_has_sum, assume hfr, have 0 ≤ r := ge_of_tendsto at_top_ne_bot hfr $ univ_mem_sets' $ assume i, show 0 ≤ (finset.range i).sum f, from finset.sum_nonneg $ assume i _, hf i, let f' (n : ℕ) : nnreal := ⟨f n, hf n⟩, r' : nnreal := ⟨r, this⟩ in have f_eq : f = (λi:ℕ, (f' i : ℝ)) := rfl, have r_eq : r = r' := rfl, begin rw [f_eq, r_eq, nnreal.has_sum_coe, nnreal.has_sum_iff_tendsto_nat, ← nnreal.tendsto_coe], simp only [nnreal.sum_coe], exact hfr end⟩ lemma infi_real_pos_eq_infi_nnreal_pos {α : Type*} [complete_lattice α] {f : ℝ → α} : (⨅(n:ℝ) (h : n > 0), f n) = (⨅(n:nnreal) (h : n > 0), f n) := le_antisymm (le_infi $ assume n, le_infi $ assume hn, infi_le_of_le n $ infi_le _ (nnreal.coe_pos.2 hn)) (le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, le_of_lt hr⟩ $ infi_le _ hr) section variables [emetric_space β] open lattice ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ennreal} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ennreal) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ennreal) (h : x ∈ ball a r) : nhds x = map (coe : ball a r → β) (nhds ⟨x, h⟩) := (map_nhds_subtype_val_eq _ $ mem_nhds_sets emetric.is_open_ball h).symm end section variable [emetric_space α] open emetric /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [inhabited β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ennreal), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (nhds 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (nhds 0), { refine tendsto_orderable.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN q p (le_trans hn hq) (le_trans hn hp)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (nhds 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : {n | b n < ε} ∈ at_top := (tendsto_orderable.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s n) (s m) ≤ b N : b_bound n m N hn hm ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ennreal} (C : ennreal) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (λx, tendsto_orderable.2 ⟨_, _⟩), show ∀e, e < f x → {y : α | e < f y} ∈ nhds x, { assume e he, let ε := min (f x - e) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, { simp [C_zero, ‹0 < ε›] }, { calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }}, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y}, { rintros y hy, by_cases htop : f y = ⊤, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { simp at hy, have : e + ε < f y + ε := calc e + ε ≤ e + (f x - e) : add_le_add_left' (min_le_left _ _) ... = f x : by simp [le_of_lt he] ... ≤ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≤ f y + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I, show e < f y, from (ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }}, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, show ∀e, f x < e → {y : α | f y < e} ∈ nhds x, { assume e he, let ε := min (e - f x) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, simp [C_zero, ‹0 < ε›], calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e}, { rintros y hy, have htop : f x ≠ ⊤ := ne_top_of_lt he, show f y < e, from calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I ... ≤ f x + (e - f x) : add_le_add_left' (min_le_left _ _) ... = e : by simp [le_of_lt he] }, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, end theorem continuous_edist' : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by simp), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [add_comm, edist_comm] ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous_edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist'.comp (hf.prod_mk hg) theorem tendsto_edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, edist (f x) (g x)) x (nhds (edist a b)) := have tendsto (λp:α×α, edist p.1 p.2) (nhds (a, b)) (nhds (edist a b)), from continuous_iff_continuous_at.mp continuous_edist' (a, b), tendsto.comp (by rw [nhds_prod_eq] at this; exact this) (hf.prod_mk hg) end --section
4acbb5071a6b6ec291a6ffd12ca5ef21f58b8218
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/disjoint_finset.lean
93544bcfbe1da7ffbe39d1cc475eba07943e7cc8
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
2,792
lean
import data.finset namespace finset variable {α : Type*} def disjoint (s t : finset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false theorem disjoint.symm {s t : finset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : finset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) @[simp] theorem empty_disjoint (l : finset α) : disjoint ∅ l | a := (not_mem_empty a).elim @[simp] theorem singleton_disjoint [decidable_eq α] {l : finset α} {a : α} : disjoint (singleton a) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton [decidable_eq α] {l : finset α} {a : α} : disjoint l (singleton a) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_insert_left [decidable_eq α] {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp [disjoint, or_imp_distrib, forall_and_distrib]; refl @[simp] theorem disjoint_insert_right [decidable_eq α] {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_insert_left] theorem inter_eq_empty_iff_disjoint [decidable_eq α] {s t : finset α} : s ∩ t = ∅ ↔ disjoint s t := by simp [ext, mem_inter]; refl theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : finset α} : s ∩ t = ∅ ↔ disjoint s t := by rw ← subset_empty; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_val {s t : finset α} : multiset.disjoint s.1 t.1 ↔ disjoint s t := by simp [disjoint, multiset.disjoint, mem_def] @[simp] theorem card_disjoint_union [decidable_eq α] {s t : finset α} : disjoint s t → card (s ∪ t) = card s + card t := finset.induction_on s (by simp) $ begin simp {contextual := tt} end end finset
c0402ce32c9142acc36426e7424fe5b3a7375ece
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/simple_module.lean
1825410212884430d6bd3c48152135dfcb5968ff
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,417
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.basic import Mathlib.order.atoms import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Simple Modules ## Main Definitions * `is_simple_module` indicates that a module has no proper submodules (the only submodules are `⊥` and `⊤`). * A `division_ring` structure on the endomorphism ring of a simple module. ## Main Results * Schur's Lemma: `bijective_or_eq_zero` shows that a linear map between simple modules is either bijective or 0, leading to a `division_ring` structure on the endomorphism ring. ## TODO * Semisimple modules, Artin-Wedderburn Theory * Unify with the work on Schur's Lemma in a category theory context -/ /-- A module is simple when it has only two submodules, `⊥` and `⊤`. -/ def is_simple_module (R : Type u_1) [comm_ring R] (M : Type u_2) [add_comm_group M] [module R M] := is_simple_lattice (submodule R M) -- Making this an instance causes the linter to complain of "dangerous instances" theorem is_simple_module.nontrivial (R : Type u_1) [comm_ring R] (M : Type u_2) [add_comm_group M] [module R M] [is_simple_module R M] : nontrivial M := sorry namespace linear_map theorem injective_or_eq_zero {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [is_simple_module R M] (f : linear_map R M N) : function.injective ⇑f ∨ f = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (function.injective ⇑f ∨ f = 0)) (Eq.symm (propext ker_eq_bot)))) (eq.mpr (id (Eq._oldrec (Eq.refl (ker f = ⊥ ∨ f = 0)) (Eq.symm (propext ker_eq_top)))) (eq_bot_or_eq_top (ker f))) theorem injective_of_ne_zero {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [is_simple_module R M] {f : linear_map R M N} (h : f ≠ 0) : function.injective ⇑f := or.resolve_right (injective_or_eq_zero f) h theorem surjective_or_eq_zero {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [is_simple_module R N] (f : linear_map R M N) : function.surjective ⇑f ∨ f = 0 := sorry theorem surjective_of_ne_zero {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [is_simple_module R N] {f : linear_map R M N} (h : f ≠ 0) : function.surjective ⇑f := or.resolve_right (surjective_or_eq_zero f) h /-- Schur's Lemma for linear maps between (possibly distinct) simple modules -/ theorem bijective_or_eq_zero {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [is_simple_module R M] [is_simple_module R N] (f : linear_map R M N) : function.bijective ⇑f ∨ f = 0 := dite (f = 0) (fun (h : f = 0) => Or.inr h) fun (h : ¬f = 0) => or.intro_left (f = 0) { left := injective_of_ne_zero h, right := surjective_of_ne_zero h } theorem bijective_of_ne_zero {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [is_simple_module R M] [is_simple_module R N] {f : linear_map R M N} (h : f ≠ 0) : function.bijective ⇑f := or.resolve_right (bijective_or_eq_zero f) h /-- Schur's Lemma makes the endomorphism ring of a simple module a division ring. -/ protected instance module.End.division_ring {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] [DecidableEq (module.End R M)] [is_simple_module R M] : division_ring (module.End R M) := division_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry (fun (f : module.End R M) => dite (f = 0) (fun (h : f = 0) => 0) fun (h : ¬f = 0) => inverse f (equiv.inv_fun (equiv.of_bijective (⇑f) (bijective_of_ne_zero h))) sorry sorry) (div_inv_monoid.div._default ring.mul sorry ring.one sorry sorry fun (f : module.End R M) => dite (f = 0) (fun (h : f = 0) => 0) fun (h : ¬f = 0) => inverse f (equiv.inv_fun (equiv.of_bijective (⇑f) (bijective_of_ne_zero h))) sorry sorry) sorry sorry sorry
8c1853dac7c3e2f02edac31db4dc420f443451d4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/testing/slim_check/sampleable_auto.lean
7b26eea14c52fc1feac40378145ae566ce23d22c
[]
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
27,439
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.lazy_list.basic import Mathlib.data.tree import Mathlib.data.int.basic import Mathlib.control.bifunctor import Mathlib.tactic.linarith.default import Mathlib.testing.slim_check.gen import Mathlib.PostPort universes u_1 u l v w u_2 u_3 namespace Mathlib /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ namespace slim_check /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α : Sort u_1} [SizeOf α] (x : α) (y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ def shrink_fn (α : Type u_1) [SizeOf α] := (x : α) → lazy_list (Subtype fun (y : α) => sizeof_lt y x) /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable (α : Type u) where wf : SizeOf α sample : gen α shrink : (x : α) → lazy_list (Subtype fun (y : α) => sizeof y < sizeof x) /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [Functor F] where wf : (α : Type u) → [_inst_1 : SizeOf α] → SizeOf (F α) sample : {α : Type u} → gen α → gen (F α) shrink : (α : Type u) → [_inst_1 : SizeOf α] → shrink_fn α → shrink_fn (F α) p_repr : (α : Type u) → has_repr α → has_repr (F α) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] where wf : (α : Type u) → (β : Type v) → [_inst_1 : SizeOf α] → [_inst_2 : SizeOf β] → SizeOf (F α β) sample : {α : Type u} → {β : Type v} → gen α → gen β → gen (F α β) shrink : (α : Type u) → (β : Type v) → [_inst_1 : SizeOf α] → [_inst_2 : SizeOf β] → shrink_fn α → shrink_fn β → shrink_fn (F α β) p_repr : (α : Type u) → (β : Type v) → has_repr α → has_repr β → has_repr (F α β) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) where proxy_repr : Type v wf : SizeOf proxy_repr interp : autoParam (proxy_repr → α) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.slim_check.sampleable.mk_trivial_interp") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "slim_check") "sampleable") "mk_trivial_interp") []) p_repr : has_repr proxy_repr sample : gen proxy_repr shrink : shrink_fn proxy_repr protected instance sampleable_ext.of_sampleable {α : Type u_1} [sampleable α] [has_repr α] : sampleable_ext α := sampleable_ext.mk α (sample α) shrink protected instance sampleable.functor {α : Type u_1} {F : Type u_1 → Type u_2} [Functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := sampleable.mk (sampleable_functor.sample F (sample α)) (sampleable_functor.shrink α shrink) protected instance sampleable.bifunctor {α : Type u_1} {β : Type u_2} {F : Type u_1 → Type u_2 → Type u_3} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := sampleable.mk (sampleable_bifunctor.sample F (sample α) (sample β)) (sampleable_bifunctor.shrink α β shrink shrink) protected instance sampleable_ext.functor {α : Type u_1} {F : Type u_1 → Type u_2} [Functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := sampleable_ext.mk (F (sampleable_ext.proxy_repr α)) (sampleable_functor.sample F (sampleable_ext.sample α)) (sampleable_functor.shrink (sampleable_ext.proxy_repr α) sampleable_ext.shrink) protected instance sampleable_ext.bifunctor {α : Type u_1} {β : Type u_2} {F : Type u_1 → Type u_2 → Type u_3} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := sampleable_ext.mk (F (sampleable_ext.proxy_repr α) (sampleable_ext.proxy_repr β)) (sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β)) (sampleable_bifunctor.shrink (sampleable_ext.proxy_repr α) (sampleable_ext.proxy_repr β) sampleable_ext.shrink sampleable_ext.shrink) /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) (n : ℕ) : n ≤ k → List (Subtype fun (m : ℕ) => has_well_founded.r m k) → List (Subtype fun (m : ℕ) => has_well_founded.r m k) := sorry /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : List (Subtype fun (m : ℕ) => has_well_founded.r m n) := dite (n > 0) (fun (h : n > 0) => (fun (this : ∀ (k : ℕ), 1 < k → n / k < n) => { val := n / bit1 (bit1 (bit0 1)), property := sorry } :: { val := n / bit1 1, property := sorry } :: nat.shrink' n n sorry []) sorry) fun (h : ¬n > 0) => [] /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := sampleable.mk (f <$> sample α) fun (x : β) => (fun (this : ∀ (a : α), sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x)) => subtype.map f this <$> shrink (g x)) sorry protected instance nat.sampleable : sampleable ℕ := sampleable.mk (gen.sized fun (sz : ℕ) => gen.freq [(1, coe <$> gen.choose_any (fin (Nat.succ (sz ^ bit1 1)))), (bit1 1, coe <$> gen.choose_any (fin (Nat.succ sz)))] sorry) fun (x : ℕ) => lazy_list.of_list (nat.shrink x) /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α : Type} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → Option α := well_founded.fix sorry fun (x : α) (f_rec : (y : α) → has_well_founded.r y x → Option α) => do trace (string.empty ++ to_string x ++ (string.str (string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1))))))) (char.of_nat (bit0 (bit1 (bit0 (bit1 (bit1 1))))))) (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++ to_string (lazy_list.to_list (shrink x)) ++ string.empty)) fun (_ : Unit) => pure Unit.unit let y ← lazy_list.find (fun (a : Subtype fun (y : α) => sizeof y < sizeof x) => p ↑a) (shrink x) f_rec ↑y sorry <|> some (subtype.val y) protected instance fin.sampleable {n : ℕ} [fact (0 < n)] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' subtype.val sorry protected instance fin.sampleable' {n : ℕ} : sampleable (fin (Nat.succ n)) := sampleable.lift ℕ fin.of_nat subtype.val sorry protected instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred sorry /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : SizeOf ℤ := { sizeOf := int.nat_abs } protected instance int.sampleable : sampleable ℤ := sampleable.mk (gen.sized fun (sz : ℕ) => gen.freq [(1, subtype.val <$> gen.choose (-(↑sz ^ bit1 1 + 1)) (↑sz ^ bit1 1 + 1) sorry), (bit1 1, subtype.val <$> gen.choose (-(↑sz + 1)) (↑sz + 1) sorry)] sorry) fun (x : ℤ) => lazy_list.of_list (list.bind (nat.shrink (int.nat_abs x)) fun (_x : Subtype fun (m : ℕ) => has_well_founded.r m (int.nat_abs x)) => sorry) protected instance bool.sampleable : sampleable Bool := sampleable.mk (do let x ← gen.choose_any Bool return x) fun (b : Bool) => dite (↥b) (fun (h : ↥b) => lazy_list.singleton { val := false, property := sorry }) fun (h : ¬↥b) => lazy_list.nil /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α : Type u_1} {β : Type u_2} [SizeOf α] [SizeOf β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) := sorry protected instance prod.sampleable : sampleable_bifunctor Prod := sampleable_bifunctor.mk (fun (α : Type u) (β : Type v) (sama : gen α) (samb : gen β) => do uliftable.up sama sorry) prod.shrink prod.has_repr protected instance sigma.sampleable {α : Type u_1} {β : Type u_2} [sampleable α] [sampleable β] : sampleable (sigma fun (_x : α) => β) := sampleable.lift (α × β) (fun (_x : α × β) => sorry) (fun (_x : sigma fun (_x : α) => β) => sorry) sorry /-- shrinking function for sum types -/ def sum.shrink {α : Type u_1} {β : Type u_2} [SizeOf α] [SizeOf β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) := sorry protected instance sum.sampleable : sampleable_bifunctor sum := sampleable_bifunctor.mk (fun (α : Type u) (β : Type v) (sam_α : gen α) (sam_β : gen β) => uliftable.up_map sum.inl sam_α <|> uliftable.up_map sum.inr sam_β) (fun (α : Type u) (β : Type v) (Iα : SizeOf α) (Iβ : SizeOf β) (shr_α : shrink_fn α) (shr_β : shrink_fn β) => sum.shrink shr_α shr_β) sum.has_repr protected instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (fun (x : ℤ × ℕ+) => prod.cases_on x rat.mk_pnat) (fun (r : ℚ) => (rat.num r, { val := rat.denom r, property := rat.pos r })) sorry /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : ℕ) (characters : string) : sampleable char := sampleable.mk (do let x ← gen.choose_nat 0 length sorry ite (subtype.val x = 0) (do let n ← sample ℕ pure (char.of_nat n)) (do let i ← gen.choose_nat 0 (string.length characters - 1) sorry pure (string.iterator.curr (string.iterator.nextn (string.mk_iterator characters) ↑i)))) fun (_x : char) => lazy_list.nil protected instance char.sampleable : sampleable char := sorry theorem list.sizeof_drop_lt_sizeof_of_lt_length {α : Type u} [SizeOf α] {xs : List α} {k : ℕ} (hk : 0 < k) (hk' : k < list.length xs) : sizeof (list.drop k xs) < sizeof xs := sorry theorem list.sizeof_cons_lt_right {α : Type u} [SizeOf α] (a : α) (b : α) {xs : List α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := sorry theorem list.sizeof_cons_lt_left {α : Type u} [SizeOf α] (x : α) {xs : List α} {xs' : List α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := sorry theorem list.sizeof_append_lt_left {α : Type u} [SizeOf α] {xs : List α} {ys : List α} {ys' : List α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := sorry theorem list.one_le_sizeof {α : Type u} [SizeOf α] (xs : List α) : 1 ≤ sizeof xs := sorry /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes {α : Type u} [SizeOf α] (k : ℕ) (hk : 0 < k) (xs : List α) (n : ℕ) : n = list.length xs → lazy_list (Subtype fun (ys : List α) => sizeof_lt ys xs) := sorry /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one {α : Type u} [SizeOf α] (shr : (x : α) → lazy_list (Subtype fun (y : α) => sizeof_lt y x)) : shrink_fn (List α) := sorry /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with {α : Type u} [SizeOf α] (shr : (x : α) → lazy_list (Subtype fun (y : α) => sizeof_lt y x)) (xs : List α) : lazy_list (Subtype fun (ys : List α) => sizeof_lt ys xs) := let n : ℕ := list.length xs; lazy_list.append (lazy_list.bind (lazy_list.cons n fun (_ : Unit) => lazy_list.map subtype.val (lazy_list.reverse (shrink n))) fun (k : ℕ) => dite (0 < k) (fun (hk : 0 < k) => list.shrink_removes k hk xs n rfl) fun (hk : ¬0 < k) => lazy_list.nil) fun (_ : Unit) => list.shrink_one shr xs protected instance list.sampleable : sampleable_functor List := sampleable_functor.mk (fun (α : Type u) (sam_α : gen α) => gen.list_of sam_α) (fun (α : Type u) (Iα : SizeOf α) (shr_α : shrink_fn α) => list.shrink_with shr_α) list.has_repr protected instance prop.sampleable_ext : sampleable_ext Prop := sampleable_ext.mk Bool (gen.choose_any Bool) fun (_x : Bool) => lazy_list.nil /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type u_1) := α protected instance no_shrink.inhabited {α : Type u_1} [Inhabited α] : Inhabited (no_shrink α) := { default := Inhabited.default } /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α : Type u_1} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α : Type u_1} (x : no_shrink α) : α := x protected instance no_shrink.sampleable {α : Type u_1} [sampleable α] : sampleable (no_shrink α) := sampleable.mk (no_shrink.mk <$> sample α) fun (_x : no_shrink α) => lazy_list.nil protected instance string.sampleable : sampleable string := sampleable.mk (do let x ← gen.list_of (sample char) pure (list.as_string x)) shrink /-- implementation of `sampleable (tree α)` -/ def tree.sample {α : Type u} (sample : gen α) : ℕ → gen (tree α) := sorry /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type u_1} [SizeOf α] (t : α) (sh : (x : α) → sizeof_lt x t → lazy_list (Subtype fun (y : α) => sizeof_lt y x)) : shrink_fn (Subtype fun (t' : α) => sizeof_lt t' t) := sorry theorem tree.one_le_sizeof {α : Type u_1} [SizeOf α] (t : tree α) : 1 ≤ sizeof t := sorry protected instance tree.functor : Functor tree := { map := tree.map, mapConst := fun (α β : Type u_1) => tree.map ∘ function.const β } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with {α : Type u} [SizeOf α] (shrink_a : (x : α) → shrink_fn (Subtype fun (y : α) => sizeof_lt y x) → List (lazy_list (Subtype fun (y : α) => sizeof_lt y x))) : shrink_fn α := well_founded.fix (sizeof_measure_wf α) fun (t : α) (f_rec : (y : α) → sizeof_measure α y t → lazy_list (Subtype fun (y_1 : α) => sizeof_lt y_1 y)) => lazy_list.join (lazy_list.of_list (shrink_a t fun (_x : Subtype fun (y : α) => sizeof_lt y t) => sorry)) theorem rec_shrink_with_eq {α : Type u} [SizeOf α] (shrink_a : (x : α) → shrink_fn (Subtype fun (y : α) => sizeof_lt y x) → List (lazy_list (Subtype fun (y : α) => sizeof_lt y x))) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list (shrink_a x fun (t' : Subtype fun (y : α) => sizeof_lt y x) => rec_shrink x (fun (x_1 : α) (h' : sizeof_lt x_1 x) => rec_shrink_with shrink_a x_1) t')) := sorry /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with {α : Type u} [SizeOf α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with fun (t : tree α) => sorry protected instance sampleable_tree : sampleable_functor tree := sampleable_functor.mk (fun (α : Type u_1) (sam_α : gen α) => gen.sized (tree.sample sam_α)) (fun (α : Type u_1) (Iα : SizeOf α) (shr_α : shrink_fn α) => tree.shrink_with shr_α) tree.has_repr /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type u_1) := α /-- Add the `small` type tag -/ def small.mk {α : Type u_1} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type u_1) := α /-- Add the `large` type tag -/ def large.mk {α : Type u_1} (x : α) : large α := x protected instance small.functor : Functor small := applicative.to_functor protected instance large.functor : Functor large := applicative.to_functor protected instance small.inhabited {α : Type u} [Inhabited α] : Inhabited (small α) := { default := Inhabited.default } protected instance large.inhabited {α : Type u} [Inhabited α] : Inhabited (large α) := { default := Inhabited.default } protected instance small.sampleable_functor : sampleable_functor small := sampleable_functor.mk (fun (α : Type u_1) (samp : gen α) => gen.resize (fun (n : ℕ) => n / bit1 (bit0 1) + bit1 (bit0 1)) samp) (fun (α : Type u_1) (_x : SizeOf α) => id) fun (α : Type u_1) => id protected instance large.sampleable_functor : sampleable_functor large := sampleable_functor.mk (fun (α : Type u_1) (samp : gen α) => gen.resize (fun (n : ℕ) => n * bit1 (bit0 1)) samp) (fun (α : Type u_1) (_x : SizeOf α) => id) fun (α : Type u_1) => id protected instance ulift.sampleable_functor : sampleable_functor ulift := sampleable_functor.mk (fun (α : Type v) (samp : gen α) => uliftable.up_map ulift.up samp) (fun (α : Type v) (_x : SizeOf α) (shr : shrink_fn α) (_x : ulift α) => sorry) fun (α : Type v) (h : has_repr α) => has_repr.mk (repr ∘ ulift.down) /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ protected instance nat_le.sampleable {y : ℕ} : sampleable (Subtype fun (x : ℕ) => x ≤ y) := sampleable.mk (do gen.choose_nat 0 y sorry sorry) fun (_x : Subtype fun (x : ℕ) => x ≤ y) => sorry protected instance nat_ge.sampleable {x : ℕ} : sampleable (Subtype fun (y : ℕ) => x ≤ y) := sampleable.mk (do sample ℕ sorry) fun (_x : Subtype fun (y : ℕ) => x ≤ y) => sorry /- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` -/ protected instance nat_gt.sampleable {x : ℕ} : sampleable (Subtype fun (y : ℕ) => x < y) := sampleable.mk (do sample ℕ sorry) fun (x_1 : Subtype fun (y : ℕ) => x < y) => shrink x_1 /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ protected instance le.sampleable {α : Type u} {y : α} [sampleable α] [linear_ordered_add_comm_group α] : sampleable (Subtype fun (x : α) => x ≤ y) := sampleable.mk (do let x ← sample α pure { val := y - abs x, property := sorry }) fun (_x : Subtype fun (x : α) => x ≤ y) => lazy_list.nil protected instance ge.sampleable {α : Type u} {x : α} [sampleable α] [linear_ordered_add_comm_group α] : sampleable (Subtype fun (y : α) => x ≤ y) := sampleable.mk (do let y ← sample α pure { val := x + abs y, property := sorry }) fun (_x : Subtype fun (y : α) => x ≤ y) => lazy_list.nil /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ protected instance int_le.sampleable {y : ℤ} : sampleable (Subtype fun (x : ℤ) => x ≤ y) := sampleable.lift ℕ (fun (n : ℕ) => { val := y - ↑n, property := sorry }) (fun (_x : Subtype fun (x : ℤ) => x ≤ y) => sorry) sorry protected instance int_ge.sampleable {x : ℤ} : sampleable (Subtype fun (y : ℤ) => x ≤ y) := sampleable.lift ℕ (fun (n : ℕ) => { val := x + ↑n, property := sorry }) (fun (_x : Subtype fun (y : ℤ) => x ≤ y) => sorry) sorry protected instance int_lt.sampleable {y : ℤ} : sampleable (Subtype fun (x : ℤ) => x < y) := sampleable.lift ℕ (fun (n : ℕ) => { val := y - (↑n + 1), property := sorry }) (fun (_x : Subtype fun (x : ℤ) => x < y) => sorry) sorry protected instance int_gt.sampleable {x : ℤ} : sampleable (Subtype fun (y : ℤ) => x < y) := sampleable.lift ℕ (fun (n : ℕ) => { val := x + (↑n + 1), property := sorry }) (fun (_x : Subtype fun (y : ℤ) => x < y) => sorry) sorry /-! ### Subtypes of any `list` -/ protected instance perm.slim_check {α : Type u} {xs : List α} : sampleable (Subtype fun (ys : List α) => xs ~ ys) := sampleable.mk (gen.permutation_of xs) fun (_x : Subtype fun (ys : List α) => xs ~ ys) => lazy_list.nil protected instance perm'.slim_check {α : Type u} {xs : List α} : sampleable (Subtype fun (ys : List α) => ys ~ xs) := sampleable.mk (subtype.map id list.perm.symm <$> gen.permutation_of xs) fun (_x : Subtype fun (ys : List α) => ys ~ xs) => lazy_list.nil /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io Unit := do let xs ← io.run_rand (uliftable.down (do let xs ← mmap (reader_t.run g ∘ ulift.up) (list.range (bit0 (bit1 (bit0 1)))) pure (ulift.up (list.map repr xs)))) mmap' io.put_str_ln xs end Mathlib
e25394b4b87949b5976c4255cafe2a1967e66c3c
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/simpDischargeLoop.lean
c658e567fb14a000dfa0feb227faa09938db61ca
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,050
lean
open Nat def double : Nat → Nat | zero => 0 | succ n => succ (succ (double n)) theorem double.inj : double n = double m → n = m := by intro h induction n generalizing m with | zero => cases m <;> trivial | succ n ih => cases m with | zero => contradiction | succ m => simp [double] at h |- apply ih h theorem double.inj' : double n = double m → n = m := by intro h induction n generalizing m with | zero => cases m <;> trivial | succ n ih => cases m with | zero => contradiction | succ m => simp apply ih simp_all [double] theorem double.inj'' : double n = double m → n = m := by intro h induction n generalizing m with | zero => cases m <;> trivial | succ n ih => cases m with | zero => contradiction | succ m => simp [ih, double] simp [double] at h apply ih h theorem double.inj''' : double n = double m → n = m := by simp (config := { maxDischargeDepth := 2 }) simp (config := { maxSteps := 2000000 }) admit
52595f54872f7cb50206a623a5429240eed29a89
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/order/hom/ring.lean
6cc404b68cf77f6f9c56cadbbb365e600684e986
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
15,243
lean
/- Copyright (c) 2022 Alex J. Best, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Yaël Dillies -/ import algebra.order.archimedean import algebra.order.hom.monoid import algebra.order.ring.defs import algebra.ring.equiv import tactic.by_contra import tactic.wlog /-! # Ordered ring homomorphisms Homomorphisms between ordered (semi)rings that respect the ordering. ## Main definitions * `order_ring_hom` : Monotone semiring homomorphisms. * `order_ring_iso` : Monotone semiring isomorphisms. ## Notation * `→+*o`: Ordered ring homomorphisms. * `≃+*o`: Ordered ring isomorphisms. ## Tags ordered ring homomorphism, order homomorphism -/ open function variables {F α β γ δ : Type*} /-- `order_ring_hom α β` is the type of monotone semiring homomorphisms from `α` to `β`. When possible, instead of parametrizing results over `(f : order_ring_hom α β)`, you should parametrize over `(F : Type*) [order_ring_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_ring_hom_class`. -/ structure order_ring_hom (α β : Type*) [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] extends α →+* β := (monotone' : monotone to_fun) /-- Reinterpret an ordered ring homomorphism as a ring homomorphism. -/ add_decl_doc order_ring_hom.to_ring_hom infix ` →+*o `:25 := order_ring_hom /-- `order_ring_hom α β` is the type of order-preserving semiring isomorphisms between `α` and `β`. When possible, instead of parametrizing results over `(f : order_ring_iso α β)`, you should parametrize over `(F : Type*) [order_ring_iso_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_ring_iso_class`. -/ structure order_ring_iso (α β : Type*) [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] extends α ≃+* β := (map_le_map_iff' {a b : α} : to_fun a ≤ to_fun b ↔ a ≤ b) infix ` ≃+*o `:25 := order_ring_iso /-- `order_ring_hom_class F α β` states that `F` is a type of ordered semiring homomorphisms. You should extend this typeclass when you extend `order_ring_hom`. -/ class order_ring_hom_class (F : Type*) (α β : out_param $ Type*) [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] extends ring_hom_class F α β := (monotone (f : F) : monotone f) /-- `order_ring_iso_class F α β` states that `F` is a type of ordered semiring isomorphisms. You should extend this class when you extend `order_ring_iso`. -/ class order_ring_iso_class (F : Type*) (α β : out_param Type*) [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] extends ring_equiv_class F α β := (map_le_map_iff (f : F) {a b : α} : f a ≤ f b ↔ a ≤ b) @[priority 100] -- See note [lower priority instance] instance order_ring_hom_class.to_order_add_monoid_hom_class [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] : order_add_monoid_hom_class F α β := { .. ‹order_ring_hom_class F α β› } @[priority 100] -- See note [lower priority instance] instance order_ring_hom_class.to_order_monoid_with_zero_hom_class [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] : order_monoid_with_zero_hom_class F α β := { .. ‹order_ring_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_ring_iso_class.to_order_iso_class [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] [order_ring_iso_class F α β] : order_iso_class F α β := { ..‹order_ring_iso_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_ring_iso_class.to_order_ring_hom_class [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_iso_class F α β] : order_ring_hom_class F α β := { monotone := λ f, order_hom_class.mono f, ..‹order_ring_iso_class F α β› } instance [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] : has_coe_t F (α →+*o β) := ⟨λ f, ⟨f, order_hom_class.mono f⟩⟩ instance [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] [order_ring_iso_class F α β] : has_coe_t F (α ≃+*o β) := ⟨λ f, ⟨f, λ a b, map_le_map_iff f⟩⟩ /-! ### Ordered ring homomorphisms -/ namespace order_ring_hom variables [non_assoc_semiring α] [preorder α] section preorder variables [non_assoc_semiring β] [preorder β] [non_assoc_semiring γ] [preorder γ] [non_assoc_semiring δ] [preorder δ] /-- Reinterpret an ordered ring homomorphism as an ordered additive monoid homomorphism. -/ def to_order_add_monoid_hom (f : α →+*o β) : α →+o β := { ..f } /-- Reinterpret an ordered ring homomorphism as an order homomorphism. -/ def to_order_monoid_with_zero_hom (f : α →+*o β) : α →*₀o β := { ..f } instance : order_ring_hom_class (α →+*o β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_mul := λ f, f.map_mul', map_one := λ f, f.map_one', map_add := λ f, f.map_add', map_zero := λ f, f.map_zero', monotone := λ f, f.monotone' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →+*o β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ lemma to_fun_eq_coe (f : α →+*o β) : f.to_fun = ⇑f := rfl @[ext] lemma ext {f g : α →+*o β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h @[simp] lemma to_ring_hom_eq_coe (f : α →+*o β) : f.to_ring_hom = f := ring_hom.ext $ λ _, rfl @[simp] lemma to_order_add_monoid_hom_eq_coe (f : α →+*o β) : f.to_order_add_monoid_hom = f := rfl @[simp] lemma to_order_monoid_with_zero_hom_eq_coe (f : α →+*o β) : f.to_order_monoid_with_zero_hom = f := rfl @[simp] lemma coe_coe_ring_hom (f : α →+*o β) : ⇑(f : α →+* β) = f := rfl @[simp] lemma coe_coe_order_add_monoid_hom (f : α →+*o β) : ⇑(f : α →+o β) = f := rfl @[simp] lemma coe_coe_order_monoid_with_zero_hom (f : α →+*o β) : ⇑(f : α →*₀o β) = f := rfl @[norm_cast] lemma coe_ring_hom_apply (f : α →+*o β) (a : α) : (f : α →+* β) a = f a := rfl @[norm_cast] lemma coe_order_add_monoid_hom_apply (f : α →+*o β) (a : α) : (f : α →+o β) a = f a := rfl @[norm_cast] lemma coe_order_monoid_with_zero_hom_apply (f : α →+*o β) (a : α) : (f : α →*₀o β) a = f a := rfl /-- Copy of a `order_ring_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : α →+*o β) (f' : α → β) (h : f' = f) : α →+*o β := { .. f.to_ring_hom.copy f' h, .. f.to_order_add_monoid_hom.copy f' h } @[simp] lemma coe_copy (f : α →+*o β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : α →+*o β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variable (α) /-- The identity as an ordered ring homomorphism. -/ protected def id : α →+*o α := { ..ring_hom.id _, ..order_hom.id } instance : inhabited (α →+*o α) := ⟨order_ring_hom.id α⟩ @[simp] lemma coe_id : ⇑(order_ring_hom.id α) = id := rfl variable {α} @[simp] lemma id_apply (a : α) : order_ring_hom.id α a = a := rfl @[simp] lemma coe_ring_hom_id : (order_ring_hom.id α : α →+* α) = ring_hom.id α := rfl @[simp] lemma coe_order_add_monoid_hom_id : (order_ring_hom.id α : α →+o α) = order_add_monoid_hom.id α := rfl @[simp] lemma coe_order_monoid_with_zero_hom_id : (order_ring_hom.id α : α →*₀o α) = order_monoid_with_zero_hom.id α := rfl /-- Composition of two `order_ring_hom`s as an `order_ring_hom`. -/ protected def comp (f : β →+*o γ) (g : α →+*o β) : α →+*o γ := { ..f.to_ring_hom.comp g.to_ring_hom, ..f.to_order_add_monoid_hom.comp g.to_order_add_monoid_hom } @[simp] lemma coe_comp (f : β →+*o γ) (g : α →+*o β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : β →+*o γ) (g : α →+*o β) (a : α) : f.comp g a = f (g a) := rfl lemma comp_assoc (f : γ →+*o δ) (g : β →+*o γ) (h : α →+*o β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : α →+*o β) : f.comp (order_ring_hom.id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+*o β) : (order_ring_hom.id β).comp f = f := ext $ λ x, rfl lemma cancel_right {f₁ f₂ : β →+*o γ} {g : α →+*o β} (hg : surjective g) : f₁.comp g = f₂.comp g ↔ f₁ = f₂ := ⟨λ h, ext $ hg.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {f : β →+*o γ} {g₁ g₂ : α →+*o β} (hf : injective f) : f.comp g₁ = f.comp g₂ ↔ g₁ = g₂ := ⟨λ h, ext $ λ a, hf $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end preorder variables [non_assoc_semiring β] instance [preorder β] : preorder (order_ring_hom α β) := preorder.lift (coe_fn : _ → α → β) instance [partial_order β] : partial_order (order_ring_hom α β) := partial_order.lift _ fun_like.coe_injective end order_ring_hom /-! ### Ordered ring isomorphisms -/ namespace order_ring_iso section has_le variables [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] [has_mul γ] [has_add γ] [has_le γ] [has_mul δ] [has_add δ] [has_le δ] /-- Reinterpret an ordered ring isomorphism as an order isomorphism. -/ def to_order_iso (f : α ≃+*o β) : α ≃o β := ⟨f.to_ring_equiv.to_equiv, λ _ _, f.map_le_map_iff'⟩ instance : order_ring_iso_class (α ≃+*o β) α β := { coe := λ f, f.to_fun, inv := λ f, f.inv_fun, coe_injective' := λ f g h₁ h₂, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_add := λ f, f.map_add', map_mul := λ f, f.map_mul', map_le_map_iff := λ f _ _, f.map_le_map_iff', left_inv := λ f, f.left_inv, right_inv := λ f, f.right_inv } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α ≃+*o β) (λ _, α → β) := fun_like.has_coe_to_fun lemma to_fun_eq_coe (f : α ≃+*o β) : f.to_fun = f := rfl @[ext] lemma ext {f g : α ≃+*o β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h @[simp] lemma coe_mk (e : α ≃+* β) (h) : ⇑(⟨e, h⟩ : α ≃+*o β) = e := rfl @[simp] lemma mk_coe (e : α ≃+*o β) (h) : (⟨e, h⟩ : α ≃+*o β) = e := ext $ λ _, rfl @[simp] lemma to_ring_equiv_eq_coe (f : α ≃+*o β) : f.to_ring_equiv = f := ring_equiv.ext $ λ _, rfl @[simp] lemma to_order_iso_eq_coe (f : α ≃+*o β) : f.to_order_iso = f := order_iso.ext rfl @[simp, norm_cast] lemma coe_to_ring_equiv (f : α ≃+*o β) : ⇑(f : α ≃+* β) = f := rfl @[simp, norm_cast] lemma coe_to_order_iso (f : α ≃+*o β) : ⇑(f : α ≃o β) = f := rfl variable (α) /-- The identity map as an ordered ring isomorphism. -/ @[refl] protected def refl : α ≃+*o α := ⟨ring_equiv.refl α, λ _ _, iff.rfl⟩ instance : inhabited (α ≃+*o α) := ⟨order_ring_iso.refl α⟩ @[simp] lemma refl_apply (x : α) : order_ring_iso.refl α x = x := rfl @[simp] lemma coe_ring_equiv_refl : (order_ring_iso.refl α : α ≃+* α) = ring_equiv.refl α := rfl @[simp] lemma coe_order_iso_refl : (order_ring_iso.refl α : α ≃o α) = order_iso.refl α := rfl variables {α} /-- The inverse of an ordered ring isomorphism as an ordered ring isomorphism. -/ @[symm] protected def symm (e : α ≃+*o β) : β ≃+*o α := ⟨e.to_ring_equiv.symm, λ a b, by erw [←map_le_map_iff e, e.1.apply_symm_apply, e.1.apply_symm_apply]⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : α ≃+*o β) : β → α := e.symm @[simp] lemma symm_symm (e : α ≃+*o β) : e.symm.symm = e := ext $ λ _, rfl /-- Composition of `order_ring_iso`s as an `order_ring_iso`. -/ @[trans, simps] protected def trans (f : α ≃+*o β) (g : β ≃+*o γ) : α ≃+*o γ := ⟨f.to_ring_equiv.trans g.to_ring_equiv, λ a b, (map_le_map_iff g).trans (map_le_map_iff f)⟩ @[simp] lemma trans_apply (f : α ≃+*o β) (g : β ≃+*o γ) (a : α) : f.trans g a = g (f a) := rfl @[simp] lemma self_trans_symm (e : α ≃+*o β) : e.trans e.symm = order_ring_iso.refl α := ext e.left_inv @[simp] lemma symm_trans_self (e : α ≃+*o β) : e.symm.trans e = order_ring_iso.refl β := ext e.right_inv lemma symm_bijective : bijective (order_ring_iso.symm : (α ≃+*o β) → β ≃+*o α) := ⟨λ f g h, f.symm_symm.symm.trans $ (congr_arg order_ring_iso.symm h).trans g.symm_symm, λ f, ⟨f.symm, f.symm_symm⟩⟩ end has_le section non_assoc_semiring variables [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [non_assoc_semiring γ] [preorder γ] /-- Reinterpret an ordered ring isomorphism as an ordered ring homomorphism. -/ def to_order_ring_hom (f : α ≃+*o β) : α →+*o β := ⟨f.to_ring_equiv.to_ring_hom, λ a b, (map_le_map_iff f).2⟩ @[simp] lemma to_order_ring_hom_eq_coe (f : α ≃+*o β) : f.to_order_ring_hom = f := rfl @[simp, norm_cast] lemma coe_to_order_ring_hom (f : α ≃+*o β) : ⇑(f : α →+*o β) = f := rfl @[simp] lemma coe_to_order_ring_hom_refl : (order_ring_iso.refl α : α →+*o α) = order_ring_hom.id α := rfl lemma to_order_ring_hom_injective : injective (to_order_ring_hom : (α ≃+*o β) → α →+*o β) := λ f g h, fun_like.coe_injective $ by convert fun_like.ext'_iff.1 h end non_assoc_semiring end order_ring_iso /-! ### Uniqueness There is at most one ordered ring homomorphism from a linear ordered field to an archimedean linear ordered field. Reciprocally, such an ordered ring homomorphism exists when the codomain is further conditionally complete. -/ /-- There is at most one ordered ring homomorphism from a linear ordered field to an archimedean linear ordered field. -/ instance order_ring_hom.subsingleton [linear_ordered_field α] [linear_ordered_field β] [archimedean β] : subsingleton (α →+*o β) := ⟨λ f g, begin ext x, by_contra' h, wlog h : f x < g x using [f g, g f], { exact ne.lt_or_lt h }, obtain ⟨q, hf, hg⟩ := exists_rat_btwn h, rw ←map_rat_cast f at hf, rw ←map_rat_cast g at hg, exact (lt_asymm ((order_hom_class.mono g).reflect_lt hg) $ (order_hom_class.mono f).reflect_lt hf).elim, end⟩ /-- There is at most one ordered ring isomorphism between a linear ordered field and an archimedean linear ordered field. -/ instance order_ring_iso.subsingleton_right [linear_ordered_field α] [linear_ordered_field β] [archimedean β] : subsingleton (α ≃+*o β) := order_ring_iso.to_order_ring_hom_injective.subsingleton /-- There is at most one ordered ring isomorphism between an archimedean linear ordered field and a linear ordered field. -/ instance order_ring_iso.subsingleton_left [linear_ordered_field α] [archimedean α] [linear_ordered_field β] : subsingleton (α ≃+*o β) := order_ring_iso.symm_bijective.injective.subsingleton
592fbee9ed8c65651c4446a163a52b8bb335f52a
a49a42dda6e1ae18983e9264eb962585a900fa99
/src/circle.lean
4299a55cdcee84c18874053c593dc27a9adee2f9
[]
no_license
jamesa9283/Lean-AreaOfACircle
a5d22cbc96bc2cf2f76b79221b0ec65628edc333
c5d5030eeab98bb6552693de55a77a9cf2c21d20
refs/heads/master
1,676,179,712,721
1,610,133,816,000
1,610,133,816,000
327,885,903
0
0
null
null
null
null
UTF-8
Lean
false
false
1,099
lean
import data.real.basic analysis.special_functions.trigonometric import measure_theory.interval_integral import analysis.special_functions.pow open_locale real noncomputable theory open interval_integral example : ∫ (x : ℝ) in 0..1, x = 1/2 := begin have : deriv (λ x : ℝ, x^2/2) = λ x, x, { ext x, simp, field_simp, ring }, simp only [← this], rw integral_deriv_eq_sub, { norm_num }, { simp }, { rw this, exact continuous_id.continuous_on } end example (r : ℝ) : deriv (λ x : ℝ, (real.sqrt (r^2 - x^2))) = λ x, (-x/real.sqrt (r^2 - x^2)) := begin ext, rw deriv_sqrt, { simp only [differentiable_at_const, mul_one, zero_sub, deriv_sub, differentiable_at_id', deriv_pow'', nat.cast_bit0, deriv_id'', deriv_const', pow_one, differentiable_at.pow, nat.cast_one, mul_zero], sorry }, { sorry }, { } end example (r : ℝ) (x : ℝ) : 4 * ∫ x in (0: ℝ)..r, (real.sqrt (r^2 - x^2)) = π*r^2 := begin have : deriv (λ x : ℝ, (real.sqrt (r^2 - x^2))) = λ x, (-x/real.sqrt (r^2 - x^2)), { ext, sorry }, sorry end
1898f364607b5e0d994a887db23c656d448141ec
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/order/ideal.lean
98cd460a2f2a9c41e694f6b898bf5c45e4dd4539
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,235
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import order.basic import data.equiv.encodable.basic /-! # Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `ideal P`: the type of upward directed, downward closed subsets of `P`. Dual to the notion of a filter on a preorder. - `cofinal P`: the type of subsets of `P` containing arbitrarily large elements. Dual to the notion of 'dense set' used in forcing. - `ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`. ## References - https://en.wikipedia.org/wiki/Ideal_(order_theory) - https://en.wikipedia.org/wiki/Cofinal_(mathematics) - https://en.wikipedia.org/wiki/Rasiowa–Sikorski_lemma Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`, in line with most presentations of forcing. ## Tags ideal, cofinal, dense, countable, generic -/ namespace order variables {P : Type*} /-- An ideal on a preorder `P` is a subset of `P` that is - nonempty - upward directed - downward closed. -/ structure ideal (P) [preorder P] := (carrier : set P) (nonempty : carrier.nonempty) (directed : directed_on (≤) carrier) (mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ carrier → x ∈ carrier) namespace ideal section preorder variables [preorder P] {x : P} {I J : ideal P} /-- The smallest ideal containing a given element. -/ def principal (p : P) : ideal P := { carrier := { x | x ≤ p }, nonempty := ⟨p, le_refl _⟩, directed := λ x hx y hy, ⟨p, le_refl _, hx, hy⟩, mem_of_le := λ x y hxy hy, le_trans hxy hy, } instance [inhabited P] : inhabited (ideal P) := ⟨ideal.principal $ default P⟩ /-- An ideal of `P` can be viewed as a subset of `P`. -/ instance : has_coe (ideal P) (set P) := ⟨carrier⟩ /-- For the notation `x ∈ I`. -/ instance : has_mem P (ideal P) := ⟨λ x I, x ∈ (I : set P)⟩ /-- Two ideals are equal when their underlying sets are equal. -/ @[ext] lemma ext : ∀ (I J : ideal P), (I : set P) = J → I = J | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ rfl := rfl /-- The partial ordering by subset inclusion, inherited from `set P`. -/ instance : partial_order (ideal P) := partial_order.lift coe ext @[trans] lemma mem_of_mem_of_le : x ∈ I → I ≤ J → x ∈ J := @set.mem_of_mem_of_subset P x I J @[simp] lemma principal_le_iff : principal x ≤ I ↔ x ∈ I := ⟨λ (h : ∀ {y}, y ≤ x → y ∈ I), h (le_refl x), λ h_mem y (h_le : y ≤ x), I.mem_of_le h_le h_mem⟩ end preorder section order_bot variables [order_bot P] {I : ideal P} /-- A specific witness of `I.nonempty` when `P` has a bottom element. -/ @[simp] lemma bot_mem : ⊥ ∈ I := I.mem_of_le bot_le I.nonempty.some_mem /-- There is a bottom ideal when `P` has a bottom element. -/ instance : order_bot (ideal P) := { bot := principal ⊥, bot_le := by simp, .. ideal.partial_order } end order_bot /-- There is a top ideal when `P` has a top element. -/ instance {P} [order_top P] : order_top (ideal P) := { top := principal ⊤, le_top := λ I x h, le_top, .. ideal.partial_order } section semilattice_sup variables [semilattice_sup P] {x y : P} {I : ideal P} /-- A specific witness of `I.directed` when `P` has joins. -/ lemma sup_mem (x y ∈ I) : x ⊔ y ∈ I := let ⟨z, h_mem, hx, hy⟩ := I.directed x ‹_› y ‹_› in I.mem_of_le (sup_le hx hy) h_mem @[simp] lemma sup_mem_iff : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I := ⟨λ h, ⟨I.mem_of_le le_sup_left h, I.mem_of_le le_sup_right h⟩, λ h, sup_mem x y h.left h.right⟩ end semilattice_sup section semilattice_sup_bot variables [semilattice_sup_bot P] (I J K : ideal P) /-- The intersection of two ideals is an ideal, when `P` has joins and a bottom. -/ def inf (I J : ideal P) : ideal P := { carrier := I ∩ J, nonempty := ⟨⊥, bot_mem, bot_mem⟩, directed := λ x ⟨_, _⟩ y ⟨_, _⟩, ⟨x ⊔ y, ⟨sup_mem x y ‹_› ‹_›, sup_mem x y ‹_› ‹_›⟩, by simp⟩, mem_of_le := λ x y h ⟨_, _⟩, ⟨mem_of_le I h ‹_›, mem_of_le J h ‹_›⟩ } /-- There is a smallest ideal containing two ideals, when `P` has joins and a bottom. -/ def sup (I J : ideal P) : ideal P := { carrier := {x | ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j}, nonempty := ⟨⊥, ⊥, bot_mem, ⊥, bot_mem, bot_le⟩, directed := λ x ⟨xi, _, xj, _, _⟩ y ⟨yi, _, yj, _, _⟩, ⟨x ⊔ y, ⟨xi ⊔ yi, sup_mem xi yi ‹_› ‹_›, xj ⊔ yj, sup_mem xj yj ‹_› ‹_›, sup_le (calc x ≤ xi ⊔ xj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_left le_sup_left) (calc y ≤ yi ⊔ yj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_right le_sup_right)⟩, le_sup_left, le_sup_right⟩, mem_of_le := λ x y _ ⟨yi, _, yj, _, _⟩, ⟨yi, ‹_›, yj, ‹_›, le_trans ‹x ≤ y› ‹_›⟩ } lemma sup_le : I ≤ K → J ≤ K → sup I J ≤ K := λ hIK hJK x ⟨i, hiI, j, hjJ, hxij⟩, K.mem_of_le hxij $ sup_mem i j (mem_of_mem_of_le hiI hIK) (mem_of_mem_of_le hjJ hJK) instance : lattice (ideal P) := { sup := sup, le_sup_left := λ I J (i ∈ I), ⟨i, ‹_›, ⊥, bot_mem, by simp only [sup_bot_eq]⟩, le_sup_right := λ I J (j ∈ J), ⟨⊥, bot_mem, j, ‹_›, by simp only [bot_sup_eq]⟩, sup_le := sup_le, inf := inf, inf_le_left := λ I J, set.inter_subset_left I J, inf_le_right := λ I J, set.inter_subset_right I J, le_inf := λ I J K, set.subset_inter, .. ideal.partial_order } @[simp] lemma mem_inf {x : P} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff_of_eq rfl @[simp] lemma mem_sup {x : P} : x ∈ I ⊔ J ↔ ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j := iff_of_eq rfl end semilattice_sup_bot end ideal /-- For a preorder `P`, `cofinal P` is the type of subsets of `P` containing arbitrarily large elements. They are the dense sets in the topology whose open sets are terminal segments. -/ structure cofinal (P) [preorder P] := (carrier : set P) (mem_gt : ∀ x : P, ∃ y ∈ carrier, x ≤ y) namespace cofinal variables [preorder P] instance : inhabited (cofinal P) := ⟨{ carrier := set.univ, mem_gt := λ x, ⟨x, trivial, le_refl _⟩}⟩ instance : has_mem P (cofinal P) := ⟨λ x D, x ∈ D.carrier⟩ variables (D : cofinal P) (x : P) /-- A (noncomputable) element of a cofinal set lying above a given element. -/ noncomputable def above : P := classical.some $ D.mem_gt x lemma above_mem : D.above x ∈ D := exists.elim (classical.some_spec $ D.mem_gt x) $ λ a _, a lemma le_above : x ≤ D.above x := exists.elim (classical.some_spec $ D.mem_gt x) $ λ _ b, b end cofinal section ideal_of_cofinals variables [preorder P] (p : P) {ι : Type*} [encodable ι] (𝒟 : ι → cofinal P) /-- Given a starting point, and a countable family of cofinal sets, this is an increasing sequence that intersects each cofinal set. -/ noncomputable def sequence_of_cofinals : ℕ → P | 0 := p | (n+1) := match encodable.decode ι n with | none := sequence_of_cofinals n | some i := (𝒟 i).above (sequence_of_cofinals n) end lemma sequence_of_cofinals.monotone : monotone (sequence_of_cofinals p 𝒟) := by { apply monotone_of_monotone_nat, intros n, dunfold sequence_of_cofinals, cases encodable.decode ι n, { refl }, { apply cofinal.le_above }, } lemma sequence_of_cofinals.encode_mem (i : ι) : sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i := by { dunfold sequence_of_cofinals, rw encodable.encodek, apply cofinal.above_mem, } /-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`, indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which - contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and - intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`. This proves the Rasiowa–Sikorski lemma. -/ def ideal_of_cofinals : ideal P := { carrier := { x : P | ∃ n, x ≤ sequence_of_cofinals p 𝒟 n }, nonempty := ⟨p, 0, le_refl _⟩, directed := λ x ⟨n, hn⟩ y ⟨m, hm⟩, ⟨_, ⟨max n m, le_refl _⟩, le_trans hn $ sequence_of_cofinals.monotone p 𝒟 (le_max_left _ _), le_trans hm $ sequence_of_cofinals.monotone p 𝒟 (le_max_right _ _) ⟩, mem_of_le := λ x y hxy ⟨n, hn⟩, ⟨n, le_trans hxy hn⟩, } lemma mem_ideal_of_cofinals : p ∈ ideal_of_cofinals p 𝒟 := ⟨0, le_refl _⟩ /-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/ lemma cofinal_meets_ideal_of_cofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 := ⟨_, sequence_of_cofinals.encode_mem p 𝒟 i, _, le_refl _⟩ end ideal_of_cofinals end order
e5371e7bb88a0a086bff2fc7fd14b35a503eedaa
649957717d58c43b5d8d200da34bf374293fe739
/src/category_theory/types.lean
032c2ed3ad1c1cf2ce8336e881a687a3974c2537
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
4,562
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl import category_theory.functor_category import category_theory.fully_faithful import data.equiv.basic namespace category_theory universes v v' w u u' -- declare the `v`'s first; see `category_theory.category` for an explanation instance types : large_category (Sort u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } @[simp] lemma types_hom {α β : Sort u} : (α ⟶ β) = (α → β) := rfl @[simp] lemma types_id (X : Sort u) : 𝟙 X = id := rfl @[simp] lemma types_comp {X Y Z : Sort u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl namespace functor variables {J : Type u} [𝒥 : category.{v} J] include 𝒥 def sections (F : J ⥤ Type w) : set (Π j, F.obj j) := { u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'} end functor namespace functor_to_types variables {C : Type u} [𝒞 : category.{v} C] (F G H : C ⥤ Sort w) {X Y Z : C} include 𝒞 variables (σ : F ⟶ G) (τ : G ⟶ H) @[simp] lemma map_comp (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp @[simp] lemma map_id (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl end functor_to_types def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_full : full ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down } instance ulift_functor_faithful : faithful ulift_functor := { injectivity' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x lemma hom_of_element_eq_iff {X : Type u} (x y : X) : hom_of_element x = hom_of_element y ↔ x = y := ⟨λ H, congr_fun H punit.star, by cc⟩ lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intros H x x' h, resetI, rw ←hom_of_element_eq_iff at ⊢ h, exact (cancel_mono f).mp h }, { refine λ H, ⟨λ Z g h H₂, _⟩, ext z, replace H₂ := congr_fun H₂ z, exact H H₂ } end lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { intros H, let g : Y ⟶ ulift Prop := λ y, ⟨true⟩, let h : Y ⟶ ulift Prop := λ y, ⟨∃ x, f x = y⟩, suffices : f ≫ g = f ≫ h, { resetI, rw cancel_epi at this, intro y, replace this := congr_fun this y, replace this : true = ∃ x, f x = y := congr_arg ulift.down this, rw ←this, trivial }, ext x, change true ↔ ∃ x', f x' = f x, rw true_iff, exact ⟨x, rfl⟩ }, { intro H, constructor, intros Z g h H₂, apply funext, rw ←forall_iff_forall_surj H, intro x, exact (congr_fun H₂ x : _) } end end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Sort u} def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv namespace category_theory.iso universe u variables {X Y : Sort u} def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl end category_theory.iso
ccdc83dcca1a4848af95e3b65b692324fdc28d8c
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebraic_topology/simplex_category.lean
335a502fd6a9dd11eb7717855b2afb1f8918f24c
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
27,263
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import category_theory.skeletal import tactic.linarith import data.fintype.sort import order.category.NonemptyFinLinOrd import category_theory.functor.reflects_isomorphisms /-! # The simplex category We construct a skeletal model of the simplex category, with objects `ℕ` and the morphism `n ⟶ m` being the monotone maps from `fin (n+1)` to `fin (m+1)`. We show that this category is equivalent to `NonemptyFinLinOrd`. ## Remarks The definitions `simplex_category` and `simplex_category.hom` are marked as irreducible. We provide the following functions to work with these objects: 1. `simplex_category.mk` creates an object of `simplex_category` out of a natural number. Use the notation `[n]` in the `simplicial` locale. 2. `simplex_category.len` gives the "length" of an object of `simplex_category`, as a natural. 3. `simplex_category.hom.mk` makes a morphism out of a monotone map between `fin`'s. 4. `simplex_category.hom.to_order_hom` gives the underlying monotone map associated to a term of `simplex_category.hom`. -/ universe v open category_theory /-- The simplex category: * objects are natural numbers `n : ℕ` * morphisms from `n` to `m` are monotone functions `fin (n+1) → fin (m+1)` -/ @[derive inhabited, irreducible] def simplex_category := ℕ namespace simplex_category section local attribute [semireducible] simplex_category -- TODO: Make `mk` irreducible. /-- Interpet a natural number as an object of the simplex category. -/ def mk (n : ℕ) : simplex_category := n localized "notation `[`n`]` := simplex_category.mk n" in simplicial -- TODO: Make `len` irreducible. /-- The length of an object of `simplex_category`. -/ def len (n : simplex_category) : ℕ := n @[ext] lemma ext (a b : simplex_category) : a.len = b.len → a = b := id @[simp] lemma len_mk (n : ℕ) : [n].len = n := rfl @[simp] lemma mk_len (n : simplex_category) : [n.len] = n := rfl /-- Morphisms in the simplex_category. -/ @[irreducible, nolint has_nonempty_instance] protected def hom (a b : simplex_category) := fin (a.len + 1) →o fin (b.len + 1) namespace hom local attribute [semireducible] simplex_category.hom /-- Make a moprhism in `simplex_category` from a monotone map of fin's. -/ def mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : simplex_category.hom a b := f /-- Recover the monotone map from a morphism in the simplex category. -/ def to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : fin (a.len + 1) →o fin (b.len + 1) := f @[ext] lemma ext {a b : simplex_category} (f g : simplex_category.hom a b) : f.to_order_hom = g.to_order_hom → f = g := id @[simp] lemma mk_to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : mk (f.to_order_hom) = f := rfl @[simp] lemma to_order_hom_mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : (mk f).to_order_hom = f := rfl lemma mk_to_order_hom_apply {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) (i : fin (a.len + 1)) : (mk f).to_order_hom i = f i := rfl /-- Identity morphisms of `simplex_category`. -/ @[simp] def id (a : simplex_category) : simplex_category.hom a a := mk order_hom.id /-- Composition of morphisms of `simplex_category`. -/ @[simp] def comp {a b c : simplex_category} (f : simplex_category.hom b c) (g : simplex_category.hom a b) : simplex_category.hom a c := mk $ f.to_order_hom.comp g.to_order_hom end hom @[simps] instance small_category : small_category.{0} simplex_category := { hom := λ n m, simplex_category.hom n m, id := λ m, simplex_category.hom.id _, comp := λ _ _ _ f g, simplex_category.hom.comp g f, } /-- The constant morphism from [0]. -/ def const (x : simplex_category) (i : fin (x.len+1)) : [0] ⟶ x := hom.mk $ ⟨λ _, i, by tauto⟩ @[simp] lemma const_comp (x y : simplex_category) (i : fin (x.len + 1)) (f : x ⟶ y) : const x i ≫ f = const y (f.to_order_hom i) := rfl /-- Make a morphism `[n] ⟶ [m]` from a monotone map between fin's. This is useful for constructing morphisms beetween `[n]` directly without identifying `n` with `[n].len`. -/ @[simp] def mk_hom {n m : ℕ} (f : (fin (n+1)) →o (fin (m+1))) : [n] ⟶ [m] := simplex_category.hom.mk f lemma hom_zero_zero (f : [0] ⟶ [0]) : f = 𝟙 _ := by { ext : 2, dsimp, apply subsingleton.elim } end open_locale simplicial section generators /-! ## Generating maps for the simplex category TODO: prove that the simplex category is equivalent to one given by the following generators and relations. -/ /-- The `i`-th face map from `[n]` to `[n+1]` -/ def δ {n} (i : fin (n+2)) : [n] ⟶ [n+1] := mk_hom (fin.succ_above i).to_order_hom /-- The `i`-th degeneracy map from `[n+1]` to `[n]` -/ def σ {n} (i : fin (n+1)) : [n+1] ⟶ [n] := mk_hom { to_fun := fin.pred_above i, monotone' := fin.pred_above_right_monotone i } /-- The generic case of the first simplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : δ i ≫ δ j.succ = δ j ≫ δ i.cast_succ := begin ext k, dsimp [δ, fin.succ_above], simp only [order_embedding.to_order_hom_coe, order_embedding.coe_of_strict_mono, function.comp_app, simplex_category.hom.to_order_hom_mk, order_hom.comp_coe], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, split_ifs; { simp at *; linarith }, end /-- The special case of the first simplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : δ i ≫ δ i.cast_succ = δ i ≫ δ i.succ := (δ_comp_δ (le_refl i)).symm /-- The second simplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : δ i.cast_succ ≫ σ j.succ = σ j ≫ δ i := begin ext k, suffices : ite (j.succ.cast_succ < ite (k < i) k.cast_succ k.succ) (ite (k < i) (k:ℕ) (k + 1) - 1) (ite (k < i) k (k + 1)) = ite ((if h : (j:ℕ) < k then k.pred (by { rintro rfl, exact nat.not_lt_zero _ h }) else k.cast_lt (by { cases j, cases k, simp only [len_mk], linarith })).cast_succ < i) (ite (j.cast_succ < k) (k - 1) k) (ite (j.cast_succ < k) (k - 1) k + 1), { dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, convert rfl }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [subtype.mk_le_mk, fin.cast_succ_mk] at H, dsimp, split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with two of them by hand. swap 8, { exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) ‹_›)).symm, }, swap 7, { have : k ≤ i := nat.le_of_pred_lt ‹_›, linarith, }, -- Hope for the best from `linarith`: all_goals { try { refl <|> simp at * }; linarith, }, end /-- The first part of the third simplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : δ i.cast_succ ≫ σ i = 𝟙 [n] := begin ext j, suffices : ite (fin.cast_succ i < ite (j < i) (fin.cast_succ j) j.succ) (ite (j < i) (j:ℕ) (j + 1) - 1) (ite (j < i) j (j + 1)) = j, { dsimp [δ, σ, fin.succ_above, fin.pred_above], simpa [fin.pred_above] with push_cast }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp, split_ifs; { simp at *; linarith, }, end /-- The second part of the third simplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : δ i.succ ≫ σ i = 𝟙 [n] := begin ext j, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, split_ifs; { simp at *; linarith, }, end /-- The fourth simplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : δ i.succ ≫ σ j.cast_succ = σ j ≫ δ i := begin ext k, dsimp [δ, σ, fin.succ_above, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [subtype.mk_lt_mk, fin.cast_succ_mk] at H, suffices : ite (_ < ite (k < i + 1) _ _) _ _ = ite _ (ite (j < k) (k - 1) k) (ite (j < k) (k - 1) k + 1), { simpa [apply_dite fin.cast_succ, fin.pred_above] with push_cast, }, split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with three of them by hand. swap 2, { simp only [subtype.mk_lt_mk] at h_1, simp only [not_lt] at h_2, simp only [self_eq_add_right, one_ne_zero], exact lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (ne_of_lt (lt_of_le_of_lt (zero_le _) h_1)).symm) (le_trans (nat.le_of_lt_succ h) h_2)) }, swap 4, { simp only [subtype.mk_lt_mk] at h_1, simp only [not_lt] at h, simp only [nat.add_succ_sub_one, add_zero], exfalso, exact lt_irrefl _ (lt_of_le_of_lt (nat.le_pred_of_lt (nat.lt_of_succ_le h)) h_3), }, swap 4, { simp only [subtype.mk_lt_mk] at h_1, simp only [not_lt] at h_3, simp only [nat.add_succ_sub_one, add_zero], exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) h_2)).symm, }, -- Hope for the best from `linarith`: all_goals { simp at h_1 h_2 ⊢; linarith, }, end local attribute [simp] fin.pred_mk /-- The fifth simplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : σ i.cast_succ ≫ σ j = σ j.succ ≫ σ i := begin ext k, dsimp [σ, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [subtype.mk_le_mk] at H, -- At this point `simp with push_cast` makes good progress, but neither `simp?` nor `squeeze_simp` -- return usable sets of lemmas. -- To avoid using a non-terminal simp, we make a `suffices` statement indicating the shape -- of the goal we're looking for, and then use `simpa with push_cast`. -- I'm not sure this is actually much more robust that a non-terminal simp. suffices : ite (_ < dite (i < k) _ _) _ _ = ite (_ < dite (j + 1 < k) _ _) _ _, { simpa [fin.pred_above] with push_cast, }, split_ifs, -- `split_ifs` created 12 goals. -- Most of them are dealt with `by simp at *; linarith`, -- but we pull out two harder ones to do by hand. swap 3, { simp only [not_lt] at h_2, exact false.elim (lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (id (ne_of_lt (lt_of_le_of_lt (zero_le i) h)).symm)) (le_trans h_2 (nat.succ_le_of_lt h_1)))) }, swap 3, { simp only [subtype.mk_lt_mk, not_lt] at h_1, exact false.elim (lt_irrefl j (lt_of_lt_of_le (nat.pred_lt_pred (nat.succ_ne_zero j) h_2) h_1)) }, -- Deal with the rest automatically. all_goals { simp at *; linarith, }, end end generators section skeleton /-- The functor that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ @[simps obj map] def skeletal_functor : simplex_category ⥤ NonemptyFinLinOrd.{v} := { obj := λ a, NonemptyFinLinOrd.of $ ulift (fin (a.len + 1)), map := λ a b f, ⟨λ i, ulift.up (f.to_order_hom i.down), λ i j h, f.to_order_hom.monotone h⟩, map_id' := λ a, by { ext, simp, }, map_comp' := λ a b c f g, by { ext, simp, }, } lemma skeletal : skeletal simplex_category := λ X Y ⟨I⟩, begin suffices : fintype.card (fin (X.len+1)) = fintype.card (fin (Y.len+1)), { ext, simpa }, { apply fintype.card_congr, refine equiv.ulift.symm.trans (((skeletal_functor ⋙ forget _).map_iso I).to_equiv.trans _), apply equiv.ulift } end namespace skeletal_functor instance : full skeletal_functor.{v} := { preimage := λ a b f, simplex_category.hom.mk ⟨λ i, (f (ulift.up i)).down, λ i j h, f.monotone h⟩, witness' := by { intros m n f, dsimp at *, ext1 ⟨i⟩, ext1, ext1, cases x, simp, } } instance : faithful skeletal_functor.{v} := { map_injective' := λ m n f g h, begin ext1, ext1, ext1 i, apply ulift.up.inj, change (skeletal_functor.map f) ⟨i⟩ = (skeletal_functor.map g) ⟨i⟩, rw h, end } instance : ess_surj skeletal_functor.{v} := { mem_ess_image := λ X, ⟨mk (fintype.card X - 1 : ℕ), ⟨begin have aux : fintype.card X = fintype.card X - 1 + 1, { exact (nat.succ_pred_eq_of_pos $ fintype.card_pos_iff.mpr ⟨⊥⟩).symm, }, let f := mono_equiv_of_fin X aux, have hf := (finset.univ.order_emb_of_fin aux).strict_mono, refine { hom := ⟨λ i, f i.down, _⟩, inv := ⟨λ i, ⟨f.symm i⟩, _⟩, hom_inv_id' := _, inv_hom_id' := _ }, { rintro ⟨i⟩ ⟨j⟩ h, show f i ≤ f j, exact hf.monotone h, }, { intros i j h, show f.symm i ≤ f.symm j, rw ← hf.le_iff_le, show f (f.symm i) ≤ f (f.symm j), simpa only [order_iso.apply_symm_apply], }, { ext1, ext1 ⟨i⟩, ext1, exact f.symm_apply_apply i }, { ext1, ext1 i, exact f.apply_symm_apply i }, end⟩⟩, } noncomputable instance is_equivalence : is_equivalence (skeletal_functor.{v}) := equivalence.of_fully_faithfully_ess_surj skeletal_functor end skeletal_functor /-- The equivalence that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ noncomputable def skeletal_equivalence : simplex_category ≌ NonemptyFinLinOrd.{v} := functor.as_equivalence skeletal_functor end skeleton /-- `simplex_category` is a skeleton of `NonemptyFinLinOrd`. -/ noncomputable def is_skeleton_of : is_skeleton_of NonemptyFinLinOrd simplex_category skeletal_functor.{v} := { skel := skeletal, eqv := skeletal_functor.is_equivalence } /-- The truncated simplex category. -/ @[derive small_category] def truncated (n : ℕ) := full_subcategory (λ a : simplex_category, a.len ≤ n) namespace truncated instance {n} : inhabited (truncated n) := ⟨⟨[0],by simp⟩⟩ /-- The fully faithful inclusion of the truncated simplex category into the usual simplex category. -/ @[derive [full, faithful]] def inclusion {n : ℕ} : simplex_category.truncated n ⥤ simplex_category := full_subcategory_inclusion _ end truncated section concrete instance : concrete_category.{0} simplex_category := { forget := { obj := λ i, fin (i.len + 1), map := λ i j f, f.to_order_hom }, forget_faithful := {} } end concrete section epi_mono /-- A morphism in `simplex_category` is a monomorphism precisely when it is an injective function -/ theorem mono_iff_injective {n m : simplex_category} {f : n ⟶ m} : mono f ↔ function.injective f.to_order_hom := begin split, { introsI m x y h, have H : const n x ≫ f = const n y ≫ f, { dsimp, rw h }, change (n.const x).to_order_hom 0 = (n.const y).to_order_hom 0, rw cancel_mono f at H, rw H }, { exact concrete_category.mono_of_injective f } end /-- A morphism in `simplex_category` is an epimorphism if and only if it is a surjective function -/ lemma epi_iff_surjective {n m : simplex_category} {f: n ⟶ m} : epi f ↔ function.surjective f.to_order_hom := begin split, { introsI hyp_f_epi x, by_contra' h_ab, -- The proof is by contradiction: assume f is not surjective, -- then introduce two non-equal auxiliary functions equalizing f, and get a contradiction. -- First we define the two auxiliary functions. set chi_1 : m ⟶ [1] := hom.mk ⟨λ u, if u ≤ x then 0 else 1, begin intros a b h, dsimp only [], split_ifs with h1 h2 h3, any_goals { exact le_rfl }, { exact bot_le }, { exact false.elim (h1 (le_trans h h3)) } end ⟩, set chi_2 : m ⟶ [1] := hom.mk ⟨λ u, if u < x then 0 else 1, begin intros a b h, dsimp only [], split_ifs with h1 h2 h3, any_goals { exact le_rfl }, { exact bot_le }, { exact false.elim (h1 (lt_of_le_of_lt h h3)) } end ⟩, -- The two auxiliary functions equalize f have f_comp_chi_i : f ≫ chi_1 = f ≫ chi_2, { dsimp, ext, simp [le_iff_lt_or_eq, h_ab x_1] }, -- We now just have to show the two auxiliary functions are not equal. rw category_theory.cancel_epi f at f_comp_chi_i, rename f_comp_chi_i eq_chi_i, apply_fun (λ e, e.to_order_hom x) at eq_chi_i, suffices : (0 : fin 2) = 1, by exact bot_ne_top this, simpa using eq_chi_i }, { exact concrete_category.epi_of_surjective f } end /-- A monomorphism in `simplex_category` must increase lengths-/ lemma len_le_of_mono {x y : simplex_category} {f : x ⟶ y} : mono f → (x.len ≤ y.len) := begin intro hyp_f_mono, have f_inj : function.injective f.to_order_hom.to_fun, { exact mono_iff_injective.elim_left (hyp_f_mono) }, simpa using fintype.card_le_of_injective f.to_order_hom.to_fun f_inj, end lemma le_of_mono {n m : ℕ} {f : [n] ⟶ [m]} : (category_theory.mono f) → (n ≤ m) := len_le_of_mono /-- An epimorphism in `simplex_category` must decrease lengths-/ lemma len_le_of_epi {x y : simplex_category} {f : x ⟶ y} : epi f → y.len ≤ x.len := begin intro hyp_f_epi, have f_surj : function.surjective f.to_order_hom.to_fun, { exact epi_iff_surjective.elim_left (hyp_f_epi) }, simpa using fintype.card_le_of_surjective f.to_order_hom.to_fun f_surj, end lemma le_of_epi {n m : ℕ} {f : [n] ⟶ [m]} : epi f → (m ≤ n) := len_le_of_epi instance {n : ℕ} {i : fin (n+2)} : mono (δ i) := begin rw mono_iff_injective, exact fin.succ_above_right_injective, end instance {n : ℕ} {i : fin (n+1)} : epi (σ i) := begin rw epi_iff_surjective, intro b, simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], by_cases b ≤ i, { use b, rw fin.pred_above_below i b (by simpa only [fin.coe_eq_cast_succ] using h), simp only [fin.coe_eq_cast_succ, fin.cast_pred_cast_succ], }, { use b.succ, rw [fin.pred_above_above i b.succ _, fin.pred_succ], rw not_le at h, rw fin.lt_iff_coe_lt_coe at h ⊢, simpa only [fin.coe_succ, fin.coe_cast_succ] using nat.lt.step h, } end instance : reflects_isomorphisms (forget simplex_category) := ⟨begin intros x y f, introI, exact is_iso.of_iso { hom := f, inv := hom.mk { to_fun := inv ((forget simplex_category).map f), monotone' :=λ y₁ y₂ h, begin by_cases h' : y₁ < y₂, { by_contradiction h'', have eq := λ i, congr_hom (iso.inv_hom_id (as_iso ((forget _).map f))) i, have ineq := f.to_order_hom.monotone' (le_of_not_ge h''), dsimp at ineq, erw [eq, eq] at ineq, exact not_le.mpr h' ineq, }, { rw eq_of_le_of_not_lt h h', } end, }, hom_inv_id' := by { ext1, ext1, exact iso.hom_inv_id (as_iso ((forget _).map f)), }, inv_hom_id' := by { ext1, ext1, exact iso.inv_hom_id (as_iso ((forget _).map f)), }, }, end⟩ lemma is_iso_of_bijective {x y : simplex_category} {f : x ⟶ y} (hf : function.bijective (f.to_order_hom.to_fun)) : is_iso f := begin haveI : is_iso ((forget simplex_category).map f) := (is_iso_iff_bijective _).mpr hf, exact is_iso_of_reflects_iso f (forget simplex_category), end /-- An isomorphism in `simplex_category` induces an `order_iso`. -/ @[simp] def order_iso_of_iso {x y : simplex_category} (e : x ≅ y) : fin (x.len+1) ≃o fin (y.len+1) := equiv.to_order_iso { to_fun := e.hom.to_order_hom, inv_fun := e.inv.to_order_hom, left_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.hom_inv_id', right_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.inv_hom_id', } e.hom.to_order_hom.monotone e.inv.to_order_hom.monotone lemma iso_eq_iso_refl {x : simplex_category} (e : x ≅ x) : e = iso.refl x := begin have h : (finset.univ : finset (fin (x.len+1))).card = x.len+1 := finset.card_fin (x.len+1), have eq₁ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso e) i)), have eq₂ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso (iso.refl x)) i)), ext1, ext1, convert congr_arg (λ φ, (order_embedding.to_order_hom φ)) (eq₁.trans eq₂.symm), ext1, ext1 i, refl, end lemma eq_id_of_is_iso {x : simplex_category} {f : x ⟶ x} (hf : is_iso f) : f = 𝟙 _ := congr_arg (λ (φ : _ ≅ _), φ.hom) (iso_eq_iso_refl (as_iso f)) lemma eq_σ_comp_of_not_injective' {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (i : fin (n+1)) (hi : θ.to_order_hom i.cast_succ = θ.to_order_hom i.succ): ∃ (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin use δ i.succ ≫ θ, ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, mk_hom, order_hom.coe_fun_mk], by_cases h' : x ≤ i.cast_succ, { rw fin.pred_above_below i x h', have eq := fin.cast_succ_cast_pred (gt_of_gt_of_ge (fin.cast_succ_lt_last i) h'), erw fin.succ_above_below i.succ x.cast_pred _, swap, { rwa [eq, ← fin.le_cast_succ_iff], }, rw eq, }, { simp only [not_le] at h', let y := x.pred begin intro h, rw h at h', simpa only [fin.lt_iff_coe_lt_coe, nat.not_lt_zero, fin.coe_zero] using h', end, simp only [show x = y.succ, by rw fin.succ_pred] at h' ⊢, rw [fin.pred_above_above i y.succ h', fin.pred_succ], by_cases h'' : y = i, { rw h'', convert hi.symm, erw fin.succ_above_below i.succ _, exact fin.lt_succ, }, { erw fin.succ_above_above i.succ _, simp only [fin.lt_iff_coe_lt_coe, fin.le_iff_coe_le_coe, fin.coe_succ, fin.coe_cast_succ, nat.lt_succ_iff, fin.ext_iff] at h' h'' ⊢, cases nat.le.dest h' with c hc, cases c, { exfalso, rw [add_zero] at hc, rw [hc] at h'', exact h'' rfl, }, { rw ← hc, simp only [add_le_add_iff_left, nat.succ_eq_add_one, le_add_iff_nonneg_left, zero_le], }, }, } end lemma eq_σ_comp_of_not_injective {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (hθ : ¬function.injective θ.to_order_hom) : ∃ (i : fin (n+1)) (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin simp only [function.injective, exists_prop, not_forall] at hθ, -- as θ is not injective, there exists `x<y` such that `θ x = θ y` -- and then, `θ x = θ (x+1)` have hθ₂ : ∃ (x y : fin (n+2)), (hom.to_order_hom θ) x = (hom.to_order_hom θ) y ∧ x<y, { rcases hθ with ⟨x, y, ⟨h₁, h₂⟩⟩, by_cases x<y, { exact ⟨x, y, ⟨h₁, h⟩⟩, }, { refine ⟨y, x, ⟨h₁.symm, _⟩⟩, cases lt_or_eq_of_le (not_lt.mp h) with h' h', { exact h', }, { exfalso, exact h₂ h'.symm, }, }, }, rcases hθ₂ with ⟨x, y, ⟨h₁, h₂⟩⟩, let z := x.cast_pred, use z, simp only [← (show z.cast_succ = x, by exact fin.cast_succ_cast_pred (lt_of_lt_of_le h₂ (fin.le_last y)))] at h₁ h₂, apply eq_σ_comp_of_not_injective', rw fin.cast_succ_lt_iff_succ_le at h₂, apply le_antisymm, { exact θ.to_order_hom.monotone (le_of_lt (fin.cast_succ_lt_succ z)), }, { rw h₁, exact θ.to_order_hom.monotone h₂, }, end lemma eq_comp_δ_of_not_surjective' {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (i : fin (n+2)) (hi : ∀ x, θ.to_order_hom x ≠ i) : ∃ (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin by_cases i < fin.last (n+1), { use θ ≫ σ (fin.cast_pred i), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp], by_cases h' : θ.to_order_hom x ≤ i, { simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], rw fin.pred_above_below (fin.cast_pred i) (θ.to_order_hom x) (by simpa [fin.cast_succ_cast_pred h] using h'), erw fin.succ_above_below i, swap, { simp only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ], exact lt_of_le_of_lt (fin.coe_cast_pred_le_self _) (fin.lt_iff_coe_lt_coe.mp ((ne.le_iff_lt (hi x)).mp h')), }, rw fin.cast_succ_cast_pred, apply lt_of_le_of_lt h' h, }, { simp only [not_le] at h', simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk, fin.pred_above_above (fin.cast_pred i) (θ.to_order_hom x) (by simpa only [fin.cast_succ_cast_pred h] using h')], erw [fin.succ_above_above i _, fin.succ_pred], simpa only [fin.le_iff_coe_le_coe, fin.coe_cast_succ, fin.coe_pred] using nat.le_pred_of_lt (fin.lt_iff_coe_lt_coe.mp h'), }, }, { obtain rfl := le_antisymm (fin.le_last i) (not_lt.mp h), use θ ≫ σ (fin.last _), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, δ, mk_hom, order_hom.coe_fun_mk, order_embedding.to_order_hom_coe, fin.pred_above_last, fin.succ_above_last, fin.cast_succ_cast_pred ((ne.le_iff_lt (hi x)).mp (fin.le_last _))], }, end lemma eq_comp_δ_of_not_surjective {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (hθ : ¬function.surjective θ.to_order_hom) : ∃ (i : fin (n+2)) (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin cases not_forall.mp hθ with i hi, use i, exact eq_comp_δ_of_not_surjective' θ i (not_exists.mp hi), end lemma eq_id_of_mono {x : simplex_category} (i : x ⟶ x) [mono i] : i = 𝟙 _ := begin apply eq_id_of_is_iso, apply is_iso_of_bijective, dsimp, rw [fintype.bijective_iff_injective_and_card i.to_order_hom, ← mono_iff_injective, eq_self_iff_true, and_true], apply_instance, end lemma eq_id_of_epi {x : simplex_category} (i : x ⟶ x) [epi i] : i = 𝟙 _ := begin apply eq_id_of_is_iso, apply is_iso_of_bijective, dsimp, rw [fintype.bijective_iff_surjective_and_card i.to_order_hom, ← epi_iff_surjective, eq_self_iff_true, and_true], apply_instance, end lemma eq_σ_of_epi {n : ℕ} (θ : mk (n+1) ⟶ mk n) [epi θ] : ∃ (i : fin (n+1)), θ = σ i := begin rcases eq_σ_comp_of_not_injective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [nat.one_ne_zero, add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_mono (mono_iff_injective.mpr h), }, use i, haveI : epi (σ i ≫ θ') := by { rw ← h, apply_instance, }, haveI := category_theory.epi_of_epi (σ i) θ', rw [h, eq_id_of_epi θ', category.comp_id], end lemma eq_δ_of_mono {n : ℕ} (θ : mk n ⟶ mk (n+1)) [mono θ] : ∃ (i : fin (n+2)), θ = δ i := begin rcases eq_comp_δ_of_not_surjective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_epi (epi_iff_surjective.mpr h), }, use i, haveI : mono (θ' ≫ δ i) := by { rw ← h, apply_instance, }, haveI := category_theory.mono_of_mono θ' (δ i), rw [h, eq_id_of_mono θ', category.id_comp], end end epi_mono /-- This functor `simplex_category ⥤ Cat` sends `[n]` (for `n : ℕ`) to the category attached to the ordered set `{0, 1, ..., n}` -/ @[simps obj map] def to_Cat : simplex_category ⥤ Cat.{0} := simplex_category.skeletal_functor ⋙ forget₂ NonemptyFinLinOrd LinearOrder ⋙ forget₂ LinearOrder Lattice ⋙ forget₂ Lattice PartialOrder ⋙ forget₂ PartialOrder Preorder ⋙ Preorder_to_Cat end simplex_category
4df19d1195a6229f8d558b3c8376ec99b212f93b
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/data/bij_on.lean
e1558ca126793305441998e0fc6ff9b03454e7f0
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
7,040
lean
import data.equiv.basic import data.set.function import for_mathlib import data.is_equiv open set equiv section Bij_on variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} -- A constructive version of bij_on: f : a → b is an equivalence. Note -- that f is defined on all of α, but its inverse need only be defined -- on b ⊆ β. structure Bij_on (f : α → β) (a : set α) (b : set β) := (e : a ≃ b) (he : ∀ (x : a), f x = e x) variables {f : α → β} {a : set α} {b : set β} -- Alternate constructor for the case when a = univ. def Bij_on.mk_univ (e : α ≃ b) (he : ∀ x, f x = e x) : Bij_on f univ b := { e := (equiv.set.univ _).trans e, he := assume x, by rw [he x]; refl } -- Construct a bijection from an equivalence. def Bij_on.of_equiv (e : α ≃ β) : Bij_on e.to_fun univ univ := Bij_on.mk_univ (e.trans (equiv.set.univ _).symm) (by intro x; refl) def Bij_on.of_Is_equiv (h : Is_equiv f) : Bij_on f univ univ := by convert Bij_on.of_equiv h.e; funext a; rw [h.h] { occs := occurrences.pos [1] }; refl def Bij_on.Is_equiv (h : Bij_on f univ univ) : Is_equiv f := { e := (equiv.set.univ _).symm.trans (h.e.trans (equiv.set.univ _)), h := funext $ λ a, h.he ⟨a, trivial⟩ } lemma Bij_on.he' (h : Bij_on f a b) {x : α} (hx : x ∈ a) : f x = h.e ⟨x, hx⟩ := h.he ⟨x, hx⟩ instance (f : α → β) (a : set α) (b : set β) : subsingleton (Bij_on f a b) := ⟨assume ⟨e, he⟩ ⟨e', he'⟩, have e = e', from coe_fn_injective (by funext x; apply subtype.eq; exact (he x).symm.trans (he' x)), by cc⟩ lemma Bij_on.maps_to (h : Bij_on f a b) : maps_to f a b := assume x hx, show f x ∈ b, by rw h.he' hx; exact (h.e _).property lemma Bij_on.inj_on (h : Bij_on f a b) : inj_on f a := assume x hx x' hx' hh, begin rw [h.he' hx, h.he' hx'] at hh, have := subtype.eq hh, simpa using this end lemma Bij_on.injective (h : Bij_on f univ b) : function.injective f := injective_iff_inj_on_univ.mpr h.inj_on lemma Bij_on.right_inv (h : Bij_on f a b) (y) : f (h.e.symm y) = y := by rw h.he; simp @[refl] def Bij_on.refl (a : set α) : Bij_on id a a := { e := equiv.refl _, he := assume x, rfl } @[trans] def Bij_on.trans {f : α → β} {g : β → γ} {a : set α} {b : set β} {c : set γ} (hf : Bij_on f a b) (hg : Bij_on g b c) : Bij_on (g ∘ f) a c := { e := hf.e.trans hg.e, he := assume x, show g (f x) = hg.e (hf.e x), by rw [hf.he, hg.he] } def Bij_on.trans_symm {f : α → β} {g : β → γ} {a : set α} {b : set β} {c : set γ} (hf : ∀ x, x ∈ a → f x ∈ b) (hgf : Bij_on (g ∘ f) a c) (hg : Bij_on g b c) : Bij_on f a b := { e := hgf.e.trans hg.e.symm, he := assume x, show f x = hg.e.symm (hgf.e x), begin apply hg.inj_on, exact hf x.val x.property, exact (hg.e.symm (hgf.e x)).property, change (g ∘ f) x = _, rw [hg.he, hgf.he], simp end } -- Product of two bijections. def Bij_on.prod {f : α → β} {a : set α} {b : set β} {g : γ → δ} {c : set γ} {d : set δ} (hf : Bij_on f a b) (hg : Bij_on g c d) : Bij_on (λ (p : α × γ), (f p.1, g p.2)) (a.prod c) (b.prod d) := { e := -- This is a bit ugly. But building e out of equiv.prod_congr made -- the proof of `he` more difficult. Part of the problem is that -- `equiv.set.prod` is too "strict": its to_fun pattern matches on -- its argument. { to_fun := λ p, ⟨(hf.e ⟨p.1.1, p.2.1⟩, hg.e ⟨p.1.2, p.2.2⟩), ⟨(hf.e ⟨p.1.1, p.2.1⟩).property, (hg.e ⟨p.1.2, p.2.2⟩).property⟩⟩, inv_fun := λ p, ⟨(hf.e.symm ⟨p.1.1, p.2.1⟩, hg.e.symm ⟨p.1.2, p.2.2⟩), ⟨(hf.e.symm ⟨p.1.1, p.2.1⟩).property, (hg.e.symm ⟨p.1.2, p.2.2⟩).property⟩⟩, left_inv := λ ⟨⟨x, y⟩, ⟨hx, hy⟩⟩, by simp, right_inv := λ ⟨⟨x, y⟩, ⟨hx, hy⟩⟩, by simp }, he := λ ⟨⟨x, y⟩, ⟨hx, hy⟩⟩, show (f (subtype.mk x hx), g (subtype.mk y hy)) = _, by rw [hf.he, hg.he]; simp } -- Product of two total bijections. -- Again, we need to use this instead of `equiv.prod_congr` because -- the latter is too strict. def Bij_on.prod' {f : α → β} {g : γ → δ} (hf : Bij_on f univ univ) (hg : Bij_on g univ univ) : Bij_on (λ (p : α × γ), (f p.1, g p.2)) univ univ := begin convert Bij_on.prod hf hg; ext p; simp end -- Product of a total bijection by a type. def Bij_on.prod_right' {f : α → β} {b : set β} (hf : Bij_on f univ b) : Bij_on (λ (p : α × γ), (f p.1, p.2)) univ (b.prod univ) := by convert Bij_on.prod hf (Bij_on.refl univ); simp -- Restriction of a bijection to a subset. def Bij_on.restrict (h : Bij_on f a b) (r : set β) : Bij_on f (f ⁻¹' r ∩ a) (r ∩ b) := { e := { to_fun := λ p, ⟨h.e ⟨p.val, p.property.right⟩, by rw ←h.he; exact p.property.left, (h.e _).property⟩, inv_fun := λ p, ⟨h.e.symm ⟨p.val, p.property.right⟩, by rw [mem_preimage, h.he]; simpa using p.property.left, (h.e.symm _).property⟩, left_inv := λ ⟨p, hp⟩, by simp, right_inv := λ ⟨p, hp⟩, by simp }, he := λ ⟨p, hp⟩, by change f p = _; rw h.he' hp.right; simp } -- Restriction of a total bijection to a subset. def Bij_on.restrict' (h : Bij_on f univ b) (r : set β) : Bij_on f (f ⁻¹' r) (r ∩ b) := by convert Bij_on.restrict h r; simp def Bij_on.restrict'' (h : Bij_on f univ univ) (r : set β) : Bij_on f (f ⁻¹' r) r := by convert Bij_on.restrict' h r; simp def Bij_on.restrict_equiv (e : α ≃ β) (r : set β) : Bij_on e.to_fun (e.to_fun ⁻¹' r) r := (Bij_on.of_equiv e).restrict'' r -- Restriction of a bijection to a subtype on both sides. -- TODO: Reduce duplicated ugliness with Bij_on.restrict? def Bij_on.restrict_to_subtype (h : Bij_on f a b) (r : β → Prop) : Bij_on (λ (x : subtype (f ⁻¹' r)), (⟨f x.val, x.property⟩ : subtype r)) {x | x.val ∈ a} {y | y.val ∈ b} := { e := { to_fun := λ p, ⟨⟨h.e ⟨p.val.val, p.property⟩, by rw ←h.he; exact p.val.property⟩, (h.e _).property⟩, inv_fun := λ p, ⟨⟨h.e.symm ⟨p.val.val, p.property⟩, show ↑(h.e.symm ⟨p.val.val, p.property⟩) ∈ f ⁻¹' r, by rw [mem_preimage, h.he]; simp⟩, (h.e.symm _).property⟩, left_inv := λ ⟨p, hp⟩, by simp, right_inv := λ ⟨p, hp⟩, by simp }, he := λ ⟨p, hp⟩, by apply subtype.eq; change f p = _; rw h.he'; refl } -- Bijection between a subtype and a propositionally equal one. def Bij_on.congr_subtype {r r' : set α} (h : r = r') : Bij_on (λ (x : subtype r), (⟨x, _⟩ : subtype r')) univ univ := Bij_on.of_equiv $ equiv.set_congr h -- TODO: Use this to simplify other colimit lemmas? def Bij_on.congr_subset {α : Type*} {r r' : set α} (h : r = r') : Bij_on id r r' := { e := { to_fun := λ p, ⟨p.val, h ▸ p.property⟩, inv_fun := λ p, ⟨p.val, h.symm ▸ p.property⟩, left_inv := λ p, by cases p; refl, right_inv := λ p, by cases p; refl }, he := λ p, by cases p; refl } end Bij_on
da1ba97bb5f91f0d65d69ee89c695126639f1b5d
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/zsqrtd/basic.lean
076b8bd2f47aa8d221266c8095fbbbb885828df6
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
26,993
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 algebra.associated import tactic.ring /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case, but of course both parts are real here since `d` is nonnegative. -/ structure zsqrtd (d : ℤ) := (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : ℤ√d := of_int 0 instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : inhabited ℤ√d := ⟨0⟩ /-- The one of the ring -/ def one : ℤ√d := of_int 1 instance : has_one ℤ√d := ⟨zsqrtd.one⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ def add : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add ℤ√d := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ def neg : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `ℤ√d` -/ def mul : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring ℤ√d := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, ..}; { intros, simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] } instance : add_comm_monoid ℤ√d := by apply_instance instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance instance : zero_ne_one_class ℤ√d := { zero := 0, one := 1, zero_ne_one := dec_trivial } instance : nonzero_comm_ring ℤ√d := { ..zsqrtd.comm_ring, ..zsqrtd.zero_ne_one_class } @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := by induction n; simp * theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; simp * theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_injective := λ m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul : Π {a b : ℤ√d}, conj (a * b) = conj a * conj b := by simp [ext, add_comm] protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := by simp [ext] protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := by simp [ext, sub_eq_add_neg] protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := by simp [ext] protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] instance : is_monoid_hom norm := { map_one := norm_one, map_mul := norm_mul } lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : ℤ√d) : Prop := nonneg (b - a) instance : has_le ℤ√d := ⟨zsqrtd.le⟩ protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a) instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le (a b : ℤ√d) : decidable (a ≤ b) := decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this theorem nonneg_add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊢, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, by simpa [sub_eq_add_neg, add_left_comm] theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder ℤ√d := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_square (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : decidable_linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ eq_of_mul_eq_mul_right w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ eq_of_mul_eq_mul_right z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : integral_domain ℤ√d := { zero_ne_one := zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, ..zsqrtd.comm_ring } protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : decidable_linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, zero_ne_one := zero_ne_one, mul_pos := @zsqrtd.mul_pos, zero_lt_one := dec_trivial, ..zsqrtd.comm_ring, ..zsqrtd.decidable_linear_order } instance : decidable_linear_ordered_semiring ℤ√d := by apply_instance instance : linear_ordered_semiring ℤ√d := by apply_instance instance : ordered_semiring ℤ√d := by apply_instance end end zsqrtd
e0e9a866b23696b8fce4547a772aa3b0eddc2a38
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/simps.lean
665f3c16082e3618d5e42fa6165be337d176a1f6
[ "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
36,319
lean
import algebra.hom.group import data.sum.basic import tactic.simps universes v u w -- set_option trace.simps.verbose true -- set_option trace.simps.debug true -- set_option trace.app_builder true open function tactic expr structure equiv' (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) local infix (name := equiv') ` ≃ `:25 := equiv' /- Since `prod` and `pprod` are a special case for `@[simps]`, we define a new structure to test the basic functionality.-/ structure my_prod (α β : Type*) := (fst : α) (snd : β) def myprod.map {α α' β β'} (f : α → α') (g : β → β') (x : my_prod α β) : my_prod α' β' := ⟨f x.1, g x.2⟩ namespace foo @[simps] protected def rfl {α} : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ /- simps adds declarations -/ run_cmd do e ← get_env, e.get `foo.rfl_to_fun, e.get `foo.rfl_inv_fun, success_if_fail (e.get `foo.rfl_left_inv), success_if_fail (e.get `foo.rfl_right_inv), p ← simps_aux.get_param `foo.rfl, guard $ p = [`foo.rfl_to_fun, `foo.rfl_inv_fun] example (n : ℕ) : foo.rfl.to_fun n = n := by rw [foo.rfl_to_fun, id] example (n : ℕ) : foo.rfl.inv_fun n = n := by rw [foo.rfl_inv_fun] /- the declarations are `simp` lemmas -/ @[simps] def foo : ℕ × ℤ := (1, 2) example : foo.1 = 1 := by simp example : foo.2 = 2 := by simp example : foo.1 = 1 := by { dsimp, refl } -- check that dsimp also unfolds example : foo.2 = 2 := by { dsimp, refl } example {α} (x : α) : foo.rfl.to_fun x = x := by simp example {α} (x : α) : foo.rfl.inv_fun x = x := by simp example {α} (x : α) : foo.rfl.to_fun = @id α := by { success_if_fail {simp}, refl } /- check some failures -/ def bar1 : ℕ := 1 -- type is not a structure noncomputable def bar2 {α} : α ≃ α := classical.choice ⟨foo.rfl⟩ run_cmd do success_if_fail_with_msg (simps_tac `foo.bar1) "Invalid `simps` attribute. Target nat is not a structure", success_if_fail_with_msg (simps_tac `foo.bar2) "Invalid `simps` attribute. The body is not a constructor application: classical.choice bar2._proof_1", e ← get_env, let nm := `foo.bar1, d ← e.get nm, let lhs : expr := const d.to_name (d.univ_params.map level.param), simps_add_projections e nm d.type lhs d.value [] d.univ_params ff {} [] [] /- test that if a non-constructor is given as definition, then `{rhs_md := semireducible, simp_rhs := tt}` is applied automatically. -/ @[simps] def rfl2 {α} : α ≃ α := foo.rfl example {α} (x : α) : rfl2.to_fun x = x ∧ rfl2.inv_fun x = x := begin dsimp only [rfl2_to_fun, rfl2_inv_fun], guard_target (x = x ∧ x = x), exact ⟨rfl, rfl⟩ end /- test `fully_applied` option -/ @[simps {fully_applied := ff}] def rfl3 {α} : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ end foo /- we reduce the type when applying [simps] -/ def my_equiv := equiv' @[simps] def baz : my_equiv ℕ ℕ := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ /- test name clashes -/ def name_clash_fst := 1 def name_clash_snd := 1 def name_clash_snd_2 := 1 @[simps] def name_clash := (2, 3) run_cmd do e ← get_env, e.get `name_clash_fst_2, e.get `name_clash_snd_3 /- check projections for nested structures -/ namespace count_nested @[simps {attrs := [`simp, `norm]}] def nested1 : my_prod ℕ $ my_prod ℤ ℕ := ⟨2, -1, 1⟩ @[simps {attrs := []}] def nested2 : ℕ × my_prod ℕ ℕ := ⟨2, myprod.map nat.succ nat.pred ⟨1, 2⟩⟩ end count_nested run_cmd do e ← get_env, e.get `count_nested.nested1_fst, e.get `count_nested.nested1_snd_fst, e.get `count_nested.nested1_snd_snd, e.get `count_nested.nested2_fst, e.get `count_nested.nested2_snd, is_simp_lemma `count_nested.nested1_fst >>= λ b, guard b, -- simp attribute is global is_simp_lemma `count_nested.nested2_fst >>= λ b, guard $ ¬b, --lemmas_only doesn't add simp lemma guard $ 7 = e.fold 0 -- there are no other lemmas generated (λ d n, n + if d.to_name.components.init.ilast = `count_nested then 1 else 0) -- testing with arguments @[simps] def bar {α : Type*} (n m : ℕ) : ℕ × ℤ := ⟨n - m, n + m⟩ structure equiv_plus_data (α β) extends α ≃ β := (P : (α → β) → Prop) (data : P to_fun) structure automorphism_plus_data α extends α ⊕ α ≃ α ⊕ α := (P : (α ⊕ α → α ⊕ α) → Prop) (data : P to_fun) (extra : bool → my_prod ℕ ℕ) @[simps] def refl_with_data {α} : equiv_plus_data α α := { P := λ f, f = id, data := rfl, ..foo.rfl } @[simps] def refl_with_data' {α} : equiv_plus_data α α := { P := λ f, f = id, data := rfl, to_equiv' := foo.rfl } /- test whether eta expansions are reduced correctly -/ @[simps] def test {α} : automorphism_plus_data α := { P := λ f, f = id, data := rfl, extra := λ b, ⟨(⟨3, 5⟩ : my_prod _ _).1, (⟨3, 5⟩ : my_prod _ _).2⟩, ..foo.rfl } /- test whether this is indeed rejected as a valid eta expansion -/ @[simps] def test_sneaky {α} : automorphism_plus_data α := { P := λ f, f = id, data := rfl, extra := λ b, ⟨(3,5).1,(3,5).2⟩, ..foo.rfl } run_cmd do e ← get_env, e.get `refl_with_data_to_equiv', e.get `refl_with_data'_to_equiv', e.get `test_extra, e.get `test_sneaky_extra_fst, success_if_fail (e.get `refl_with_data_to_equiv_to_fun), success_if_fail (e.get `refl_with_data'_to_equiv_to_fun), success_if_fail (e.get `test_extra_fst), success_if_fail (e.get `test_sneaky_extra) structure partially_applied_str := (data : ℕ → my_prod ℕ ℕ) /- if we have a partially applied constructor, we treat it as if it were eta-expanded -/ @[simps] def partially_applied_term : partially_applied_str := ⟨my_prod.mk 3⟩ @[simps] def another_term : partially_applied_str := ⟨λ n, ⟨n + 1, n + 2⟩⟩ run_cmd do e ← get_env, e.get `partially_applied_term_data_fst, e.get `partially_applied_term_data_snd structure very_partially_applied_str := (data : ∀β, ℕ → β → my_prod ℕ β) /- if we have a partially applied constructor, we treat it as if it were eta-expanded. (this is not very useful, and we could remove this behavior if convenient) -/ @[simps] def very_partially_applied_term : very_partially_applied_str := ⟨@my_prod.mk ℕ⟩ run_cmd do e ← get_env, e.get `very_partially_applied_term_data_fst, e.get `very_partially_applied_term_data_snd @[simps] def let1 : ℕ × ℤ := let n := 3 in ⟨n + 4, 5⟩ @[simps] def let2 : ℕ × ℤ := let n := 3, m := 4 in let k := 5 in ⟨n + m, k⟩ @[simps] def let3 : ℕ → ℕ × ℤ := λ n, let m := 4, k := 5 in ⟨n + m, k⟩ @[simps] def let4 : ℕ → ℕ × ℤ := let m := 4, k := 5 in λ n, ⟨n + m, k⟩ run_cmd do e ← get_env, e.get `let1_fst, e.get `let2_fst, e.get `let3_fst, e.get `let4_fst, e.get `let1_snd, e.get `let2_snd, e.get `let3_snd, e.get `let4_snd namespace specify @[simps fst] def specify1 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd] def specify2 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd_fst] def specify3 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd snd_snd snd_snd] def specify4 : ℕ × ℕ × ℕ := (1, 2, 3) -- last argument is ignored @[simps] noncomputable def specify5 : ℕ × ℕ × ℕ := (1, classical.choice ⟨(2, 3)⟩) end specify run_cmd do e ← get_env, e.get `specify.specify1_fst, e.get `specify.specify2_snd, e.get `specify.specify3_snd_fst, e.get `specify.specify4_snd_snd, e.get `specify.specify4_snd, e.get `specify.specify5_fst, e.get `specify.specify5_snd, guard $ 12 = e.fold 0 -- there are no other lemmas generated (λ d n, n + if d.to_name.components.init.ilast = `specify then 1 else 0), success_if_fail_with_msg (simps_tac `specify.specify1 {} ["fst_fst"]) "Invalid simp lemma specify.specify1_fst_fst. Projection fst doesn't exist, because target is not a structure.", success_if_fail_with_msg (simps_tac `specify.specify1 {} ["foo_fst"]) "Invalid simp lemma specify.specify1_foo_fst. Structure prod does not have projection foo. The known projections are: [fst, snd] You can also see this information by running `initialize_simps_projections? prod`. Note: these projection names might not correspond to the projection names of the structure.", success_if_fail_with_msg (simps_tac `specify.specify1 {} ["snd_bar"]) "Invalid simp lemma specify.specify1_snd_bar. Structure prod does not have projection bar. The known projections are: [fst, snd] You can also see this information by running `initialize_simps_projections? prod`. Note: these projection names might not correspond to the projection names of the structure.", success_if_fail_with_msg (simps_tac `specify.specify5 {} ["snd_snd"]) "Invalid simp lemma specify.specify5_snd_snd. The given definition is not a constructor application: classical.choice specify.specify5._proof_1", p ← simps_aux.get_param `specify.specify4, guard $ p = [`specify.specify4_snd, `specify.specify4_snd_snd] /- We also eta-reduce if we explicitly specify the projection. -/ attribute [simps extra] test run_cmd do e ← get_env, d1 ← e.get `test_extra, d2 ← e.get `test_extra_2, guard $ d1.type =ₐ d2.type, skip /- check simp_rhs option -/ @[simps {simp_rhs := tt}] def equiv'.trans {α β γ} (f : α ≃ β) (g : β ≃ γ) : α ≃ γ := ⟨g.to_fun ∘ f.to_fun, f.inv_fun ∘ g.inv_fun, by { intro x, simp [equiv'.left_inv _ _] }, by { intro x, simp [equiv'.right_inv _ _] }⟩ example {α β γ : Type} (f : α ≃ β) (g : β ≃ γ) (x : α) : (f.trans g).to_fun x = (f.trans g).to_fun x := begin dsimp only [equiv'.trans_to_fun], guard_target g.to_fun (f.to_fun x) = g.to_fun (f.to_fun x), refl, end local attribute [simp] nat.zero_add nat.one_mul nat.mul_one @[simps {simp_rhs := tt}] def my_nat_equiv : ℕ ≃ ℕ := ⟨λ n, 0 + n, λ n, 1 * n * 1, by { intro n, simp }, by { intro n, simp }⟩ run_cmd success_if_fail (has_attribute `_refl_lemma `my_nat_equiv'_to_fun) >> has_attribute `_refl_lemma `equiv'.trans_to_fun example (n : ℕ) : my_nat_equiv.to_fun (my_nat_equiv.to_fun $ my_nat_equiv.inv_fun n) = n := by { success_if_fail { refl }, simp only [my_nat_equiv_to_fun, my_nat_equiv_inv_fun] } @[simps {simp_rhs := tt}] def succeed_without_simplification_possible : ℕ ≃ ℕ := ⟨λ n, n, λ n, n, by { intro n, refl }, by { intro n, refl }⟩ /- test that we don't recursively take projections of `prod` and `pprod` -/ @[simps] def pprod_equiv_prod : pprod ℕ ℕ ≃ ℕ × ℕ := { to_fun := λ x, ⟨x.1, x.2⟩, inv_fun := λ x, ⟨x.1, x.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } run_cmd do e ← get_env, e.get `pprod_equiv_prod_to_fun, e.get `pprod_equiv_prod_inv_fun attribute [simps to_fun_fst inv_fun_snd] pprod_equiv_prod run_cmd do e ← get_env, e.get `pprod_equiv_prod_to_fun_fst, e.get `pprod_equiv_prod_inv_fun_snd -- we can disable this behavior with the option `not_recursive`. @[simps {not_recursive := []}] def pprod_equiv_prod2 : pprod ℕ ℕ ≃ ℕ × ℕ := pprod_equiv_prod run_cmd do e ← get_env, e.get `pprod_equiv_prod2_to_fun_fst, e.get `pprod_equiv_prod2_to_fun_snd, e.get `pprod_equiv_prod2_inv_fun_fst, e.get `pprod_equiv_prod2_inv_fun_snd /- Tests with universe levels -/ class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg @[simps] instance types : category_struct (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } example (X : Type u) : (X ⟶ X) = (X → X) := by simp example (X : Type u) : 𝟙 X = (λ x, x) := by { funext, simp } example (X Y Z : Type u) (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := by { funext, simp } namespace coercing structure foo_str := (c : Type) (x : c) instance : has_coe_to_sort foo_str Type := ⟨foo_str.c⟩ @[simps] def foo : foo_str := ⟨ℕ, 3⟩ @[simps] def foo2 : foo_str := ⟨ℕ, 34⟩ example : ↥foo = ℕ := by simp only [foo_c] example : foo.x = (3 : ℕ) := by simp only [foo_x] structure voo_str (n : ℕ) := (c : Type) (x : c) instance has_coe_voo_str (n : ℕ) : has_coe_to_sort (voo_str n) Type := ⟨voo_str.c⟩ @[simps] def voo : voo_str 7 := ⟨ℕ, 3⟩ @[simps] def voo2 : voo_str 4 := ⟨ℕ, 34⟩ example : ↥voo = ℕ := by simp only [voo_c] example : voo.x = (3 : ℕ) := by simp only [voo_x] structure equiv2 (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) instance {α β} : has_coe_to_fun (equiv2 α β) (λ _, α → β) := ⟨equiv2.to_fun⟩ @[simps] protected def rfl2 {α} : equiv2 α α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩ example {α} (x : α) : coercing.rfl2 x = x := by rw [coercing.rfl2_to_fun] example {α} (x : α) : coercing.rfl2 x = x := by simp example {α} (x : α) : coercing.rfl2.inv_fun x = x := by simp @[simps] protected def equiv2.symm {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ @[simps] protected def equiv2.symm2 {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f.to_fun, f.right_inv, f.left_inv⟩ @[simps {fully_applied := ff}] protected def equiv2.symm3 {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ example {α β} (f : equiv2 α β) (y : β) : f.symm y = f.inv_fun y := by simp example {α β} (f : equiv2 α β) (x : α) : f.symm.inv_fun x = f x := by simp example {α β} (f : equiv2 α β) : f.symm.inv_fun = f := by { success_if_fail {simp}, refl } example {α β} (f : equiv2 α β) : f.symm3.inv_fun = f := by simp section set_option old_structure_cmd true class semigroup (G : Type u) extends has_mul G := (mul_assoc : ∀ a b c : G, a * b * c = a * (b * c)) end @[simps] instance {α β} [semigroup α] [semigroup β] : semigroup (α × β) := { mul := λ x y, (x.1 * y.1, x.2 * y.2), mul_assoc := by { intros, simp only [semigroup.mul_assoc], refl } } example {α β} [semigroup α] [semigroup β] (x y : α × β) : x * y = (x.1 * y.1, x.2 * y.2) := by simp example {α β} [semigroup α] [semigroup β] (x y : α × β) : (x * y).1 = x.1 * y.1 := by simp structure Semigroup := (G : Type*) (op : G → G → G) (infix (name := op) ` * ` := op) (op_assoc : ∀ (x y z : G), (x * y) * z = x * (y * z)) namespace Group instance : has_coe_to_sort Semigroup Type* := ⟨Semigroup.G⟩ -- We could try to generate lemmas with this `has_mul` instance, but it is unused in mathlib. -- Therefore, this is ignored. instance (G : Semigroup) : has_mul G := ⟨G.op⟩ @[simps] def prod_Semigroup (G H : Semigroup) : Semigroup := { G := G × H, op := λ x y, (x.1 * y.1, x.2 * y.2), op_assoc := by { intros, dsimp [Group.has_mul], simp [Semigroup.op_assoc] }} end Group section set_option old_structure_cmd true class extending_stuff (G : Type u) extends has_mul G, has_zero G, has_neg G, has_subset G := (new_axiom : ∀ x : G, x * - 0 ⊆ - x) end @[simps] def bar : extending_stuff ℕ := { mul := (*), zero := 0, neg := nat.succ, subset := λ x y, true, new_axiom := λ x, trivial } section local attribute [instance] bar example (x : ℕ) : x * - 0 ⊆ - x := by simp end class new_extending_stuff (G : Type u) extends has_mul G, has_zero G, has_neg G, has_subset G := (new_axiom : ∀ x : G, x * - 0 ⊆ - x) @[simps] def new_bar : new_extending_stuff ℕ := { mul := (*), zero := 0, neg := nat.succ, subset := λ x y, true, new_axiom := λ x, trivial } section local attribute [instance] new_bar example (x : ℕ) : x * - 0 ⊆ - x := by simp end end coercing namespace manual_coercion structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_coercion.equiv variables {α β γ : Sort*} instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : γ) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := by simp only [equiv.trans_inv_fun] end manual_coercion namespace faulty_manual_coercion structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := faulty_manual_coercion.equiv variables {α β γ : Sort*} /-- See Note [custom simps projection] -/ noncomputable def equiv.simps.inv_fun (e : α ≃ β) : β → α := classical.choice ⟨e.inv_fun⟩ run_cmd do e ← get_env, success_if_fail_with_msg (simps_get_raw_projections e `faulty_manual_coercion.equiv) "Invalid custom projection: λ {α : Sort u_1} {β : Sort u_2} (e : α ≃ β), classical.choice _ Expression is not definitionally equal to λ (α : Sort u_1) (β : Sort u_2) (x : α ≃ β), x.inv_fun" end faulty_manual_coercion namespace manual_initialize /- defining a manual coercion. -/ variables {α β γ : Sort*} structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_initialize.equiv instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different unvierse levels for equiv.symm than for equiv def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv run_cmd has_attribute `_simps_str `manual_initialize.equiv /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ end manual_initialize namespace faulty_universes variables {α β γ : Sort*} structure equiv (α : Sort u) (β : Sort v) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := faulty_universes.equiv instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different names for the universe variables for equiv.symm than for -- equiv def equiv.simps.inv_fun {α : Type u} {β : Type v} (e : α ≃ β) : β → α := e.symm run_cmd do e ← get_env, success_if_fail_with_msg (simps_get_raw_projections e `faulty_universes.equiv) "Invalid custom projection: λ {α : Type u} {β : Type v} (e : α ≃ β), ⇑(e.symm) Expression has different type than faulty_universes.equiv.inv_fun. Given type: Π {α : Type u} {β : Type v} (e : α ≃ β), (λ (_x : β ≃ α), β → α) e.symm Expected type: Π (α : Sort u) (β : Sort v), α ≃ β → β → α" end faulty_universes namespace manual_universes variables {α β γ : Sort*} structure equiv (α : Sort u) (β : Sort v) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_universes.equiv instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different unvierse levels for equiv.symm than for equiv def equiv.simps.inv_fun {α : Sort w} {β : Sort u} (e : α ≃ β) : β → α := e.symm -- check whether we can generate custom projections even if the universe names don't match initialize_simps_projections equiv end manual_universes namespace manual_projection_names structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_projection_names.equiv variables {α β γ : Sort*} instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) run_cmd do e ← get_env, data ← simps_get_raw_projections e `manual_projection_names.equiv, guard $ data.2.map projection_data.name = [`apply, `symm_apply] @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : α) : (e₁.trans e₂) x = e₂ (e₁ x) := by simp only [equiv.trans_apply] example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : γ) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := by simp only [equiv.trans_symm_apply] -- the new projection names are parsed correctly (the old projection names won't work anymore) @[simps apply symm_apply] protected def equiv.trans2 (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ end manual_projection_names namespace prefix_projection_names structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := prefix_projection_names.equiv variables {α β γ : Sort*} instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → coe as_prefix, inv_fun → symm_apply) run_cmd do e ← get_env, data ← simps_get_raw_projections e `prefix_projection_names.equiv, guard $ data.2.map projection_data.name = [`coe, `symm_apply], guard $ data.2.map projection_data.is_prefix = [tt, ff] @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : α) : (e₁.trans e₂) x = e₂ (e₁ x) := by simp only [equiv.coe_trans] -- the new projection names are parsed correctly @[simps coe symm_apply] protected def equiv.trans2 (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ -- it interacts somewhat well with multiple projections (though the generated name is not great) @[simps snd_coe_fst] def foo {α β γ δ : Type*} (x : α) (e₁ : α ≃ β) (e₂ : γ ≃ δ) : α × (α × γ ≃ β × δ) := ⟨x, prod.map e₁ e₂, prod.map e₁.symm e₂.symm⟩ example {α β γ δ : Type*} (x : α) (e₁ : α ≃ β) (e₂ : γ ≃ δ) (z : α × γ) : ((foo x e₁ e₂).2 z).1 = e₁ z.1 := by simp only [coe_foo_snd_fst] end prefix_projection_names -- test transparency setting structure set_plus (α : Type) := (s : set α) (x : α) (h : x ∈ s) @[simps] def nat_set_plus : set_plus ℕ := ⟨set.univ, 1, trivial⟩ example : nat_set_plus.s = set.univ := begin dsimp only [nat_set_plus_s], guard_target @set.univ ℕ = set.univ, refl end @[simps {type_md := semireducible}] def nat_set_plus2 : set_plus ℕ := ⟨set.univ, 1, trivial⟩ example : nat_set_plus2.s = set.univ := begin success_if_fail { dsimp only [nat_set_plus2_s] }, refl end @[simps {rhs_md := semireducible}] def nat_set_plus3 : set_plus ℕ := nat_set_plus example : nat_set_plus3.s = set.univ := begin dsimp only [nat_set_plus3_s], guard_target @set.univ ℕ = set.univ, refl end namespace nested_non_fully_applied structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := nested_non_fully_applied.equiv variables {α β γ : Sort*} @[simps] def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ @[simps {rhs_md := semireducible, fully_applied := ff}] def equiv.symm2 : (α ≃ β) ≃ (β ≃ α) := ⟨equiv.symm, equiv.symm⟩ example (e : α ≃ β) : (equiv.symm2.inv_fun e).to_fun = e.inv_fun := begin dsimp only [equiv.symm2_inv_fun_to_fun], guard_target e.inv_fun = e.inv_fun, refl end /- do not prematurely unfold `equiv.symm`, unless necessary -/ @[simps to_fun to_fun_to_fun {rhs_md := semireducible}] def equiv.symm3 : (α ≃ β) ≃ (β ≃ α) := equiv.symm2 example (e : α ≃ β) (y : β) : (equiv.symm3.to_fun e).to_fun y = e.inv_fun y ∧ (equiv.symm3.to_fun e).to_fun y = e.inv_fun y := begin split, { dsimp only [equiv.symm3_to_fun], guard_target e.symm.to_fun y = e.inv_fun y, refl }, { dsimp only [equiv.symm3_to_fun_to_fun], guard_target e.inv_fun y = e.inv_fun y, refl } end end nested_non_fully_applied -- test that type classes which are props work class prop_class (n : ℕ) : Prop := (has_true : true) instance has_prop_class (n : ℕ) : prop_class n := ⟨trivial⟩ structure needs_prop_class (n : ℕ) [prop_class n] := (t : true) @[simps] def test_prop_class : needs_prop_class 1 := { t := trivial } /- check that when the coercion is given in eta-expanded form, we can also find the coercion. -/ structure alg_hom (R A B : Type*) := (to_fun : A → B) instance (R A B : Type*) : has_coe_to_fun (alg_hom R A B) (λ _, A → B) := ⟨λ f, f.to_fun⟩ @[simps] def my_alg_hom : alg_hom unit bool bool := { to_fun := id } example (x : bool) : my_alg_hom x = id x := by simp only [my_alg_hom_to_fun] structure ring_hom (A B : Type*) := (to_fun : A → B) instance (A B : Type*) : has_coe_to_fun (ring_hom A B) (λ _, A → B) := ⟨λ f, f.to_fun⟩ @[simps] def my_ring_hom : ring_hom bool bool := { to_fun := id } example (x : bool) : my_ring_hom x = id x := by simp only [my_ring_hom_to_fun] /- check interaction with the `@[to_additive]` attribute -/ @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ run_cmd do get_decl `prod.has_mul_mul, get_decl `prod.has_add_add, has_attribute `to_additive `prod.has_mul, has_attribute `to_additive `prod.has_mul_mul, has_attribute `simp `prod.has_mul_mul, has_attribute `simp `prod.has_add_add example {M N} [has_mul M] [has_mul N] (p q : M × N) : p * q = ⟨p.1 * q.1, p.2 * q.2⟩ := by simp example {M N} [has_add M] [has_add N] (p q : M × N) : p + q = ⟨p.1 + q.1, p.2 + q.2⟩ := by simp /- The names of the generated simp lemmas for the additive version are not great if the definition had a custom additive name -/ @[to_additive my_add_instance, simps] instance my_instance {M N} [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ run_cmd do get_decl `my_instance_one, get_decl `my_add_instance_zero, has_attribute `to_additive `my_instance, has_attribute `to_additive `my_instance_one, has_attribute `simp `my_instance_one, has_attribute `simp `my_add_instance_zero example {M N} [has_one M] [has_one N] : (1 : M × N) = ⟨1, 1⟩ := by simp example {M N} [has_zero M] [has_zero N] : (0 : M × N) = ⟨0, 0⟩ := by simp section /-! Test `dsimp, simp` with the option `simp_rhs` -/ local attribute [simp] nat.add structure my_type := (A : Type) @[simps {simp_rhs := tt}] def my_type_def : my_type := ⟨{ x : fin (nat.add 3 0) // 1 + 1 = 2 }⟩ example (h : false) (x y : { x : fin (nat.add 3 0) // 1 + 1 = 2 }) : my_type_def.A = unit := begin simp only [my_type_def_A], guard_target ({ x : fin 3 // true } = unit), /- note: calling only one of `simp` or `dsimp` does not produce the current target, as the following tests show. -/ success_if_fail { guard_hyp x : { x : fin 3 // true } }, dsimp at x, success_if_fail { guard_hyp x : { x : fin 3 // true } }, simp at y, success_if_fail { guard_hyp y : { x : fin 3 // true } }, simp at x, dsimp at y, guard_hyp x : { x : fin 3 // true }, guard_hyp y : { x : fin 3 // true }, contradiction end /- Test that `to_additive` copies the `@[_refl_lemma]` attribute correctly -/ @[to_additive, simps] def monoid_hom.my_comp {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, } -- `simps` adds the `_refl_lemma` attribute to `monoid_hom.my_comp_apply` example {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) (m : M) : hnp.my_comp hmn m = hnp (hmn m) := by { dsimp, guard_target (hnp (hmn m) = hnp (hmn m)), refl } -- `to_additive` adds the `_refl_lemma` attribute to `add_monoid_hom.my_comp_apply` example {M N P : Type*} [add_zero_class M] [add_zero_class N] [add_zero_class P] (hnp : N →+ P) (hmn : M →+ N) (m : M) : hnp.my_comp hmn m = hnp (hmn m) := by { dsimp, guard_target (hnp (hmn m) = hnp (hmn m)), refl } -- test that `to_additive` works with a custom name @[to_additive some_test2, simps] def some_test1 (M : Type*) [comm_monoid M] : subtype (λ f : M, true) := ⟨1, trivial⟩ run_cmd get_decl `some_test2_coe end /- Test custom compositions of projections. -/ section comp_projs instance {α β} : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv'.to_fun⟩ @[simps] protected def equiv'.symm {α β} (f : α ≃ β) : β ≃ α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ structure decorated_equiv (α : Sort*) (β : Sort*) extends equiv' α β := (P_to_fun : function.injective to_fun ) (P_inv_fun : function.injective inv_fun) instance {α β} : has_coe_to_fun (decorated_equiv α β) (λ _, α → β) := ⟨λ f, f.to_equiv'⟩ def decorated_equiv.symm {α β : Sort*} (e : decorated_equiv α β) : decorated_equiv β α := { to_equiv' := e.to_equiv'.symm, P_to_fun := e.P_inv_fun, P_inv_fun := e.P_to_fun } def decorated_equiv.simps.apply {α β : Sort*} (e : decorated_equiv α β) : α → β := e def decorated_equiv.simps.symm_apply {α β : Sort*} (e : decorated_equiv α β) : β → α := e.symm initialize_simps_projections decorated_equiv (to_equiv'_to_fun → apply, to_equiv'_inv_fun → symm_apply, -to_equiv') @[simps] def foo (α : Type) : decorated_equiv α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h } example {α : Type} (x : α) : (foo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps to_equiv' apply symm_apply] def foo2 (α : Type) : decorated_equiv α α := { P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, ..foo.rfl } example {α : Type} (x : α) : (foo2 α).to_equiv' x = x := by { dsimp, guard_target (foo.rfl x = x), refl } example {α : Type} (x : α) : foo2 α x = x := by { dsimp, guard_target (x = x), refl } structure further_decorated_equiv (α : Sort*) (β : Sort*) extends decorated_equiv α β := (Q_to_fun : function.surjective to_fun ) (Q_inv_fun : function.surjective inv_fun ) instance {α β} : has_coe_to_fun (further_decorated_equiv α β) (λ _, α → β) := ⟨λ f, f.to_decorated_equiv⟩ def further_decorated_equiv.symm {α β : Sort*} (e : further_decorated_equiv α β) : further_decorated_equiv β α := { to_decorated_equiv := e.to_decorated_equiv.symm, Q_to_fun := e.Q_inv_fun, Q_inv_fun := e.Q_to_fun } def further_decorated_equiv.simps.apply {α β : Sort*} (e : further_decorated_equiv α β) : α → β := e def further_decorated_equiv.simps.symm_apply {α β : Sort*} (e : further_decorated_equiv α β) : β → α := e.symm initialize_simps_projections further_decorated_equiv (to_decorated_equiv_to_equiv'_to_fun → apply, to_decorated_equiv_to_equiv'_inv_fun → symm_apply, -to_decorated_equiv, to_decorated_equiv_to_equiv' → to_equiv', -to_equiv') @[simps] def ffoo (α : Type) : further_decorated_equiv α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩ } example {α : Type} (x : α) : (ffoo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps] def ffoo3 (α : Type) : further_decorated_equiv α α := { Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩, .. foo α } @[simps apply to_equiv'_to_fun to_decorated_equiv_apply] def ffoo4 (α : Type) : further_decorated_equiv α α := { Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩, to_decorated_equiv := foo α } structure one_more (α : Sort*) (β : Sort*) extends further_decorated_equiv α β instance {α β} : has_coe_to_fun (one_more α β) (λ _, α → β) := ⟨λ f, f.to_further_decorated_equiv⟩ def one_more.symm {α β : Sort*} (e : one_more α β) : one_more β α := { to_further_decorated_equiv := e.to_further_decorated_equiv.symm } def one_more.simps.apply {α β : Sort*} (e : one_more α β) : α → β := e def one_more.simps.symm_apply {α β : Sort*} (e : one_more α β) : β → α := e.symm initialize_simps_projections one_more (to_further_decorated_equiv_to_decorated_equiv_to_equiv'_to_fun → apply, to_further_decorated_equiv_to_decorated_equiv_to_equiv'_inv_fun → symm_apply, -to_further_decorated_equiv, to_further_decorated_equiv_to_decorated_equiv → to_dequiv, -to_dequiv) @[simps] def fffoo (α : Type) : one_more α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩ } example {α : Type} (x : α) : (fffoo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps apply to_dequiv_apply to_further_decorated_equiv_apply to_dequiv] def fffoo2 (α : Type) : one_more α α := fffoo α /- test the case where a projection takes additional arguments. -/ variables {ι : Type*} [decidable_eq ι] (A : ι → Type*) class something [has_add ι] [Π i, add_comm_monoid (A i)] := (mul {i} : A i →+ A i) def something.simps.apply [has_add ι] [Π i, add_comm_monoid (A i)] [something A] {i : ι} (x : A i) : A i := something.mul ι x initialize_simps_projections something (mul_to_fun → apply, -mul) class something2 [has_add ι] := (mul {i j} : A i ≃ (A j ≃ A (i + j))) def something2.simps.mul [has_add ι] [something2 A] {i j : ι} (x : A i) (y : A j) : A (i + j) := something2.mul x y initialize_simps_projections something2 (mul → mul', mul_to_fun_to_fun → mul, -mul') attribute [ext] equiv' @[simps] def thing (h : bool ≃ (bool ≃ bool)) : something2 (λ x : ℕ, bool) := { mul := λ i j, { to_fun := λ b, { to_fun := h b, inv_fun := (h b).symm, left_inv := (h b).left_inv, right_inv := (h b).right_inv }, inv_fun := h.symm, left_inv := by { convert h.left_inv, ext x; refl }, right_inv := by { convert h.right_inv, ext x; refl } } } example (h : bool ≃ (bool ≃ bool)) (i j : ℕ) (b1 b2 : bool) : @something2.mul _ _ _ _ (thing h) i j b1 b2 = h b1 b2 := by simp only [thing_mul] end comp_projs section /-! Check that the tactic also works if the elaborated type of `type` reduces to `Sort*`, but is not `Sort*` itself. -/ structure my_functor (C D : Type*) := (obj [] : C → D) local infixr ` ⥤ `:26 := my_functor @[simps] def foo_sum {I J : Type*} (C : I → Type*) {D : J → Type*} : (Π i, C i) ⥤ (Π j, D j) ⥤ (Π s : I ⊕ J, sum.elim C D s) := { obj := λ f, { obj := λ g s, sum.rec f g s }} end
d59f615fa26fc35b77b83c004d21db355a831ddd
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/interactive/goal_info_rw.lean
f6b0afc9efd92e48b83c11210bf02fef4f2dc42e
[ "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
253
lean
example (p q r : Prop) (h₁ : p = q) (h₂ : q = r) : p = r := by rw [h₁, --^ "command": "info" ←h₂, --^ "command": "info" ←h₁ --^ "command": "info" --^ "command": "info" ] --^ "command": "info"
838f77fedd3d96712c819d2f08eed55429abe084
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/charpoly/basic.lean
630f07ee362112c747b09eb588e05b8714256df0
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,650
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.free_module.finite.basic import linear_algebra.matrix.charpoly.coeff import field_theory.minpoly /-! # Characteristic polynomial We define the characteristic polynomial of `f : M →ₗ[R] M`, where `M` is a finite and free `R`-module. The proof that `f.charpoly` is the characteristic polynomial of the matrix of `f` in any basis is in `linear_algebra/charpoly/to_matrix`. ## Main definition * `linear_map.charpoly f` : the characteristic polynomial of `f : M →ₗ[R] M`. -/ universes u v w variables {R : Type u} {M : Type v} [comm_ring R] [nontrivial R] variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M] (f : M →ₗ[R] M) open_locale classical matrix polynomial noncomputable theory open module.free polynomial matrix namespace linear_map section basic /-- The characteristic polynomial of `f : M →ₗ[R] M`. -/ def charpoly : R[X] := (to_matrix (choose_basis R M) (choose_basis R M) f).charpoly lemma charpoly_def : f.charpoly = (to_matrix (choose_basis R M) (choose_basis R M) f).charpoly := rfl end basic section coeff lemma charpoly_monic : f.charpoly.monic := charpoly_monic _ end coeff section cayley_hamilton /-- The **Cayley-Hamilton Theorem**, that the characteristic polynomial of a linear map, applied to the linear map itself, is zero. See `matrix.aeval_self_charpoly` for the equivalent statement about matrices. -/ lemma aeval_self_charpoly : aeval f f.charpoly = 0 := begin apply (linear_equiv.map_eq_zero_iff (alg_equiv_matrix _).to_linear_equiv).1, rw [alg_equiv.to_linear_equiv_apply, ← alg_equiv.coe_alg_hom, ← polynomial.aeval_alg_hom_apply _ _ _, charpoly_def], exact aeval_self_charpoly _, end lemma is_integral : is_integral R f := ⟨f.charpoly, ⟨charpoly_monic f, aeval_self_charpoly f⟩⟩ lemma minpoly_dvd_charpoly {K : Type u} {M : Type v} [field K] [add_comm_group M] [module K M] [finite_dimensional K M] (f : M →ₗ[K] M) : minpoly K f ∣ f.charpoly := minpoly.dvd _ _ (aeval_self_charpoly f) /-- Any endomorphism polynomial `p` is equivalent under evaluation to `p %ₘ f.charpoly`; that is, `p` is equivalent to a polynomial with degree less than the dimension of the module. -/ lemma aeval_eq_aeval_mod_charpoly (p : R[X]) : aeval f p = aeval f (p %ₘ f.charpoly) := (aeval_mod_by_monic_eq_self_of_root f.charpoly_monic f.aeval_self_charpoly).symm /-- Any endomorphism power can be computed as the sum of endomorphism powers less than the dimension of the module. -/ lemma pow_eq_aeval_mod_charpoly (k : ℕ) : f^k = aeval f (X^k %ₘ f.charpoly) := by rw [←aeval_eq_aeval_mod_charpoly, map_pow, aeval_X] variable {f} lemma minpoly_coeff_zero_of_injective (hf : function.injective f) : (minpoly R f).coeff 0 ≠ 0 := begin intro h, obtain ⟨P, hP⟩ := X_dvd_iff.2 h, have hdegP : P.degree < (minpoly R f).degree, { rw [hP, mul_comm], refine degree_lt_degree_mul_X (λ h, _), rw [h, mul_zero] at hP, exact minpoly.ne_zero (is_integral f) hP }, have hPmonic : P.monic, { suffices : (minpoly R f).monic, { rwa [monic.def, hP, mul_comm, leading_coeff_mul_X, ← monic.def] at this }, exact minpoly.monic (is_integral f) }, have hzero : aeval f (minpoly R f) = 0 := minpoly.aeval _ _, simp only [hP, mul_eq_comp, ext_iff, hf, aeval_X, map_eq_zero_iff, coe_comp, alg_hom.map_mul, zero_apply] at hzero, exact not_le.2 hdegP (minpoly.min _ _ hPmonic (ext hzero)), end end cayley_hamilton end linear_map
efa6f60d9b21b929b0818b296108166cc6002109
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/subsemigroup/center.lean
99208d255088d8740c3e59de32bdfd31a6655d65
[ "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
4,968
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Jireh Loreaux -/ import group_theory.subsemigroup.operations import data.fintype.basic /-! # Centers of magmas and semigroups ## Main definitions * `set.center`: the center of a magma * `subsemigroup.center`: the center of a semigroup * `set.add_center`: the center of an additive magma * `add_subsemigroup.center`: the center of an additive semigroup We provide `submonoid.center`, `add_submonoid.center`, `subgroup.center`, `add_subgroup.center`, `subsemiring.center`, and `subring.center` in other files. -/ variables {M : Type*} namespace set variables (M) /-- The center of a magma. -/ @[to_additive add_center /-" The center of an additive magma. "-/] def center [has_mul M] : set M := {z | ∀ m, m * z = z * m} @[to_additive mem_add_center] lemma mem_center_iff [has_mul M] {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center [has_mul M] [decidable_eq M] [fintype M] : decidable_pred (∈ center M) := λ _, decidable_of_iff' _ (mem_center_iff M) @[simp, to_additive zero_mem_add_center] lemma one_mem_center [mul_one_class M] : (1 : M) ∈ set.center M := by simp [mem_center_iff] @[simp] lemma zero_mem_center [mul_zero_class M] : (0 : M) ∈ set.center M := by simp [mem_center_iff] variables {M} @[simp, to_additive add_mem_add_center] lemma mul_mem_center [semigroup M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a * b ∈ set.center M := λ g, by rw [mul_assoc, ←hb g, ← mul_assoc, ha g, mul_assoc] @[simp, to_additive neg_mem_add_center] lemma inv_mem_center [group M] {a : M} (ha : a ∈ set.center M) : a⁻¹ ∈ set.center M := λ g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] @[simp] lemma add_mem_center [distrib M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a + b ∈ set.center M := λ c, by rw [add_mul, mul_add, ha c, hb c] @[simp] lemma neg_mem_center [ring M] {a : M} (ha : a ∈ set.center M) : -a ∈ set.center M := λ c, by rw [←neg_mul_comm, ha (-c), neg_mul_comm] @[to_additive subset_add_center_add_units] lemma subset_center_units [monoid M] : (coe : Mˣ → M) ⁻¹' center M ⊆ set.center Mˣ := λ a ha b, units.ext $ ha _ lemma center_units_subset [group_with_zero M] : set.center Mˣ ⊆ (coe : Mˣ → M) ⁻¹' center M := λ a ha b, begin obtain rfl | hb := eq_or_ne b 0, { rw [zero_mul, mul_zero], }, { exact units.ext_iff.mp (ha (units.mk0 _ hb)) } end /-- In a group with zero, the center of the units is the preimage of the center. -/ lemma center_units_eq [group_with_zero M] : set.center Mˣ = (coe : Mˣ → M) ⁻¹' center M := subset.antisymm center_units_subset subset_center_units @[simp] lemma inv_mem_center₀ [group_with_zero M] {a : M} (ha : a ∈ set.center M) : a⁻¹ ∈ set.center M := begin obtain rfl | ha0 := eq_or_ne a 0, { rw inv_zero, exact zero_mem_center M }, rcases is_unit.mk0 _ ha0 with ⟨a, rfl⟩, rw ←units.coe_inv, exact center_units_subset (inv_mem_center (subset_center_units ha)), end @[simp, to_additive sub_mem_add_center] lemma div_mem_center [group M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a / b ∈ set.center M := begin rw [div_eq_mul_inv], exact mul_mem_center ha (inv_mem_center hb), end @[simp] lemma div_mem_center₀ [group_with_zero M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a / b ∈ set.center M := begin rw div_eq_mul_inv, exact mul_mem_center ha (inv_mem_center₀ hb), end variables (M) @[simp, to_additive add_center_eq_univ] lemma center_eq_univ [comm_semigroup M] : center M = set.univ := subset.antisymm (subset_univ _) $ λ x _ y, mul_comm y x end set namespace subsemigroup section variables (M) [semigroup M] /-- The center of a semigroup `M` is the set of elements that commute with everything in `M` -/ @[to_additive "The center of a semigroup `M` is the set of elements that commute with everything in `M`"] def center : subsemigroup M := { carrier := set.center M, mul_mem' := λ a b, set.mul_mem_center } @[to_additive] lemma coe_center : ↑(center M) = set.center M := rfl variables {M} @[to_additive] lemma mem_center_iff {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := iff.rfl @[to_additive] instance decidable_mem_center [decidable_eq M] [fintype M] : decidable_pred (∈ center M) := λ _, decidable_of_iff' _ mem_center_iff /-- The center of a semigroup is commutative. -/ @[to_additive "The center of an additive semigroup is commutative."] instance : comm_semigroup (center M) := { mul_comm := λ a b, subtype.ext $ b.prop _, .. mul_mem_class.to_semigroup (center M) } end section variables (M) [comm_semigroup M] @[to_additive, simp] lemma center_eq_top : center M = ⊤ := set_like.coe_injective (set.center_eq_univ M) end end subsemigroup
217c351666973e3506ad8404ab59f627627c21d8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/abelian/right_derived.lean
4797700212e96993415407836075e6be9f0a6eb1
[ "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
13,901
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Scott Morrison -/ import category_theory.abelian.injective_resolution import algebra.homology.additive import category_theory.limits.constructions.epi_mono import category_theory.abelian.homology import category_theory.abelian.exact /-! # Right-derived functors We define the right-derived functors `F.right_derived n : C ⥤ D` for any additive functor `F` out of a category with injective resolutions. The definition is ``` injective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n ``` that is, we pick an injective resolution (thought of as an object of the homotopy category), we apply `F` objectwise, and compute `n`-th homology. We show that these right-derived functors can be calculated on objects using any choice of injective resolution, and on morphisms by any choice of lift to a cochain map between chosen injective resolutions. Similarly we define natural transformations between right-derived functors coming from natural transformations between the original additive functors, and show how to compute the components. ## Main results * `category_theory.functor.right_derived_obj_injective_zero`: the `0`-th derived functor of `F` on an injective object `X` is isomorphic to `F.obj X`. * `category_theory.functor.right_derived_obj_injective_succ`: injective objects have no higher right derived functor. * `category_theory.nat_trans.right_derived`: the natural isomorphism between right derived functors induced by natural transformation. Now, we assume `preserves_finite_limits F`, then * `category_theory.abelian.functor.preserves_exact_of_preserves_finite_limits_of_mono`: if `f` is mono and `exact f g`, then `exact (F.map f) (F.map g)`. * `category_theory.abelian.functor.right_derived_zero_iso_self`: if there are enough injectives, then there is a natural isomorphism `(F.right_derived 0) ≅ F`. -/ noncomputable theory open category_theory open category_theory.limits namespace category_theory universes v u variables {C : Type u} [category.{v} C] {D : Type*} [category D] variables [abelian C] [has_injective_resolutions C] [abelian D] /-- The right derived functors of an additive functor. -/ def functor.right_derived (F : C ⥤ D) [F.additive] (n : ℕ) : C ⥤ D := injective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n /-- We can compute a right derived functor using a chosen injective resolution. -/ @[simps] def functor.right_derived_obj_iso (F : C ⥤ D) [F.additive] (n : ℕ) {X : C} (P : InjectiveResolution X) : (F.right_derived n).obj X ≅ (homology_functor D _ n).obj ((F.map_homological_complex _).obj P.cocomplex) := (homotopy_category.homology_functor D _ n).map_iso (homotopy_category.iso_of_homotopy_equiv (F.map_homotopy_equiv (InjectiveResolution.homotopy_equiv _ P))) ≪≫ (homotopy_category.homology_factors D _ n).app _ /-- The 0-th derived functor of `F` on an injective object `X` is just `F.obj X`. -/ @[simps] def functor.right_derived_obj_injective_zero (F : C ⥤ D) [F.additive] (X : C) [injective X] : (F.right_derived 0).obj X ≅ F.obj X := F.right_derived_obj_iso 0 (InjectiveResolution.self X) ≪≫ (homology_functor _ _ _).map_iso ((cochain_complex.single₀_map_homological_complex F).app X) ≪≫ (cochain_complex.homology_functor_0_single₀ D).app (F.obj X) open_locale zero_object /-- The higher derived functors vanish on injective objects. -/ @[simps inv] def functor.right_derived_obj_injective_succ (F : C ⥤ D) [F.additive] (n : ℕ) (X : C) [injective X] : (F.right_derived (n+1)).obj X ≅ 0 := F.right_derived_obj_iso (n+1) (InjectiveResolution.self X) ≪≫ (homology_functor _ _ _).map_iso ((cochain_complex.single₀_map_homological_complex F).app X) ≪≫ (cochain_complex.homology_functor_succ_single₀ D n).app (F.obj X) ≪≫ (functor.zero_obj _).iso_zero /-- We can compute a right derived functor on a morphism using a descent of that morphism to a cochain map between chosen injective resolutions. -/ lemma functor.right_derived_map_eq (F : C ⥤ D) [F.additive] (n : ℕ) {X Y : C} (f : Y ⟶ X) {P : InjectiveResolution X} {Q : InjectiveResolution Y} (g : Q.cocomplex ⟶ P.cocomplex) (w : Q.ι ≫ g = (cochain_complex.single₀ C).map f ≫ P.ι) : (F.right_derived n).map f = (F.right_derived_obj_iso n Q).hom ≫ (homology_functor D _ n).map ((F.map_homological_complex _).map g) ≫ (F.right_derived_obj_iso n P).inv := begin dsimp only [functor.right_derived, functor.right_derived_obj_iso], dsimp, simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, apply functor.map_homotopy, apply homotopy.trans, exact homotopy_category.homotopy_out_map _, apply InjectiveResolution.desc_homotopy f, { simp, }, { simp only [InjectiveResolution.homotopy_equiv_hom_ι_assoc], rw [←category.assoc, w, category.assoc], simp only [InjectiveResolution.homotopy_equiv_inv_ι], }, end /-- The natural transformation between right-derived functors induced by a natural transformation.-/ @[simps] def nat_trans.right_derived {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ) : F.right_derived n ⟶ G.right_derived n := whisker_left (injective_resolutions C) (whisker_right (nat_trans.map_homotopy_category α _) (homotopy_category.homology_functor D _ n)) @[simp] lemma nat_trans.right_derived_id (F : C ⥤ D) [F.additive] (n : ℕ) : nat_trans.right_derived (𝟙 F) n = 𝟙 (F.right_derived n) := by { simp [nat_trans.right_derived], refl, } @[simp, nolint simp_nf] lemma nat_trans.right_derived_comp {F G H : C ⥤ D} [F.additive] [G.additive] [H.additive] (α : F ⟶ G) (β : G ⟶ H) (n : ℕ) : nat_trans.right_derived (α ≫ β) n = nat_trans.right_derived α n ≫ nat_trans.right_derived β n := by simp [nat_trans.right_derived] /-- A component of the natural transformation between right-derived functors can be computed using a chosen injective resolution. -/ lemma nat_trans.right_derived_eq {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ) {X : C} (P : InjectiveResolution X) : (nat_trans.right_derived α n).app X = (F.right_derived_obj_iso n P).hom ≫ (homology_functor D _ n).map ((nat_trans.map_homological_complex α _).app P.cocomplex) ≫ (G.right_derived_obj_iso n P).inv := begin symmetry, dsimp [nat_trans.right_derived, functor.right_derived_obj_iso], simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, simp only [nat_trans.map_homological_complex_naturality_assoc, ←functor.map_comp], apply homotopy.comp_left_id, rw [←functor.map_id], apply functor.map_homotopy, apply homotopy_equiv.homotopy_hom_inv_id, end end category_theory section universes w v u open category_theory.limits category_theory category_theory.functor variables {C : Type u} [category.{w} C] {D : Type u} [category.{w} D] variables (F : C ⥤ D) {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} namespace category_theory.abelian.functor open category_theory.preadditive variables [abelian C] [abelian D] [additive F] /-- If `preserves_finite_limits F` and `mono f`, then `exact (F.map f) (F.map g)` if `exact f g`. -/ lemma preserves_exact_of_preserves_finite_limits_of_mono [preserves_finite_limits F] [mono f] (ex : exact f g) : exact (F.map f) (F.map g) := abelian.exact_of_is_kernel _ _ (by simp [← functor.map_comp, ex.w]) $ limits.is_limit_fork_map_of_is_limit' _ ex.w (abelian.is_limit_of_exact_of_mono _ _ ex) lemma exact_of_map_injective_resolution (P: InjectiveResolution X) [preserves_finite_limits F] : exact (F.map (P.ι.f 0)) (((F.map_homological_complex (complex_shape.up ℕ)).obj P.cocomplex).d_from 0) := preadditive.exact_of_iso_of_exact' (F.map (P.ι.f 0)) (F.map (P.cocomplex.d 0 1)) _ _ (iso.refl _) (iso.refl _) (homological_complex.X_next_iso ((F.map_homological_complex _).obj P.cocomplex) rfl).symm (by simp) (by rw [iso.refl_hom, category.id_comp, iso.symm_hom, homological_complex.d_from_eq]; congr') (preserves_exact_of_preserves_finite_limits_of_mono _ (P.exact₀)) /-- Given `P : InjectiveResolution X`, a morphism `(F.right_derived 0).obj X ⟶ F.obj X` given `preserves_finite_limits F`. -/ def right_derived_zero_to_self_app [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : (F.right_derived 0).obj X ⟶ F.obj X := (right_derived_obj_iso F 0 P).hom ≫ (homology_iso_kernel_desc _ _ _).hom ≫ kernel.map _ _ (cokernel.desc _ (𝟙 _) (by simp)) (𝟙 _) (by { ext, simp }) ≫ (as_iso (kernel.lift _ _ (exact_of_map_injective_resolution F P).w)).inv /-- Given `P : InjectiveResolution X`, a morphism `F.obj X ⟶ (F.right_derived 0).obj X`. -/ def right_derived_zero_to_self_app_inv [enough_injectives C] {X : C} (P : InjectiveResolution X) : F.obj X ⟶ (F.right_derived 0).obj X := homology.lift _ _ _ (F.map (P.ι.f 0) ≫ cokernel.π _) begin have : (complex_shape.up ℕ).rel 0 1 := rfl, rw [category.assoc, cokernel.π_desc, homological_complex.d_from_eq _ this, map_homological_complex_obj_d, ← category.assoc, ← functor.map_comp], simp only [InjectiveResolution.ι_f_zero_comp_complex_d, functor.map_zero, zero_comp], end ≫ (right_derived_obj_iso F 0 P).inv lemma right_derived_zero_to_self_app_comp_inv [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : right_derived_zero_to_self_app F P ≫ right_derived_zero_to_self_app_inv F P = 𝟙 _ := begin dsimp [right_derived_zero_to_self_app, right_derived_zero_to_self_app_inv], rw [← category.assoc, iso.comp_inv_eq, category.id_comp, category.assoc, category.assoc, ← iso.eq_inv_comp, iso.inv_hom_id], ext, rw [category.assoc, category.assoc, homology.lift_ι, category.id_comp, homology.π'_ι, category.assoc, ←category.assoc _ _ (cokernel.π _), abelian.kernel.lift.inv, ← category.assoc, ← category.assoc _ (kernel.ι _), limits.kernel.lift_ι, category.assoc, category.assoc, ← category.assoc (homology_iso_kernel_desc _ _ _).hom _ _, ← homology.ι, ←category.assoc, homology.π'_ι, category.assoc, ←category.assoc (cokernel.π _), cokernel.π_desc, whisker_eq], convert category.id_comp (cokernel.π _), end lemma right_derived_zero_to_self_app_inv_comp [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : right_derived_zero_to_self_app_inv F P ≫ right_derived_zero_to_self_app F P = 𝟙 _ := begin dsimp [right_derived_zero_to_self_app, right_derived_zero_to_self_app_inv], rw [← category.assoc _ (F.right_derived_obj_iso 0 P).hom, category.assoc _ _ (F.right_derived_obj_iso 0 P).hom, iso.inv_hom_id, category.comp_id, ← category.assoc, ← category.assoc, is_iso.comp_inv_eq, category.id_comp], ext, simp only [limits.kernel.lift_ι_assoc, category.assoc, limits.kernel.lift_ι, homology.lift], rw [← category.assoc, ← category.assoc, category.assoc _ _ (homology_iso_kernel_desc _ _ _).hom], simp, end /-- Given `P : InjectiveResolution X`, the isomorphism `(F.right_derived 0).obj X ≅ F.obj X` if `preserves_finite_limits F`. -/ def right_derived_zero_to_self_app_iso [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : (F.right_derived 0).obj X ≅ F.obj X := { hom := right_derived_zero_to_self_app _ P, inv := right_derived_zero_to_self_app_inv _ P, hom_inv_id' := right_derived_zero_to_self_app_comp_inv _ P, inv_hom_id' := right_derived_zero_to_self_app_inv_comp _ P } /-- Given `P : InjectiveResolution X` and `Q : InjectiveResolution Y` and a morphism `f : X ⟶ Y`, naturality of the square given by `right_derived_zero_to_self_natural`. -/ lemma right_derived_zero_to_self_natural [enough_injectives C] {X : C} {Y : C} (f : X ⟶ Y) (P : InjectiveResolution X) (Q : InjectiveResolution Y) : F.map f ≫ right_derived_zero_to_self_app_inv F Q = right_derived_zero_to_self_app_inv F P ≫ (F.right_derived 0).map f := begin dsimp [right_derived_zero_to_self_app_inv], simp only [category_theory.functor.map_id, category.id_comp, ← category.assoc], rw [iso.comp_inv_eq, right_derived_map_eq F 0 f (InjectiveResolution.desc f Q P) (by simp), category.assoc, category.assoc, category.assoc, category.assoc, iso.inv_hom_id, category.comp_id, ← category.assoc (F.right_derived_obj_iso 0 P).inv, iso.inv_hom_id, category.id_comp], dsimp only [homology_functor_map], ext, rw [category.assoc, homology.lift_ι, category.assoc, homology.map_ι, ←category.assoc (homology.lift _ _ _ _ _) _ _, homology.lift_ι, category.assoc, cokernel.π_desc, ←category.assoc, ← functor.map_comp, ← category.assoc, homological_complex.hom.sq_from_left, map_homological_complex_map_f, ← functor.map_comp, show f ≫ Q.ι.f 0 = P.ι.f 0 ≫ (InjectiveResolution.desc f Q P).f 0, from homological_complex.congr_hom (InjectiveResolution.desc_commutes f Q P).symm 0], end /-- Given `preserves_finite_limits F`, the natural isomorphism `(F.right_derived 0) ≅ F`. -/ def right_derived_zero_iso_self [enough_injectives C] [preserves_finite_limits F] : (F.right_derived 0) ≅ F := iso.symm $ nat_iso.of_components (λ X, (right_derived_zero_to_self_app_iso _ (InjectiveResolution.of X)).symm) (λ X Y f, right_derived_zero_to_self_natural _ _ _ _) end category_theory.abelian.functor end
c3bbdd5ac2f9d6c888f73f0bbc74b7c84fb88a61
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Elab/PreDefinition/Structural.lean
5976a5b1193a943d85ac026f13e5b7d8f9c8fe5a
[ "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
24,207
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.Util.ForEachExpr import Lean.Meta.ForEachExpr import Lean.Meta.RecursorInfo import Lean.Meta.Match.Match import Lean.Meta.Transform import Lean.Elab.PreDefinition.Basic namespace Lean.Elab namespace Structural open Meta private def getFixedPrefix (declName : Name) (xs : Array Expr) (value : Expr) : MetaM Nat := do let numFixedRef ← IO.mkRef xs.size forEachExpr' value fun e => do if e.isAppOf declName then let args := e.getAppArgs numFixedRef.modify fun numFixed => if args.size < numFixed then args.size else numFixed for arg in args, x in xs do /- We should not use structural equality here. For example, given the definition ``` def V.map {α β} f x x_1 := @V.map.match_1.{1} α (fun x x_2 => V β x) x x_1 (fun x x_2 => @V.mk₁ β x (f Bool.true x_2)) (fun e => @V.mk₂ β (V.map (fun b => α b) (fun b => β b) f Bool.false e)) ``` The first three arguments at `V.map (fun b => α b) (fun b => β b) f Bool.false e` are "fixed" modulo definitional equality. We disable to proof irrelevance to be able to use structural recursion on inductive predicates. For example, consider the example ``` inductive PList (α : Type) : Prop | nil | cons : α → PList α → PList α infixr:67 " ::: " => PList.cons set_option trace.Elab.definition.structural true in def pmap {α β} (f : α → β) : PList α → PList β | PList.nil => PList.nil | a:::as => f a ::: pmap f as ``` The "Fixed" prefix would be 4 since all elements of type `PList α` are definitionally equal. -/ if !(← withoutProofIrrelevance <| withReducible <| isDefEq arg x) then -- We continue searching if e's arguments are not a prefix of `xs` return true return false else return true numFixedRef.get structure RecArgInfo where /- `fixedParams ++ ys` are the arguments of the function we are trying to justify termination using structural recursion. -/ fixedParams : Array Expr ys : Array Expr -- recursion arguments pos : Nat -- position in `ys` of the argument we are recursing on indicesPos : Array Nat -- position in `ys` of the inductive datatype indices we are recursing on indName : Name -- inductive datatype name of the argument we are recursing on indLevels : List Level -- inductice datatype universe levels of the argument we are recursing on indParams : Array Expr -- inductive datatype parameters of the argument we are recursing on indIndices : Array Expr -- inductive datatype indices of the argument we are recursing on, it is equal to `indicesPos.map fun i => ys.get! i` reflexive : Bool -- true if we are recursing over a reflexive inductive datatype private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := do let mut minPos := xs.size for index in indices do match xs.indexOf? index with | some pos => if pos.val < minPos then minPos := pos.val | _ => pure () return minPos -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr × Expr)) := do for index in indices do let indexType ← inferType index for y in ys do if !indices.contains y && (← dependsOn indexType y.fvarId!) then return some (index, y) return none -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr × Expr)) := do for p in indParams do let pType ← inferType p for y in ys do if ← dependsOn pType y.fvarId! then return some (p, y) return none private def throwStructuralFailed {α} : MetaM α := throwError "structural recursion cannot be used" structure State where /- When compiling structural recursion we use the `brecOn` recursor automatically built by the `inductive` command. For an inductive datatype `C`, it has the form `C.brecOn As motive is c F` where `As` are the inductive datatype parameters, `is` are the inductive datatype indices, `c : C As is`, and `F : (js) → (d : C As js) → C.below d → motive d` The `C.below d` is used to eliminate recursive applications. We refine its type when we process a nested dependent pattern matcher using `MatcherApp.addArg`. See `replaceRecApps` for additional details. We store the names of the matcher where we used `MatcherApp.addArg` at `matcherBelowDep`. We use this information to generate the auxiliary `_sunfold` definition needed by the smart unfolding technique used at WHNF. -/ matcherBelowDep : NameSet := {} abbrev M := StateRefT State MetaM instance {α} : Inhabited (M α) where default := throwError "failed" private def run {α} (x : M α) (s : State := {}) : MetaM (α × State) := StateRefT'.run x s private def orelse' {α} (x y : M α) : M α := do let saveState ← get orelseMergeErrors x (do set saveState; y) private partial def findRecArg {α} (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → M α) : M α := let rec loop (i : Nat) : M α := do if h : i < xs.size then let x := xs.get ⟨i, h⟩ let localDecl ← getFVarLocalDecl x if localDecl.isLet then throwStructuralFailed else let xType ← whnfD localDecl.type matchConstInduct xType.getAppFn (fun _ => loop (i+1)) fun indInfo us => do if !(← hasConst (mkBRecOnName indInfo.name)) then loop (i+1) else if indInfo.isReflexive && !(← hasConst (mkBInductionOnName indInfo.name)) then loop (i+1) else let indArgs := xType.getAppArgs let indParams := indArgs.extract 0 indInfo.numParams let indIndices := indArgs.extract indInfo.numParams indArgs.size if !indIndices.all Expr.isFVar then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not variables{indentExpr xType}") (loop (i+1)) else if !indIndices.allDiff then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not pairwise distinct{indentExpr xType}") (loop (i+1)) else let indexMinPos := getIndexMinPos xs indIndices let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed let fixedParams := xs.extract 0 numFixed let ys := xs.extract numFixed xs.size match ← hasBadIndexDep? ys indIndices with | some (index, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive family{indentExpr xType}\nand index{indentExpr index}\ndepends on the non index{indentExpr y}") (loop (i+1)) | none => match ← hasBadParamDep? ys indParams with | some (indParam, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive datatype{indentExpr xType}\nand parameter{indentExpr indParam}\ndepends on{indentExpr y}") (loop (i+1)) | none => let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable! orelse' (mapError (k { fixedParams := fixedParams ys := ys pos := i - fixedParams.size indicesPos := indicesPos indName := indInfo.name indLevels := us indParams := indParams indIndices := indIndices reflexive := indInfo.isReflexive }) (fun msg => m!"argument #{i+1} was not used for structural recursion{indentD msg}")) (loop (i+1)) else throwStructuralFailed loop numFixed private def containsRecFn (recFnName : Name) (e : Expr) : Bool := (e.find? fun e => e.isConstOf recFnName).isSome private def ensureNoRecFn (recFnName : Name) (e : Expr) : MetaM Expr := do if containsRecFn recFnName e then Meta.forEachExpr e fun e => do if e.isAppOf recFnName then throwError "unexpected occurrence of recursive application{indentExpr e}" pure e else pure e private def throwToBelowFailed {α} : MetaM α := throwError "toBelow failed" /- See toBelow -/ private partial def toBelowAux (C : Expr) : Expr → Expr → Expr → MetaM Expr | belowDict, arg, F => do let belowDict ← whnf belowDict trace[Elab.definition.structural] "belowDict: {belowDict}, arg: {arg}" match belowDict with | Expr.app (Expr.app (Expr.const `PProd _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `PProd.fst #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `PProd.snd #[F])) | Expr.app (Expr.app (Expr.const `And _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `And.left #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `And.right #[F])) | _ => forallTelescopeReducing belowDict fun xs belowDict => do let argArgs := arg.getAppArgs unless argArgs.size >= xs.size do throwToBelowFailed let n := argArgs.size let argTailArgs := argArgs.extract (n - xs.size) n let belowDict := belowDict.replaceFVars xs argTailArgs match belowDict with | Expr.app belowDictFun belowDictArg _ => unless belowDictFun.getAppFn == C do throwToBelowFailed unless ← isDefEq belowDictArg arg do throwToBelowFailed pure (mkAppN F argTailArgs) | _ => throwToBelowFailed /- See toBelow -/ private def withBelowDict {α} (below : Expr) (numIndParams : Nat) (k : Expr → Expr → MetaM α) : MetaM α := do let belowType ← inferType below trace[Elab.definition.structural] "belowType: {belowType}" belowType.withApp fun f args => do let motivePos := numIndParams + 1 unless motivePos < args.size do throwError "unexpected 'below' type{indentExpr belowType}" let pre := mkAppN f (args.extract 0 numIndParams) let preType ← inferType pre forallBoundedTelescope preType (some 1) fun x _ => do let motiveType ← inferType x[0] let C ← mkFreshUserName `C withLocalDeclD C motiveType fun C => let belowDict := mkApp pre C let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size) k C belowDict /- `below` is a free variable with type of the form `I.below indParams motive indices major`, where `I` is the name of an inductive datatype. For example, when trying to show that the following function terminates using structural recursion ```lean def addAdjacent : List Nat → List Nat | [] => [] | [a] => [a] | a::b::as => (a+b) :: addAdjacent as ``` when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type `@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)` The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute. So, we first replace it with a fresh variable `C` at `withBelowDict`. Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary of the "previous values". We search this dictionary using the auxiliary function `toBelowAux`. The dictionary is built using the `PProd` (`And` for inductive predicates). We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/ private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do withBelowDict below numIndParams fun C belowDict => toBelowAux C belowDict recArg below /-- Return true iff `e` contains an application `recFnName .. t ..` where the term `t` is the argument we are trying to recurse on, and it contains loose bound variables. We use this test to decide whether we should process a matcher-application as a regular applicaton or not. That is, whether we should push the `below` argument should be affected by the matcher or not. If `e` does not contain an application of the form `recFnName .. t ..`, then we know the recursion doesn't depend on any pattern variable in this matcher. -/ private def recArgHasLooseBVarsAt (recFnName : Name) (recArgInfo : RecArgInfo) (e : Expr) : Bool := let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos let app? := e.find? fun e => e.isAppOf recFnName && e.getAppNumArgs > recArgPos && (e.getArg! recArgPos).hasLooseBVars app?.isSome private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) (below : Expr) (e : Expr) : M Expr := let rec loop (below : Expr) (e : Expr) : M Expr := do match e with | Expr.lam n d b c => withLocalDecl n c.binderInfo (← loop below d) fun x => do mkLambdaFVars #[x] (← loop below (b.instantiate1 x)) | Expr.forallE n d b c => withLocalDecl n c.binderInfo (← loop below d) fun x => do mkForallFVars #[x] (← loop below (b.instantiate1 x)) | Expr.letE n type val body _ => withLetDecl n (← loop below type) (← loop below val) fun x => do mkLetFVars #[x] (← loop below (body.instantiate1 x)) | Expr.mdata d e _ => return mkMData d (← loop below e) | Expr.proj n i e _ => return mkProj n i (← loop below e) | Expr.app _ _ _ => let processApp (e : Expr) : M Expr := e.withApp fun f args => do if f.isConstOf recFnName then let numFixed := recArgInfo.fixedParams.size let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos if recArgPos >= args.size then throwError "insufficient number of parameters at recursive application {indentExpr e}" let recArg := args[recArgPos] -- For reflexive type, we may have nested recursive applications in recArg let recArg ← loop below recArg let f ← try toBelow below recArgInfo.indParams.size recArg catch _ => throwError "failed to eliminate recursive application{indentExpr e}" -- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them. let argsNonFixed := args.extract numFixed args.size -- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too. let mut fArgs := #[] for i in [:argsNonFixed.size] do if recArgInfo.pos != i && !recArgInfo.indicesPos.contains i then let arg := argsNonFixed[i] let arg ← replaceRecApps recFnName recArgInfo below arg fArgs := fArgs.push arg return mkAppN f fArgs else return mkAppN (← loop below f) (← args.mapM (loop below)) let matcherApp? ← matchMatcherApp? e match matcherApp? with | some matcherApp => if !recArgHasLooseBVarsAt recFnName recArgInfo e then processApp e else /- Here is an example we currently not handle ``` def g (xs : List Nat) : Nat := match xs with | [] => 0 | y::ys => match ys with | [] => 1 | _::_::zs => g zs + 1 | zs => g ys + 2 ``` We are matching on `ys`, but still using `ys` in the third alternative. If we push the `below` argument over the dependent match it will be able to eliminate recursive call using `zs`. To make it work, users have to write the third alternative as `| zs => g zs + 2` If this is too annoying in practice, we may replace `ys` with the matching term, but this may generate weird error messages, when it doesn't work. -/ trace[Elab.definition.structural] "below before matcherApp.addArg: {below} : {← inferType below}" let matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg) modify fun s => { s with matcherBelowDep := s.matcherBelowDep.insert matcherApp.matcherName } let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do trace[Elab.definition.structural] "altNumParams: {numParams}, xs: {xs}" unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let belowForAlt := xs[numParams - 1] mkLambdaFVars xs (← loop belowForAlt altBody) pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | e => ensureNoRecFn recFnName e loop below e private def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : M Expr := do let type := (← inferType value).headBeta let major := recArgInfo.ys[recArgInfo.pos] let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y trace[Elab.definition.structural] "fixedParams: {recArgInfo.fixedParams}, otherArgs: {otherArgs}" let motive ← mkForallFVars otherArgs type let mut brecOnUniv ← getLevel motive trace[Elab.definition.structural] "brecOn univ: {brecOnUniv}" let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero if recArgInfo.reflexive && brecOnUniv != levelZero then brecOnUniv ← decLevel brecOnUniv let motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive trace[Elab.definition.structural] "brecOn motive: {motive}" let brecOn := if useBInductionOn then Lean.mkConst (mkBInductionOnName recArgInfo.indName) recArgInfo.indLevels else Lean.mkConst (mkBRecOnName recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels) let brecOn := mkAppN brecOn recArgInfo.indParams let brecOn := mkApp brecOn motive let brecOn := mkAppN brecOn recArgInfo.indIndices let brecOn := mkApp brecOn major check brecOn let brecOnType ← inferType brecOn trace[Elab.definition.structural] "brecOn {brecOn}" trace[Elab.definition.structural] "brecOnType {brecOnType}" forallBoundedTelescope brecOnType (some 1) fun F _ => do let F := F[0] let FType ← inferType F trace[Elab.definition.structural] "FType: {FType}" let FType ← instantiateForall FType recArgInfo.indIndices let FType ← instantiateForall FType #[major] forallBoundedTelescope FType (some 1) fun below _ => do let below := below[0] let valueNew ← replaceRecApps recFnName recArgInfo below value let Farg ← mkLambdaFVars (recArgInfo.indIndices ++ #[major, below] ++ otherArgs) valueNew let brecOn := mkApp brecOn Farg pure $ mkAppN brecOn otherArgs private def shouldBetaReduce (e : Expr) (recFnName : Name) : Bool := if e.isHeadBetaTarget then e.getAppFn.find? (·.isConstOf recFnName) |>.isSome else false /-- Beta reduce terms where the recursive function occurs in the lambda term. This is useful to improve the effectiveness of `elimRecursion`. Example: ``` def f : Nat → Nat | 0 => 1 | i+1 => (fun x => f x) i ``` -/ private def preprocess (e : Expr) (recFnName : Name) : CoreM Expr := Core.transform e fun e => return TransformStep.visit <| if shouldBetaReduce e recFnName then e.headBeta else e private def elimRecursion (preDef : PreDefinition) : M PreDefinition := withoutModifyingEnv do lambdaTelescope preDef.value fun xs value => do addAsAxiom preDef let value ← preprocess value preDef.declName trace[Elab.definition.structural] "{preDef.declName} {xs} :=\n{value}" let numFixed ← getFixedPrefix preDef.declName xs value trace[Elab.definition.structural] "numFixed: {numFixed}" findRecArg numFixed xs fun recArgInfo => do -- when (recArgInfo.indName == `Nat) throwStructuralFailed -- HACK to skip Nat argument let valueNew ← mkBRecOn preDef.declName recArgInfo value let valueNew ← mkLambdaFVars xs valueNew trace[Elab.definition.structural] "result: {valueNew}" -- Recursive applications may still occur in expressions that were not visited by replaceRecApps (e.g., in types) let valueNew ← ensureNoRecFn preDef.declName valueNew pure { preDef with value := valueNew } partial def addSmartUnfoldingDefAux (preDef : PreDefinition) (matcherBelowDep : NameSet) : MetaM PreDefinition := do let recFnName := preDef.declName let isMarkedMatcherName (n : Name) : Bool := matcherBelowDep.contains n let isMarkedMatcherConst (e : Expr) : Bool := e.isConst && isMarkedMatcherName e.constName! let isMarkedMatcherApp (e : Expr) : Bool := isMarkedMatcherConst e.getAppFn let containsMarkedMatcher (e : Expr) : Bool := e.find? isMarkedMatcherConst |>.isSome let rec visit (e : Expr) : MetaM Expr := do match e with | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← visit b) | Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← visit b) | Expr.letE n type val body _ => withLetDecl n type (← visit val) fun x => do mkLetFVars #[x] (← visit (body.instantiate1 x)) | Expr.mdata d b _ => return mkMData d (← visit b) | Expr.proj n i s _ => return mkProj n i (← visit s) | Expr.app .. => let processApp (e : Expr) : MetaM Expr := e.withApp fun f args => do return mkAppN (← visit f) (← args.mapM visit) match isMarkedMatcherApp e, (← matchMatcherApp? e) with | true, some matcherApp => let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" if containsMarkedMatcher altBody then -- continue mkLambdaFVars xs (← visit altBody) else -- add idRhs marker let altBody ← mkLambdaFVars xs[numParams:xs.size] altBody let altBody ← mkIdRhs altBody mkLambdaFVars xs[0:numParams] altBody pure { matcherApp with alts := altsNew }.toExpr | _, _ => processApp e | _ => pure e return { preDef with declName := mkSmartUnfoldingNameFor preDef.declName, value := (← visit preDef.value), modifiers := {} } partial def addSmartUnfoldingDef (preDef : PreDefinition) (state : State) : TermElabM Unit := do if (← isProp preDef.type) then return () else let preDefSUnfold ← addSmartUnfoldingDefAux preDef state.matcherBelowDep addNonRec preDefSUnfold def structuralRecursion (preDefs : Array PreDefinition) : TermElabM Unit := if preDefs.size != 1 then throwError "structural recursion does not handle mutually recursive functions" else do let (preDefNonRec, state) ← run $ elimRecursion preDefs[0] mapError (addNonRec preDefNonRec) (fun msg => m!"structural recursion failed, produced type incorrect term{indentD msg}") addAndCompilePartialRec preDefs addSmartUnfoldingDef preDefs[0] state builtin_initialize registerTraceClass `Elab.definition.structural end Structural export Structural (structuralRecursion) end Lean.Elab
ad52deda8fc3ef0eba66447fd4d0d9d67e89e07a
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/demos/category_theory.lean
9e7ac3257bee7327de592a631857532e75badf4a
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
15,347
lean
import demos.category_theory_imports /-! This is a demo of the category theory library in mathlib, as part of "Lean for the Curious Mathematician 2020". You can get this file by: * installing Lean if necessary: https://leanprover-community.github.io/get_started.html#regular-install * `leanproject get lftcm2020` * `code lftcm2020` * open the file `src/demos/category_theory.lean` If you've already got a copy of `lftcm2020`, you should update it now, using ``` cd /path/to/lftcm2020/ git pull leanproject get-mathlib-cache ``` There are also exercises associated with this demo, in `src/exercise_sources/thursday/afternoon/category_theory/` with hints at `src/hints/thursday/afternoon/category_theory/` and (partial) solutions at `src/solutions/thursday/afternoon/category_theory/` Any of Exercises 1-7 should be approachable after the demo. The later exercises are quite hard, and will take you longer than the afternoon problem session! -/ open category_theory /-! ## Categories Categories are implemented in mathlib as a typeclass, parametrised by the type of objects. Thus to talk about an arbitrary category, we can write -/ variables (C : Type) [category C] /-! There is special notation for the morphisms in a category: if `X Y : C`, we write * `X ⟶ Y` for the type of morphisms from `X` to `Y`. (To enter the special arrow `⟶`, type `\hom`, or hover over the symbol to see the hint.) * `𝟙 X` is a the identity morphisms on `X` (i.e., a term of type `X ⟶ X`). * If `f : X ⟶ Y` and `g : Y ⟶ Z`, then we write `f ≫ g` for the composition, a morphism `X ⟶ Z`. -/ example {W X Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) : (f ≫ (𝟙 X ≫ g)) ≫ h = f ≫ g ≫ h := begin rw category.id_comp, rw category.assoc, -- alternatively, just `simp` will do end /-! ## Functors To introduce functors, we'll need a second category around. -/ variables (D : Type) [category D] /-! We write a functor as `F : C ⥤ D`. (Unlike categories, which are partially unbundled, a functor is "fully bundled", containing the function on objects as field. This parallels the design for algebraic structures.) -/ example (F : C ⥤ D) (X : C) : F.map (𝟙 X) = 𝟙 (F.obj X) := F.map_id X example (F : C ⥤ D) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : F.map (f ≫ g) = F.map f ≫ F.map g := F.map_comp f g /-! The identity functor is written as `𝟭 C`, and functor composition is written `⋙`. -/ example (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : (𝟭 C ⋙ F).map (f ≫ 𝟙 Y) = F.map f := begin rw functor.comp_map, rw functor.map_comp, rw category_theory.functor.map_id, -- yuck! we really should fix this rw functor.id_map, rw functor.map_comp, rw category_theory.functor.map_id, rw category.comp_id, -- or just replace the entire proof with `by simp` end /-! To build a functor `F : C ⥤ D` we need to specify four fields * `obj : C → D` * `map : ∀ {X Y : C} (f : X ⟶ Y), obj X ⟶ obj Y` * `map_id'` and `map_comp'`, expressing the functor laws. -/ example {X : C} : C ⥤ Type* := { obj := λ Y, X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_id' := λ X, begin funext, simp, end, map_comp' := λ X Y Z f g, begin funext, simp, end } /-! However Lean will automatically attempt to fill in the `map_id'` and `map_comp'` fields itself, because these fields are marked with `auto_param`. This lets us specify a tactic to use to try to synthesize the field. (In fact, the whole category theory library started off as an experiment to see how far we could push this automation.) -/ example {X : C} : C ⥤ Type* := { obj := λ Y, X ⟶ Y, map := λ Y Y' f g, g ≫ f, } /-! Lean automatically checked functoriality here! This was pretty easy: we just need to use `category.comp_id` and `category.assoc`. The more powerful we make the `simp` lemmas, the more boring goals can be discharged automatically. Most of the `auto_param`s appearing in mathlib so far are in the `category_theory` library, where they are nearly all filled using the tactic `tidy`, which repeatedly attempts to use one of a list of "conservative" tactics. You can see what `tidy` is doing using `tidy?`: -/ example {X : C} : C ⥤ Type* := { obj := λ Y, X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_id' := by tidy?, map_comp' := by tidy? } /-! Sebastien's talk on differential geometry tomorrow will give another example of `auto_param` being used. You can also watch me doing a speed-run https://youtu.be/oz3z2NSNY8c of Floris's "pointed map" exercises from yesterday, taking advantage of `auto_param`. -/ /-! ## Natural transformations The collection of functors from `C` to `D` has been given the structure of a category: to talk about the natural transformations, you just write `F ⟶ G` using the usual "morphism" arrow. If `α : F ⟶ G`, then `α.app X` is the component at `X`, i.e. a morphism `F.obj X ⟶ G.obj X`. -/ example {F G : C ⥤ D} {α : F ⟶ G} {X Y : C} (f : X ⟶ Y) : F.map f ≫ α.app Y = α.app X ≫ G.map f := α.naturality f -- or just `by simp` /-! Again, to construct a natural transformation `F ⟶ G` we need to provide two fields * `app : Π X : C, F.obj X ⟶ G.obj X` and * `naturality'`, which often is provided by automation. -/ /-! ## A note on universes Before we go on, we should mention a slight complication: out in the world we meet both small and large categories. In set-theoretic foundations, this distinction is about whether the objects form a set or merely a class. In the type-theoretic foundations used in Lean, this distinction is about whether the objects and morphisms live in the same universe, or if the objects live one universe higher up. Rather than making separate definitions for the two cases, we simply allow the objects and morphisms to live in two unrelated universes. To talk about a general category we thus write -/ universes u v variables (E : Type u) [category.{v} E] /-! This says that the objects live in universe `u`, while the morphisms live in universe `v`. In fact, the definition `category` is paramaterised by two universe levels, and when we write `category.{v} E` Lean actually understands this as `category.{v u} E`, automatically filling in the second argument from the universe level of `E`. There are abbreviations available for the two standard cases: * if `E : Type (u+1)`, then `large_category E` means `category.{u (u+1)} E` * if `E : Type u`, then `small_category E` means `category.{u u} E`. However you'll rarely use these except when setting up particular examples. All the "concrete" categories, like `Group`, `Ring`, and `Top`, described below, are instances of `large_category`. Typically the indexing diagrams for limits and colimits are instances of `small_category`. If you're talking about an arbitrary category, and you don't mind whether it is small or large, you should just allow two independent universe variables, as above. -/ /-! ## Concrete categories We've set up a number of concrete categories in mathlib. -/ example (R S : CommRing) (f : R ⟶ S) (x y : R) : f (x * y) = f x * f y := by simp /-! Note here we have a particularly succinct way of introducing a commutative ring: we just write `R : CommRing`, rather than `(R : Type) [comm_ring R]`. Rather than writing `f : R →+* S` for a `ring_hom`, we can just use the morphism arrow, and Lean works out the appropriate notion automatically. There's a coercion from `CommRing` to `Type`, so we can still talk about elements by writing `x : R`, and morphisms automatically behave properly as functions (e.g. in `f (x * y)`). -/ /-! ## Limits and colimits We talk about limits using the following notions: * For `F : J ⥤ C`, `c : cone F` consists of * `c.X : C` an object in `C`, and * `c.π`, a natural transformation with components `c.π.app j : c.X ⟶ F.obj j`. * For `c : cone F`, `is_limit c` expresses that `c` is a limit cone. * `has_limit F`, a typeclass specifying a particular choice of limit cone for a functor `F`. * `has_limits C`, a typeclass specifying a choice of limit for any functor into `C`. (There are also all the dual notions, `cocone`, `is_colimit`, `has_colimit`, etc.) There are also typeclasses for various "special shapes", in particular * `has_equalizers` * `has_pullbacks` * `has_binary_products` / `has_finite_products` / `has_products` * `has_terminal` A related typeclass `has_zero_morphisms C` specifies a choice of zero morphism in each hom space, satisfying the usual axioms (equivalent to `C` being enriched in pointed sets), and using that we can also express some other special shapes, including * `has_kernels` * `has_binary_biproducts` / `has_finite_biproducts` * `has_zero_object` For most of the concrete categories, these instances are all available when appropriate. -/ /-! ### Examples of using (co)limits in `Top` -/ noncomputable theory open category_theory.limits def R : Top := Top.of ℝ def I : Top := Top.of (set.Icc 0 1 : set ℝ) def pt : Top := Top.of unit -- Let's construct the mapping cylinder. def to_pt (X : Top) : X ⟶ pt := { val := λ _, unit.star, property := continuous_const } def I₀ : pt ⟶ I := { val := λ _, ⟨(0 : ℝ), by norm_num [set.left_mem_Icc]⟩, property := continuous_const } def I₁ : pt ⟶ I := { val := λ _, ⟨(1 : ℝ), by norm_num [set.right_mem_Icc]⟩, property := continuous_const } -- We now construct a cylinder as a categorical limit. -- `limits.prod` is a shorthand for constructing a limit over the two point diagram: def cylinder (X : Top) : Top := prod X I -- To define a map to the cylinder, we give a map to each factor. -- `prod.lift` is a helper method, providing a wrapper around `limit.lift` for binary products. def cylinder₀ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₀) def cylinder₁ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₁) /-- The mapping cylinder is the pushout of the diagram ``` X ↙ ↘ Y (X x I) ``` (`pushout` is implemented just as a wrapper around `colimit`) -/ def mapping_cylinder {X Y : Top} (f : X ⟶ Y) : Top := pushout f (cylinder₁ X) /-! It's perhaps worth admitting here that constructing objects using categorical (co)limits typically gives quite ghastly "definitional" properties --- if you want to use these objects, you're going to have to work through their universal properties. This is not necessarily a bad thing, but takes some getting used to. -/ /-! ## Applications We're only just getting to the point in mathlib where we're ready to do the sorts of mathematics that rely on category theory as a basic language. There's lots more to come --- big chunks of algebraic geometry, homological algebra, quantum topology, etc. One important way in which we'll use the category theory library is to achieve polymorphism. We don't want to separately prove theorems about sheaves of sets, sheaves of rings, etc. Instead we'd like to talk about sheaves in an arbitrary category, possibly with some additional typeclasses providing extra structure (`has_products`, `concrete_category`, `monoidal_category`, etc), and prove our theorems there. -/ /-! ### Homological algebra We've recently set up the very basics of homoological algebra using the category theory library. There's still a way to go --- good projects for the near future include * injective covers and resolutions * `Ext` and `Tor` * bicomplexes, the salamander, snake, five, and nine lemmas Here's something you can do already: -/ open category_theory.limits local notation `Ab` := AddCommGroup.{0} local attribute [instance] has_equalizers_of_has_finite_limits local attribute [instance] has_coequalizers_of_has_finite_colimits noncomputable theory -- `has_images Ab` is noncomputable! open cochain_complex homological_complex abbreviation Z := AddCommGroup.of ℤ def mul_by (k : ℤ) : Z ⟶ Z := add_monoid_hom.of (gsmul k) /-- We define the complex `... --0--> ℤ --2--> ℤ --0--> ℤ --4--> ℤ --0--> ...` -/ def P : cochain_complex Ab := { X := λ i, Z, d := λ i, if i.even then mul_by i else 0, d_squared' := begin ext i, dsimp, by_cases h : i.even; simp [h] with parity_simps, end } #check (graded_cohomology Ab).obj P /-- Let's try to calculate the cohomology! -/ @[simp] lemma mul_by_apply (k x : ℤ) : mul_by k x = (k * x : ℤ) := by simp [mul_by] lemma mul_by_ker {k : ℤ} (h : k ≠ 0) : (mul_by k).ker = ⊥ := begin tidy, { simp only [add_monoid_hom.mem_ker] at a, finish, }, { subst a, simp [add_monoid_hom.mem_ker], }, end def P_2 : P.cohomology_group 2 ≅ 0 := begin change cokernel (image_to_kernel_map 0 (mul_by 2) _) ≅ 0, calc cokernel (image_to_kernel_map 0 (mul_by 2) (has_zero_morphisms.zero_comp _ _)) ≅ cokernel (0 : image (0 : Z ⟶ Z) ⟶ kernel (mul_by 2)) : cokernel_iso_of_eq (by simp) ... ≅ kernel (mul_by 2) : cokernel_zero_iso_target ... ≅ AddCommGroup.of (mul_by 2).ker : AddCommGroup.kernel_iso_ker (mul_by 2) ... ≅ AddCommGroup.of (⊥ : add_subgroup Z) : AddCommGroup.of_add_subgroup_eq (mul_by_ker (by norm_num)) ... ≅ 0 : AddCommGroup.of_add_subgroup_bot, end. -- Somehow this isn't in mathlib? lemma quotient_gsmul (k : ℕ) : quotient_add_group.quotient (set.range (gsmul k : ℤ → ℤ)) ≃+ zmod k := sorry def P_3 : P.cohomology_group 3 ≅ AddCommGroup.of (zmod 2) := begin change cokernel (image_to_kernel_map (mul_by 2) 0 _) ≅ AddCommGroup.of (zmod 2), calc cokernel (image_to_kernel_map (mul_by 2) 0 _) ≅ cokernel (image.ι (mul_by 2) ≫ inv (kernel.ι (0 : Z ⟶ Z))) : cokernel_iso_of_eq (image_to_kernel_map_zero_right _) ... ≅ cokernel (image.ι (mul_by 2)) : cokernel_comp_is_iso _ _ ... ≅ cokernel (mul_by 2) : cokernel_image_ι _ ... ≅ AddCommGroup.of (quotient_add_group.quotient (set.range (mul_by 2))) : AddCommGroup.cokernel_iso_quotient _ ... ≅ AddCommGroup.of (zmod 2) : add_equiv_iso_AddCommGroup_iso.hom (quotient_gsmul 2), end /-! ## Odds and ends There's a bunch in mathlib's `category_theory/` folder that hasn't been mentioned at all here, including: * Adjunctions * Equivalences * Monads * Abelian categories * Monoidal categories * ... -/ #print category_theory.adjunction.right_adjoint_preserves_limits #print category_theory.abelian -- Right now we don't have a single instance of `abelian` in the library: -- constructing `abelian AddCommGroup` is a great exercise, and all the ingredients are available. -- The only things remaining are -- "every mono is the kernel of its cokernel" and "every epi is the cokernel of its kernel" -- and these should be easy consequences of statements in the non-categorical group theory library. instance : abelian AddCommGroup := { normal_mono := λ X Y f f_mono, -- If you're actually going to attempt this, write `by extract_goal` here -- and prove this as a preliminary lemma. { Z := cokernel f, g := cokernel.π f, w := by tidy, is_limit := begin fapply kernel_fork.is_limit.mk, -- now look in group_theory/quotient_group.lean! sorry, sorry, sorry, end, }, normal_epi := sorry, } example (R : CommRing) : monoidal_category (Module R) := by apply_instance example : reflective (forget₂ CpltSepUniformSpace UniformSpace) := by apply_instance
5ad21423eb9ae143eb5086ec1c2447a8219f9eab
246309748072bf9f8da313401699689ebbecd94d
/src/ring_theory/integral_closure.lean
15ccafb5464e88a8fb9220c8b5ef8b3fe979a72b
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
16,555
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.algebra_tower /-! # Integral closure of a subring. If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial with coefficients in R. Enough theory is developed to prove that integral elements form a sub-R-algebra of A. ## Main definitions Let `R` be a `comm_ring` and let `A` be an R-algebra. * `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with coefficients in `R`. * `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`. -/ universes u v w open_locale classical open polynomial submodule section variables (R : Type u) {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra R A] [algebra R B] /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. -/ def is_integral (x : A) : Prop := ∃ p : polynomial R, monic p ∧ aeval x p = 0 variables {R} theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := ⟨X - C x, monic_X_sub_C _, by rw [alg_hom.map_sub, aeval_def, aeval_def, eval₂_X, eval₂_C, sub_self]⟩ theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) := let ⟨p, hp, hpx⟩ := hx in ⟨p, hp, by rw [aeval_alg_hom_apply, hpx, f.map_zero]⟩ theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B] (x : B) (hx : is_integral R x) : is_integral A x := let ⟨p, hp, hpx⟩ := hx in ⟨p.map $ algebra_map R A, monic_map _ hp, by rw [← is_scalar_tower.aeval_apply, hpx]⟩ theorem is_integral_of_subring {x : A} (T : set R) [is_subring T] (hx : is_integral T x) : is_integral R x := is_integral_of_is_scalar_tower x hx theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (ring.closure s) r := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, refine ⟨_, set.finite_mem_finset _, p.restriction, subtype.eq hmp, _⟩, erw [is_scalar_tower.aeval_apply _ R, map_restriction, hpr] }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A) : submodule R A).fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range at hr, rcases hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %ₘ f = q at this ⊢, rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, finsupp.sum], refine sum_mem _ (λ k hkq, _), rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _), rw [degree_le_iff_coeff_zero] at this, rw [finsupp.mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s : submodule R A).fg := set.finite.induction_on hfs (λ _, ⟨{1}, submodule.ext $ λ x, by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_map_top, map_top, linear_map.mem_range, algebra.mem_bot], refl }⟩) (λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his theorem is_integral_of_noetherian' (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval x).to_linear_map, let D : ℕ → submodule R A := λ n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : ¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_noetherian (S : subalgebra R A) (H : is_noetherian R (S : submodule R A)) (x : A) (hx : x ∈ S) : is_integral R x := begin letI : algebra R S := S.algebra, letI : comm_ring S := S.comm_ring R A, suffices : is_integral R (⟨x, hx⟩ : S), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg subtype.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, eval₂, finsupp.sum], rw ← p.support.sum_hom subtype.val, { refine finset.sum_congr rfl (λ n hn, _), change _ = _ * _, rw is_monoid_hom.map_pow coe, refl, split; intros; refl }, refine { map_add := _, map_zero := _ }; intros; refl }, refine is_integral_of_noetherian' H ⟨x, hx⟩ end theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : (S : submodule R A).fg) (x : A) (hx : x ∈ S) : is_integral R x := begin cases HS with y hy, obtain ⟨lx, hlx1, hlx2⟩ : ∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, have hyS : ∀ {p}, p ∈ y → p ∈ S := λ p hp, show p ∈ (S : submodule R A), by { rw ← hy, exact subset_span hp }, have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ (S : submodule R A) := λ jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2), rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_iff_total] at this, choose ly hly1 hly2, let S₀ : set R := ring.closure ↑(lx.frange ∪ finset.bind finset.univ (finsupp.frange ∘ ly)), refine is_integral_of_subring S₀ _, have : span S₀ (insert 1 ↑y : set A) * span S₀ (insert 1 ↑y : set A) ≤ span S₀ (insert 1 ↑y : set A), { rw span_mul_span, refine span_le.2 (λ z hz, _), rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩, { rw one_mul, exact subset_span hq }, rcases hq with rfl | hq, { rw mul_one, exact subset_span (or.inr hp) }, erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, rw [finsupp.total_apply, finsupp.sum], refine (span S₀ (insert 1 ↑y : set A)).sum_mem (λ t ht, _), have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ S₀ := ring.subset_closure (finset.mem_union_right _ $ finset.mem_bind.2 ⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _, finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩), change (⟨_, this⟩ : S₀) • t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) }, haveI : is_subring (span S₀ (insert 1 ↑y : set A) : set A) := { one_mem := subset_span $ or.inl rfl, mul_mem := λ p q hp hq, this $ mul_mem_mul hp hq, zero_mem := (span S₀ (insert 1 ↑y : set A)).zero_mem, add_mem := λ _ _, (span S₀ (insert 1 ↑y : set A)).add_mem, neg_mem := λ _, (span S₀ (insert 1 ↑y : set A)).neg_mem }, have : span S₀ (insert 1 ↑y : set A) = algebra.adjoin S₀ (↑y : set A), { refine le_antisymm (span_le.2 $ set.insert_subset.2 ⟨(algebra.adjoin S₀ ↑y).one_mem, algebra.subset_adjoin⟩) (λ z hz, _), rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, rw ← submodule.mem_coe, refine ring.closure_subset (set.union_subset (set.range_subset_iff.2 $ λ t, _) (λ t ht, subset_span $ or.inr ht)) hz, rw algebra.algebra_map_eq_smul_one, exact smul_mem (span S₀ (insert 1 ↑y : set A)) _ (subset_span $ or.inl rfl) }, haveI : is_noetherian_ring ↥S₀ := is_noetherian_ring_closure _ (finset.finite_to_set _), refine is_integral_of_noetherian (algebra.adjoin S₀ ↑y) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw [finset.coe_insert, this]⟩) _ _, rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (λ r hr, _), have : lx r ∈ S₀ := ring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)), change (⟨_, this⟩ : S₀) • r ∈ _, rw finsupp.mem_supported at hlx1, exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _ end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ ring.closure ({x, y} : set A)) : is_integral R z := begin have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (algebra.mem_adjoin_iff.2 $ ring.closure_mono (set.subset_union_right _ _) hz) end theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).map_zero ▸ is_integral_algebra_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).map_one ▸ is_integral_algebra_map theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem (ring.subset_closure (or.inl rfl))) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := is_integral_add hx (is_integral_neg hy) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := is_integral_of_mem_closure hx hy (is_submonoid.mul_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) variables (R A) /-- The integral closure of R in an R-algebra A. -/ def integral_closure : subalgebra R A := { carrier := { carrier := { r | is_integral R r }, zero_mem' := is_integral_zero, one_mem' := is_integral_one, add_mem' := λ _ _, is_integral_add, mul_mem' := λ _ _, is_integral_mul }, algebra_map_mem' := λ x, is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, (M : submodule R A).fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ variables {R} {A} lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x := let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $ by rwa [subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩ end section algebra open algebra variables {R : Type*} {A : Type*} {B : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra A B] [algebra R B] lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) : is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x := begin generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S, have coeffs_mem : ∀ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S, { intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0, { rw hi, exact subalgebra.zero_mem _ }, rw ← hS, exact subset_adjoin (finsupp.mem_frange.2 ⟨hi, i, rfl⟩) }, obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) = (p.map $ algebra_map A B), { rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (λ i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) B)).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact monic_map _ pmonic } }, { convert hp using 1, replace hq := congr_arg (eval x) hq, convert hq using 1; symmetry; apply eval_map }, end variables [algebra R A] [is_scalar_tower R A B] /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : ∀ x : A, is_integral R x) (x : B) (hx : is_integral A x) : is_integral R x := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set B := ↑(p.map $ algebra_map A B).frange, refine is_integral_of_mem_of_fg (adjoin R (S ∪ {x})) _ _ (subset_adjoin $ or.inr rfl), refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (λ x hx, _)) _, { rw [finset.mem_coe, finsupp.mem_frange] at hx, rcases hx with ⟨_, i, rfl⟩, show is_integral R ((p.map $ algebra_map A B).coeff i), rw coeff_map, convert is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (A_int : ∀ x : A, is_integral R x)(B_int : ∀ x:B, is_integral A x) : ∀ x:B, is_integral R x := λ x, is_integral_trans A_int x (B_int x) lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : ∀ x : A, is_integral R x := λ x, (h x).rec_on (λ y hy, (hy ▸ is_integral_algebra_map : is_integral R x)) /-- If `R → A → B` is an algebra tower with `A → B` injective, then if the entire tower is an integral extension so is `R → A` -/ lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B)) {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p, ⟨hp, _⟩⟩, rw [aeval_def, is_scalar_tower.algebra_map_eq R A B, ← eval₂_map, eval₂_hom, ← ring_hom.map_zero (algebra_map A B)] at hp', rw [aeval_def, eval₂_eq_eval_map], exact H hp', end /-- If `R → A → B` is an algebra tower, then if the entire tower is an integral extension so is `A → B` -/ lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p.map (algebra_map R A), ⟨monic_map (algebra_map R A) hp, _⟩⟩, rw [aeval_def, is_scalar_tower.algebra_map_eq R A B, ← eval₂_map] at hp', rw [aeval_def], exact hp', end end algebra theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] : integral_closure (integral_closure R A : set A) A = ⊥ := eq_bot_iff.2 $ λ x hx, algebra.mem_bot.2 ⟨⟨x, is_integral_trans integral_closure.is_integral _ hx⟩, rfl⟩ section integral_domain variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S] instance : integral_domain (integral_closure R S) := { exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.mp zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨a, ha⟩ ⟨b, hb⟩ h, or.imp subtype.ext_iff_val.mpr subtype.ext_iff_val.mpr (eq_zero_or_eq_zero_of_mul_eq_zero (subtype.ext_iff_val.mp h)), ..(integral_closure R S).comm_ring R S } end integral_domain
c80e80a5d9573d8a0cb54bb5f581a8a261e3a12e
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/OtherScarceResources.lean
09693911a5f64ced628d9b0961440dbacc0fc273
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
618
lean
-- OtherScarceResources /- [OtherScarceResources] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Efficient]. -/ import SystemModel.System inductive OtherScarceResources (sys_type: SystemType): Prop | intro : (exists otherScarceResources: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, otherScarceResources c p s st) -> OtherScarceResources
4cb1085816bf3b9a4980bd55aac1fc6cd0885e0e
4c630d016e43ace8c5f476a5070a471130c8a411
/group_theory/subgroup.lean
ac7eefa6a4b84e95b0e8d6c8997714e95263299a
[ "Apache-2.0" ]
permissive
ngamt/mathlib
9a510c391694dc43eec969914e2a0e20b272d172
58909bd424209739a2214961eefaa012fb8a18d2
refs/heads/master
1,585,942,993,674
1,540,739,585,000
1,540,916,815,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,113
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro -/ import group_theory.submonoid open set function variables {α : Type*} {β : Type*} {a a₁ a₂ b c: α} section group variables [group α] [add_group β] @[to_additive injective_add] lemma injective_mul {a : α} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ class is_subgroup (s : set α) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup (s : set β) extends is_add_submonoid s : Prop := (neg_mem {a} : a ∈ s → -a ∈ s) attribute [to_additive is_add_subgroup] is_subgroup attribute [to_additive is_add_subgroup.to_is_add_submonoid] is_subgroup.to_is_submonoid attribute [to_additive is_add_subgroup.neg_mem] is_subgroup.inv_mem attribute [to_additive is_add_subgroup.mk] is_subgroup.mk instance additive.is_add_subgroup (s : set α) [is_subgroup s] : @is_add_subgroup (additive α) _ s := ⟨@is_subgroup.inv_mem _ _ _ _⟩ theorem additive.is_add_subgroup_iff {s : set α} : @is_add_subgroup (additive α) _ s ↔ is_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk α _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ instance multiplicative.is_subgroup (s : set β) [is_add_subgroup s] : @is_subgroup (multiplicative β) _ s := ⟨@is_add_subgroup.neg_mem _ _ _ _⟩ theorem multiplicative.is_subgroup_iff {s : set β} : @is_subgroup (multiplicative β) _ s ↔ is_add_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk β _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ instance subtype.group {s : set α} [is_subgroup s] : group s := by subtype_instance instance subtype.add_group {s : set β} [is_add_subgroup s] : add_group s := by subtype_instance attribute [to_additive subtype.add_group] subtype.group @[simp, to_additive is_add_subgroup.coe_neg] lemma is_subgroup.coe_inv {s : set α} [is_subgroup s] (a : s) : ((a⁻¹ : s) : α) = a⁻¹ := rfl @[simp] lemma is_subgroup.coe_gpow {s : set α} [is_subgroup s] (a : s) (n : ℤ) : ((a ^ n : s) : α) = a ^ n := by induction n; simp [is_submonoid.coe_pow a] @[simp] lemma is_add_subgroup.gsmul_coe {β : Type*} [add_group β] {s : set β} [is_add_subgroup s] (a : s) (n : ℤ) : ((gsmul n a : s) : β) = gsmul n a := by induction n; simp [is_add_submonoid.smul_coe a] attribute [to_additive is_add_subgroup.gsmul_coe] is_subgroup.coe_gpow theorem is_subgroup.of_div (s : set α) (one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s): is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } theorem is_add_subgroup.of_sub (s : set β) (zero_mem : (0:β) ∈ s) (sub_mem : ∀{a b:β}, a ∈ s → b ∈ s → a - b ∈ s): is_add_subgroup s := multiplicative.is_subgroup_iff.1 $ @is_subgroup.of_div (multiplicative β) _ _ zero_mem @sub_mem def gpowers (x : α) : set α := {y | ∃i:ℤ, x^i = y} def gmultiples (x : β) : set β := {y | ∃i:ℤ, gsmul i x = y} attribute [to_additive gmultiples] gpowers instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } instance gmultiples.is_add_subgroup (x : β) : is_add_subgroup (gmultiples x) := multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _ attribute [to_additive gmultiples.is_add_subgroup] gpowers.is_subgroup lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma is_add_subgroup.gsmul_mem {a : β} {s : set β} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s := @is_subgroup.gpow_mem (multiplicative β) _ _ _ _ lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩ lemma mem_gmultiples {a : β} : a ∈ gmultiples a := ⟨1, by simp⟩ attribute [to_additive mem_gmultiples] mem_gpowers end group namespace is_subgroup open is_submonoid variables [group α] (s : set α) [is_subgroup s] @[to_additive is_add_subgroup.neg_mem_iff] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := ⟨λ h, by simpa using inv_mem h, inv_mem⟩ @[to_additive is_add_subgroup.add_mem_cancel_left] lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive is_add_subgroup.add_mem_cancel_right] lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ end is_subgroup theorem is_add_subgroup.sub_mem {α} [add_group α] (s : set α) [is_add_subgroup s] (a b : α) (ha : a ∈ s) (hb : b ∈ s) : a - b ∈ s := is_add_submonoid.add_mem ha (is_add_subgroup.neg_mem hb) namespace group open is_submonoid is_subgroup variables [group α] {s : set α} inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : α} : in_closure a → in_closure a⁻¹ | mul {a b : α} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := {a | in_closure s a } lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic instance closure.is_subgroup (s : set α) : is_subgroup (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } theorem subset_closure {s : set α} : s ⊆ closure s := λ a, mem_closure theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] lemma closure_subset_iff (s t : set α) [is_subgroup t] : closure s ⊆ t ↔ s ⊆ t := ⟨assume h b ha, h (mem_closure ha), assume h b ha, closure_subset h ha⟩ theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} := subset.antisymm (assume x h, match x, h with _, ⟨i, rfl⟩ := gpow_mem (mem_closure $ by simp) end) (closure_subset $ by simp [mem_gpowers]) end group namespace add_group open is_add_submonoid is_add_subgroup variables [add_group α] {s : set α} /-- `add_group.closure s` is the additive subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := @group.closure (multiplicative α) _ s attribute [to_additive add_group.closure] group.closure lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := group.mem_closure attribute [to_additive add_group.mem_closure] group.mem_closure instance closure.is_add_subgroup (s : set α) : is_add_subgroup (closure s) := multiplicative.is_subgroup_iff.1 $ group.closure.is_subgroup _ attribute [to_additive add_group.closure.is_add_subgroup] group.closure.is_subgroup attribute [to_additive add_group.subset_closure] group.subset_closure theorem closure_subset {s t : set α} [is_add_subgroup t] : s ⊆ t → closure s ⊆ t := group.closure_subset attribute [to_additive add_group.closure_subset] group.closure_subset attribute [to_additive add_group.closure_subset_iff] group.closure_subset_iff theorem gmultiples_eq_closure {a : α} : gmultiples a = closure {a} := group.gpowers_eq_closure attribute [to_additive add_group.gmultiples_eq_closure] group.gpowers_eq_closure end add_group class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s) class normal_add_subgroup [add_group α] (s : set α) extends is_add_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g + n - g ∈ s) attribute [to_additive normal_add_subgroup] normal_subgroup attribute [to_additive normal_add_subgroup.to_is_add_subgroup] normal_subgroup.to_is_subgroup attribute [to_additive normal_add_subgroup.normal] normal_subgroup.normal attribute [to_additive normal_add_subgroup.mk] normal_subgroup.mk @[to_additive normal_add_subgroup_of_add_comm_group] lemma normal_subgroup_of_comm_group [comm_group α] (s : set α) [hs : is_subgroup s] : normal_subgroup s := { normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul], ..hs } instance additive.normal_add_subgroup [group α] (s : set α) [normal_subgroup s] : @normal_add_subgroup (additive α) _ s := ⟨@normal_subgroup.normal _ _ _ _⟩ theorem additive.normal_add_subgroup_iff [group α] {s : set α} : @normal_add_subgroup (additive α) _ s ↔ normal_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_subgroup.mk α _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ instance multiplicative.normal_subgroup [add_group α] (s : set α) [normal_add_subgroup s] : @normal_subgroup (multiplicative α) _ s := ⟨@normal_add_subgroup.normal _ _ _ _⟩ theorem multiplicative.normal_subgroup_iff [add_group α] {s : set α} : @normal_subgroup (multiplicative α) _ s ↔ normal_add_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_add_subgroup.mk α _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ namespace is_subgroup variable [group α] -- Normal subgroup properties lemma mem_norm_comm {s : set α} [normal_subgroup s] {a b : α} (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h lemma mem_norm_comm_iff {s : set α} [normal_subgroup s] {a b : α} : a * b ∈ s ↔ b * a ∈ s := ⟨mem_norm_comm, mem_norm_comm⟩ /-- The trivial subgroup -/ def trivial (α : Type*) [group α] : set α := {1} @[simp] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 := mem_singleton_iff instance trivial_normal : normal_subgroup (trivial α) := by refine {..}; simp [trivial] {contextual := tt} lemma trivial_eq_closure : trivial α = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) instance univ_subgroup : normal_subgroup (@univ α) := by refine {..}; simp def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g} lemma mem_center {a : α} : a ∈ center α ↔ ∀g, g * a = a * g := iff.rfl instance center_normal : normal_subgroup (center α) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } end is_subgroup namespace is_add_subgroup variable [add_group α] attribute [to_additive is_add_subgroup.mem_norm_comm] is_subgroup.mem_norm_comm attribute [to_additive is_add_subgroup.mem_norm_comm_iff] is_subgroup.mem_norm_comm_iff /-- The trivial subgroup -/ def trivial (α : Type*) [add_group α] : set α := {0} attribute [to_additive is_add_subgroup.trivial] is_subgroup.trivial attribute [to_additive is_add_subgroup.mem_trivial] is_subgroup.mem_trivial instance trivial_normal : normal_add_subgroup (trivial α) := multiplicative.normal_subgroup_iff.1 is_subgroup.trivial_normal attribute [to_additive is_add_subgroup.trivial_normal] is_subgroup.trivial_normal attribute [to_additive is_add_subgroup.trivial_eq_closure] is_subgroup.trivial_eq_closure instance univ_add_subgroup : normal_add_subgroup (@univ α) := multiplicative.normal_subgroup_iff.1 is_subgroup.univ_subgroup attribute [to_additive is_add_subgroup.univ_add_subgroup] is_subgroup.univ_subgroup def center (α : Type*) [add_group α] : set α := {z | ∀ g, g + z = z + g} attribute [to_additive is_add_subgroup.center] is_subgroup.center attribute [to_additive is_add_subgroup.mem_center] is_subgroup.mem_center instance center_normal : normal_add_subgroup (center α) := multiplicative.normal_subgroup_iff.1 is_subgroup.center_normal end is_add_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup variables [group α] [group β] @[to_additive is_add_group_hom.ker] def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β) attribute [to_additive is_add_group_hom.ker.equations._eqn_1] ker.equations._eqn_1 @[to_additive is_add_group_hom.mem_ker] lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 := mem_trivial @[to_additive is_add_group_hom.zero_ker_neg] lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [mul f, inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end @[to_additive is_add_group_hom.neg_ker_zero] lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←inv f, ←mul f] at this @[to_additive is_add_group_hom.zero_iff_ker_neg] lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ @[to_additive is_add_group_hom.neg_iff_ker] lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, mul f]⟩, one_mem := ⟨1, one_mem s, one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw inv f; simp *⟩ } attribute [to_additive is_add_group_hom.image_add_subgroup._match_1] is_group_hom.image_subgroup._match_1 attribute [to_additive is_add_group_hom.image_add_subgroup._match_2] is_group_hom.image_subgroup._match_2 attribute [to_additive is_add_group_hom.image_add_subgroup._match_3] is_group_hom.image_subgroup._match_3 attribute [to_additive is_add_group_hom.image_add_subgroup] is_group_hom.image_subgroup attribute [to_additive is_add_group_hom.image_add_subgroup._match_1.equations._eqn_1] is_group_hom.image_subgroup._match_1.equations._eqn_1 attribute [to_additive is_add_group_hom.image_add_subgroup._match_2.equations._eqn_1] is_group_hom.image_subgroup._match_2.equations._eqn_1 attribute [to_additive is_add_group_hom.image_add_subgroup._match_3.equations._eqn_1] is_group_hom.image_subgroup._match_3.equations._eqn_1 attribute [to_additive is_add_group_hom.image_add_subgroup.equations._eqn_1] is_group_hom.image_subgroup.equations._eqn_1 instance range_subgroup (f : α → β) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ attribute [to_additive is_add_group_hom.range_add_subgroup] is_group_hom.range_subgroup attribute [to_additive is_add_group_hom.range_add_subgroup.equations._eqn_1] is_group_hom.range_subgroup.equations._eqn_1 local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [mul f, one f, inv f, @inv_mem β _ s] {contextual:=tt} attribute [to_additive is_add_group_hom.preimage] is_group_hom.preimage attribute [to_additive is_add_group_hom.preimage.equations._eqn_1] is_group_hom.preimage.equations._eqn_1 instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [mul f, inv f] {contextual:=tt}⟩ attribute [to_additive is_add_group_hom.preimage_normal] is_group_hom.preimage_normal attribute [to_additive is_add_group_hom.preimage_normal.equations._eqn_1] is_group_hom.preimage_normal.equations._eqn_1 instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial β) attribute [to_additive is_add_group_hom.normal_subgroup_ker] is_group_hom.normal_subgroup_ker attribute [to_additive is_add_group_hom.normal_subgroup_ker.equations._eqn_1] is_group_hom.normal_subgroup_ker.equations._eqn_1 lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) : function.injective f := begin intros a₁ a₂ hfa, simp [ext_iff, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) : ker f = trivial α := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.one f] {contextual := tt}) lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] : function.injective f ↔ ker f = trivial α := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ end is_group_hom
2d0d8860190b04f020a7797181d1187584a9c8bd
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/equiv/set.lean
c9771c9240018b95fe43c249470d225ad7eb51d4
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,017
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.basic import data.set.function /-! # Equivalences and sets In this file we provide lemmas linking equivalences to sets. Some notable definitions are: * `equiv.of_injective`: an injective function is (noncomputably) equivalent to its range. * `equiv.set_congr`: two equal sets are equivalent as types. * `equiv.set.union`: a disjoint union of sets is equivalent to their `sum`. This file is separate from `equiv/basic` such that we do not require the full lattice structure on sets before defining what an equivalence is. -/ open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} namespace equiv @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ := set.eq_univ_of_forall e.surjective protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv lemma _root_.set.mem_image_equiv {α β} {S : set α} {f : α ≃ β} {x : β} : x ∈ f '' S ↔ f.symm x ∈ S := set.ext_iff.mp (f.image_eq_preimage S) x /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.image_equiv_eq_preimage_symm {α β} (S : set α) (f : α ≃ β) : f '' S = f.symm ⁻¹' S := f.image_eq_preimage S /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.preimage_equiv_eq_image_symm {α β} (S : set α) (f : β ≃ α) : f ⁻¹' S = f.symm '' S := (f.symm.image_eq_preimage S).symm @[simp] protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : e.symm '' t ⊆ s ↔ t ⊆ e '' s := by rw [set.image_subset_iff, e.image_eq_preimage] @[simp] protected lemma subset_image' {α β} (e : α ≃ β) (s : set α) (t : set β) : s ⊆ e.symm '' t ↔ e '' s ⊆ t := calc s ⊆ e.symm '' t ↔ e.symm.symm '' s ⊆ t : by rw e.symm.subset_image ... ↔ e '' s ⊆ t : by rw e.symm_symm @[simp] lemma symm_image_image {α β} (e : α ≃ β) (s : set α) : e.symm '' (e '' s) = s := e.left_inverse_symm.image_image s lemma eq_image_iff_symm_image_eq {α β} (e : α ≃ β) (s : set α) (t : set β) : t = e '' s ↔ e.symm '' t = s := (e.symm.injective.image_injective.eq_iff' (e.symm_image_image s)).symm @[simp] lemma image_symm_image {α β} (e : α ≃ β) (s : set β) : e '' (e.symm '' s) = s := e.symm.symm_image_image s @[simp] lemma image_preimage {α β} (e : α ≃ β) (s : set β) : e '' (e ⁻¹' s) = s := e.surjective.image_preimage s @[simp] lemma preimage_image {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e '' s) = s := e.injective.preimage_image s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' sᶜ = (f '' s)ᶜ := set.image_compl_eq f.bijective @[simp] lemma symm_preimage_preimage {α β} (e : α ≃ β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.right_inverse_symm.preimage_preimage s @[simp] lemma preimage_symm_preimage {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e.symm ⁻¹' s) = s := e.left_inverse_symm.preimage_preimage s @[simp] lemma preimage_subset {α β} (e : α ≃ β) (s t : set β) : e ⁻¹' s ⊆ e ⁻¹' t ↔ s ⊆ t := e.surjective.preimage_subset_preimage_iff @[simp] lemma image_subset {α β} (e : α ≃ β) (s t : set α) : e '' s ⊆ e '' t ↔ s ⊆ t := set.image_subset_image_iff e.injective @[simp] lemma image_eq_iff_eq {α β} (e : α ≃ β) (s t : set α) : e '' s = e '' t ↔ s = t := set.image_eq_image e.injective lemma preimage_eq_iff_eq_image {α β} (e : α ≃ β) (s t) : e ⁻¹' s = t ↔ s = e '' t := set.preimage_eq_iff_eq_image e.bijective lemma eq_preimage_iff_image_eq {α β} (e : α ≃ β) (s t) : s = e ⁻¹' t ↔ e '' s = t := set.eq_preimage_iff_image_eq e.bijective lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} : equiv.prod_assoc α β γ ⁻¹' s.prod (t.prod u) = (s.prod t).prod u := by { ext, simp [and_assoc] } /-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/ def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) : s ≃ Σ x : α, {y | (x, y) ∈ s} := { to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩, inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩, left_inv := λ ⟨⟨x, y⟩, h⟩, rfl, right_inv := λ ⟨x, y, h⟩, rfl } /-- The subtypes corresponding to equal sets are equivalent. -/ @[simps apply] def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_equiv_prop h /-- A set is equivalent to its image under an equivalence. -/ -- We could construct this using `equiv.set.image e s e.injective`, -- but this definition provides an explicit inverse. @[simps] def image {α β : Type*} (e : α ≃ β) (s : set α) : s ≃ e '' s := { to_fun := λ x, ⟨e x.1, by simp⟩, inv_fun := λ y, ⟨e.symm y.1, by { rcases y with ⟨-, ⟨a, ⟨m, rfl⟩⟩⟩, simpa using m, }⟩, left_inv := λ x, by simp, right_inv := λ y, by simp, }. namespace set open set /-- `univ α` is equivalent to `α`. -/ @[simps apply symm_apply] protected def univ (α) : @univ α ≃ α := ⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ /-- An empty set is equivalent to the `empty` type. -/ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty _ /-- An empty set is equivalent to a `pempty` type. -/ protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty _ /-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x, or.inl x.2⟩ | (sum.inr x) := ⟨x, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } /-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg $ λ h, H ⟨h, ha⟩ @[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ := rfl @[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ := rfl /-- A singleton set is equivalent to a `punit` type. -/ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ /-- Equal sets are equivalent. -/ @[simps apply symm_apply] protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x, h ▸ x.2⟩, inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } /-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/ protected def insert {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.subset_def]) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) @[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ := rfl @[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ := rfl @[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl /-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/ protected def sum_compl {α} (s : set α) [decidable_pred (∈ s)] : s ⊕ (sᶜ : set α) ≃ α := calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : sᶜ) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } @[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : s} : (equiv.set.sum_compl s).symm x = sum.inl x := by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx @[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x := by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx /-- `sum_diff_subset s t` is the natural equivalence between `s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/ protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] : s ⊕ (t \ s : set α) ≃ t := calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) : (equiv.set.union (by simp [inter_diff_self])).symm ... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] }) @[simp] lemma sum_diff_subset_apply_inl {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl @[simp] lemma sum_diff_subset_apply_inr {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : t \ s) : equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl lemma sum_diff_subset_symm_apply_of_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∈ s) : (equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inl], exact subtype.eq rfl, end lemma sum_diff_subset_symm_apply_of_not_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∉ s) : (equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inr], exact subtype.eq rfl, end /-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent to `s ⊕ t`. -/ protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred (∈ s)] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } /-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences `e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences between `sᶜ` and `tᶜ`. -/ protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred (∈ s)] [decidable_pred (∈ t)] (e₀ : s ≃ t) : {e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) := { to_fun := λ e, subtype_equiv e (λ a, not_congr $ iff.symm $ maps_to.mem_iff (maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩) (surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2 ⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)), inv_fun := λ e₁, subtype.mk (calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm ... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁ ... ≃ β : set.sum_compl t) (λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply, set.sum_compl_apply_inl, set.sum_compl_symm_apply]), left_inv := λ e, begin ext x, by_cases hx : x ∈ s, { simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩, sum.map_inl, sum_congr_apply, trans_apply, subtype.coe_mk, set.sum_compl_apply_inl] }, { simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, trans_apply, sum_congr_apply, subtype.coe_mk] }, end, right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans, subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] } /-- The set product of two sets is equivalent to the type product of their coercions to types. -/ protected def prod {α β} (s : set α) (t : set β) : s.prod t ≃ s × t := @subtype_prod_equiv_prod α β s t /-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩, λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ /-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/ @[simps apply] protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (H.inj_on s) @[simp] protected lemma image_symm_apply {α β} (f : α → β) (s : set α) (H : injective f) (x : α) (h : x ∈ s) : (set.image f s H).symm ⟨f x, ⟨x, ⟨h, rfl⟩⟩⟩ = ⟨x, h⟩ := begin apply (set.image f s H).injective, simp [(set.image f s H).apply_symm_apply], end lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) : (λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) := begin ext ⟨b, a, has, rfl⟩, have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2, simp [equiv.set.image, equiv.set.image_of_inj_on, hf.eq_iff, this], end /-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/ @[simps] protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ /-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm /-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/ protected def powerset {α} (S : set α) : 𝒫 S ≃ set S := { to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α), inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩, left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩, right_inv := λ x, by ext; simp } /-- If `s` is a set in `range f`, then its image under `range_splitting f` is in bijection (via `f`) with `s`. -/ @[simps] noncomputable def range_splitting_image_equiv {α β : Type*} (f : α → β) (s : set (range f)) : range_splitting f '' s ≃ s := { to_fun := λ x, ⟨⟨f x, by simp⟩, (by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simpa [apply_range_splitting f] using m, })⟩, inv_fun := λ x, ⟨range_splitting f x, ⟨x, ⟨x.2, rfl⟩⟩⟩, left_inv := λ x, by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simp [apply_range_splitting f] }, right_inv := λ x, by simp [apply_range_splitting f], } end set /-- If `f : α → β` has a left-inverse when `α` is nonempty, then `α` is computably equivalent to the range of `f`. While awkward, the `nonempty α` hypothesis on `f_inv` and `hf` allows this to be used when `α` is empty too. This hypothesis is absent on analogous definitions on stronger `equiv`s like `linear_equiv.of_left_inverse` and `ring_equiv.of_left_inverse` as their typeclass assumptions are already sufficient to ensure non-emptiness. -/ @[simps] def of_left_inverse {α β : Sort*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : α ≃ set.range f := { to_fun := λ a, ⟨f a, a, rfl⟩, inv_fun := λ b, f_inv (nonempty_of_exists b.2) b, left_inv := λ a, hf ⟨a⟩ a, right_inv := λ ⟨b, a, ha⟩, subtype.eq $ show f (f_inv ⟨a⟩ b) = b, from eq.trans (congr_arg f $ by exact ha ▸ (hf _ a)) ha } /-- If `f : α → β` has a left-inverse, then `α` is computably equivalent to the range of `f`. Note that if `α` is empty, no such `f_inv` exists and so this definition can't be used, unlike the stronger but less convenient `of_left_inverse`. -/ abbreviation of_left_inverse' {α β : Sort*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : α ≃ set.range f := of_left_inverse f (λ _, f_inv) (λ _, hf) /-- If `f : α → β` is an injective function, then domain `α` is equivalent to the range of `f`. -/ @[simps apply] noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ set.range f := equiv.of_left_inverse f (λ h, by exactI function.inv_fun f) (λ h, by exactI function.left_inverse_inv_fun hf) theorem apply_of_injective_symm {α β} (f : α → β) (hf : injective f) (b : set.range f) : f ((of_injective f hf).symm b) = b := subtype.ext_iff.1 $ (of_injective f hf).apply_symm_apply b @[simp] theorem of_injective_symm_apply {α β} (f : α → β) (hf : injective f) (a : α) : (of_injective f hf).symm ⟨f a, ⟨a, rfl⟩⟩ = a := begin apply (of_injective f hf).injective, simp [apply_of_injective_symm f hf], end @[simp] lemma self_comp_of_injective_symm {α β} (f : α → β) (hf : injective f) : f ∘ ((of_injective f hf).symm) = coe := funext (λ x, apply_of_injective_symm f hf x) lemma of_left_inverse_eq_of_injective {α β : Type*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : of_left_inverse f f_inv hf = of_injective f ((em (nonempty α)).elim (λ h, (hf h).injective) (λ h _ _ _, by { haveI : subsingleton α := subsingleton_of_not_nonempty h, simp })) := by { ext, simp } lemma of_left_inverse'_eq_of_injective {α β : Type*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : of_left_inverse' f f_inv hf = of_injective f hf.injective := by { ext, simp } protected lemma set_forall_iff {α β} (e : α ≃ β) {p : set α → Prop} : (∀ a, p a) ↔ (∀ a, p (e ⁻¹' a)) := by simpa [equiv.image_eq_preimage] using (equiv.set.congr e).forall_congr_left' protected lemma preimage_sUnion {α β} (f : α ≃ β) {s : set (set β)} : f ⁻¹' (⋃₀ s) = ⋃₀ (_root_.set.image f ⁻¹' s) := by { ext x, simp [(equiv.set.congr f).symm.exists_congr_left] } end equiv /-- If a function is a bijection between two sets `s` and `t`, then it induces an equivalence between the types `↥s` and ``↥t`. -/ noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set α} {t : set β} (f : α → β) (h : set.bij_on f s t) : s ≃ t := equiv.of_bijective _ h.bijective /-- The composition of an updated function with an equiv on a subset can be expressed as an updated function. -/ lemma dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {s : set α} (e : β ≃ s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α] [∀ j, decidable (j ∈ s)] : (λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) = function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x := begin ext i, by_cases h : i ∈ s, { rw [dif_pos h, function.update_apply_equiv_apply, equiv.symm_symm, function.comp, function.update_apply, function.update_apply, dif_pos h], have h_coe : (⟨i, h⟩ : s) = e j ↔ i = e j := subtype.ext_iff.trans (by rw subtype.coe_mk), simp_rw h_coe, congr, }, { have : i ≠ e j, by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this }, simp [h, this] } end
73c601df959529a0971367c2e2e666fbd1ecc3ec
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/data/vector.lean
7a1eefc0e3c1c8cd09478bdb95d3ca1518ec01a8
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
4,588
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Tuples are lists of a fixed size. It is implemented as a subtype. -/ import data.list universes u v w def vector (α : Type u) (n : ℕ) := { l : list α // l.length = n } namespace vector variables {α : Type u} {β : Type v} {φ : Type w} variable {n : ℕ} instance [decidable_eq α] : decidable_eq (vector α n) := begin unfold vector, apply_instance end @[pattern] def nil : vector α 0 := ⟨[], rfl⟩ @[pattern] def cons : α → vector α n → vector α (nat.succ n) | a ⟨ v, h ⟩ := ⟨ a::v, congr_arg nat.succ h ⟩ @[reducible] def length (v : vector α n) : ℕ := n notation a :: b := cons a b notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l open nat def head : vector α (nat.succ n) → α | ⟨ [], h ⟩ := by contradiction | ⟨ a :: v, h ⟩ := a theorem head_cons (a : α) : Π (v : vector α n), head (a :: v) = a | ⟨ l, h ⟩ := rfl def tail : vector α n → vector α (n - 1) | ⟨ [], h ⟩ := ⟨ [], congr_arg pred h ⟩ | ⟨ a :: v, h ⟩ := ⟨ v, congr_arg pred h ⟩ theorem tail_cons (a : α) : Π (v : vector α n), tail (a :: v) = v | ⟨ l, h ⟩ := rfl @[simp] theorem cons_head_tail : ∀ v : vector α (succ n), (head v :: tail v) = v | ⟨ [], h ⟩ := by contradiction | ⟨ a :: v, h ⟩ := rfl def to_list (v : vector α n) : list α := v.1 def nth : Π (v : vector α n), fin n → α | ⟨ l, h ⟩ i := l.nth_le i.1 (by rw h; exact i.2) def append {n m : nat} : vector α n → vector α m → vector α (n + m) | ⟨ l₁, h₁ ⟩ ⟨ l₂, h₂ ⟩ := ⟨ l₁ ++ l₂, by simp_using_hs ⟩ @[elab_as_eliminator] def elim {α} {C : Π {n}, vector α n → Sort u} (H : ∀l : list α, C ⟨l, rfl⟩) {n : nat} : Π (v : vector α n), C v | ⟨l, h⟩ := match n, h with ._, rfl := H l end /- map -/ def map (f : α → β) : vector α n → vector β n | ⟨ l, h ⟩ := ⟨ list.map f l, by simp_using_hs ⟩ @[simp] lemma map_nil (f : α → β) : map f nil = nil := rfl lemma map_cons (f : α → β) (a : α) : Π (v : vector α n), map f (a::v) = f a :: map f v | ⟨l,h⟩ := rfl def map₂ (f : α → β → φ) : vector α n → vector β n → vector φ n | ⟨ x, _ ⟩ ⟨ y, _ ⟩ := ⟨ list.map₂ f x y, by simp_using_hs ⟩ def repeat (a : α) (n : ℕ) : vector α n := ⟨ list.repeat a n, list.length_repeat a n ⟩ def dropn (i : ℕ) : vector α n → vector α (n - i) | ⟨l, p⟩ := ⟨ list.dropn i l, by simp_using_hs ⟩ def taken (i : ℕ) : vector α n → vector α (min i n) | ⟨l, p⟩ := ⟨ list.taken i l, by simp_using_hs ⟩ def remove_nth (i : fin n) : vector α n → vector α (n - 1) | ⟨l, p⟩ := ⟨ list.remove_nth l i.1, by rw[l.length_remove_nth i.1]; rw p; exact i.2 ⟩ def of_fn : Π {n}, (fin n → α) → vector α n | 0 f := [] | (n+1) f := f 0 :: of_fn (λi, f i.succ) section accum open prod variable {σ : Type} def map_accumr (f : α → σ → σ × β) : vector α n → σ → σ × vector β n | ⟨ x, px ⟩ c := let res := list.map_accumr f x c in ⟨ res.1, res.2, by simp_using_hs ⟩ def map_accumr₂ {α β σ φ : Type} (f : α → β → σ → σ × φ) : vector α n → vector β n → σ → σ × vector φ n | ⟨ x, px ⟩ ⟨ y, py ⟩ c := let res := list.map_accumr₂ f x y c in ⟨ res.1, res.2, by simp_using_hs ⟩ end accum protected lemma eq {n : ℕ} : ∀ (a1 a2 : vector α n), to_list a1 = to_list a2 → a1 = a2 | ⟨x, h1⟩ ⟨._, h2⟩ rfl := rfl protected theorem eq_nil (v : vector α 0) : v = [] := v.eq [] (list.eq_nil_of_length_eq_zero v.2) @[simp] lemma to_list_mk (v : list α) (P : list.length v = n) : to_list (subtype.mk v P) = v := rfl @[simp] lemma to_list_nil : to_list [] = @list.nil α := rfl @[simp] lemma to_list_length (v : vector α n) : (to_list v).length = n := v.2 @[simp] lemma to_list_cons (a : α) (v : vector α n) : to_list (a :: v) = a :: to_list v := begin cases v, reflexivity end @[simp] lemma to_list_append {n m : nat} (v : vector α n) (w : vector α m) : to_list (append v w) = to_list v ++ to_list w := begin cases v, cases w, reflexivity end @[simp] lemma to_list_dropn {n m : ℕ} (v : vector α m) : to_list (dropn n v) = list.dropn n (to_list v) := begin cases v, reflexivity end @[simp] lemma to_list_taken {n m : ℕ} (v : vector α m) : to_list (taken n v) = list.taken n (to_list v) := begin cases v, reflexivity end end vector
3c8c8c38eaa2e0c05bd9b073f5f7ec2798121de0
d1bbf1801b3dcb214451d48214589f511061da63
/src/data/equiv/basic.lean
4352e1303f303624c44842262c070c456b8eba0c
[ "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
88,084
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.set.function /-! # Equivalence between types In this file we define two types: * `equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and not equality!) to express that various `Type`s or `Sort`s are equivalent. * `equiv.perm α`: the group of permutations `α ≃ α`. More lemmas about `equiv.perm` can be found in `group_theory/perm`. Then we define * canonical isomorphisms between various types: e.g., - `equiv.refl α` is the identity map interpreted as `α ≃ α`; - `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β` and the sigma-type `Σ b : bool, cond b α β`; - `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum satisfy the distributive law up to a canonical equivalence; * operations on equivalences: e.g., - `equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`; - `equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order of the arguments!); - `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and `eb : β₁ ≃ β₂` using `prod.map`. * definitions that transfer some instances along an equivalence. By convention, we transfer instances from right to left. - `equiv.inhabited` takes `e : α ≃ β` and `[inhabited β]` and returns `inhabited α`; - `equiv.unique` takes `e : α ≃ β` and `[unique β]` and returns `unique α`; - `equiv.decidable_eq` takes `e : α ≃ β` and `[decidable_eq β]` and returns `decidable_eq α`. More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance` does it for many algebraic type classes like `group`, `module`, etc. ## Tags equivalence, congruence, bijective map -/ open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ @[nolint has_inhabited_instance] structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) infix ` ≃ `:25 := equiv /-- Convert an involutive function `f` to an equivalence with `to_fun = inv_fun = f`. -/ def function.involutive.to_equiv (f : α → α) (h : involutive f) : α ≃ α := ⟨f, f, h.left_inverse, h.right_inverse⟩ namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl /-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/ theorem injective_coe_fn : function.injective (λ (e : α ≃ β) (x : α), e x) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from l₁.eq_right_inverse (this.symm ▸ r₂), by simp * @[simp, norm_cast] protected lemma coe_inj {e₁ e₂ : α ≃ β} : ⇑e₁ = e₂ ↔ e₁ = e₂ := injective_coe_fn.eq_iff @[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g := injective_coe_fn (funext H) protected lemma congr_arg {f : equiv α β} : Π {x x' : α}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : equiv α β} (h : f = g) (x : α) : f x = g x := h ▸ rfl lemma ext_iff {f g : equiv α β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ @[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext H protected lemma perm.congr_arg {f : equiv.perm α} {x x' : α} : x = x' → f x = f x' := equiv.congr_arg protected lemma perm.congr_fun {f g : equiv.perm α} (h : f = g) (x : α) : f x = g x := equiv.congr_fun h x lemma perm.ext_iff {σ τ : equiv.perm α} : σ = τ ↔ ∀ x, σ x = τ x := ext_iff /-- Any type is equivalent to itself. -/ @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ instance inhabited' : inhabited (α ≃ α) := ⟨equiv.refl α⟩ /-- Inverse of an equivalence `e : α ≃ β`. -/ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ /-- See Note [custom simps projection] -/ def simps.inv_fun (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ @[simp] lemma to_fun_as_coe (e : α ≃ β) : e.to_fun = e := rfl @[simp] lemma inv_fun_as_coe (e : α ≃ β) : e.inv_fun = e.symm := rfl protected theorem injective (e : α ≃ β) : injective e := e.left_inv.injective protected theorem surjective (e : α ≃ β) : surjective e := e.right_inv.surjective protected theorem bijective (f : α ≃ β) : bijective f := ⟨f.injective, f.surjective⟩ @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ := set.eq_univ_of_forall e.surjective protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α := e.injective.subsingleton protected theorem subsingleton.symm (e : α ≃ β) [subsingleton α] : subsingleton β := e.symm.injective.subsingleton instance equiv_subsingleton_cod [subsingleton β] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, subsingleton.elim _ _⟩ instance equiv_subsingleton_dom [subsingleton α] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, @subsingleton.elim _ (equiv.subsingleton.symm f) _ _⟩ instance perm_subsingleton [subsingleton α] : subsingleton (perm α) := equiv.equiv_subsingleton_cod lemma perm.subsingleton_eq_refl [subsingleton α] (e : perm α) : e = equiv.refl α := subsingleton.elim _ _ /-- Transfer `decidable_eq` across an equivalence. -/ protected def decidable_eq (e : α ≃ β) [decidable_eq β] : decidable_eq α := e.injective.decidable_eq lemma nonempty_iff_nonempty (e : α ≃ β) : nonempty α ↔ nonempty β := nonempty.congr e e.symm /-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/ protected def inhabited [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ /-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/ protected def unique [unique β] (e : α ≃ β) : unique α := e.symm.surjective.unique /-- Equivalence between equal types. -/ protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl @[simp] theorem perm.coe_subsingleton {α : Type*} [subsingleton α] (e : perm α) : ⇑(e) = id := by rw [perm.subsingleton_eq_refl e, coe_refl] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x := e.right_inv x @[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl -- The `simp` attribute is needed to make this a `dsimp` lemma. -- `simp` will always rewrite with `equiv.symm_symm` before this has a chance to fire. @[simp, nolint simp_nf] theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl @[simp] theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y := f.injective.eq_iff theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) {x : α} {y : β} : f x = y ↔ x = f.symm y := begin conv_lhs { rw ←apply_symm_apply f y, }, rw apply_eq_iff_eq, end @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl } @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl } @[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl } @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv /-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ` is equivalent to the type of equivalences `β ≃ δ`. -/ def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩ @[simp] lemma equiv_congr_refl {α β} : (equiv.refl α).equiv_congr (equiv.refl β) = equiv.refl (α ≃ β) := by { ext, refl } @[simp] lemma equiv_congr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (ab.equiv_congr cd).symm = ab.symm.equiv_congr cd.symm := by { ext, refl } @[simp] lemma equiv_congr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) : (ab.equiv_congr de).trans (bc.equiv_congr ef) = (ab.trans bc).equiv_congr (de.trans ef) := by { ext, refl } @[simp] lemma equiv_congr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) : (equiv.refl α).equiv_congr bg e = e.trans bg := rfl @[simp] lemma equiv_congr_refl_right {α β} (ab e : α ≃ β) : ab.equiv_congr (equiv.refl β) e = ab.symm.trans e := rfl @[simp] lemma equiv_congr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) : ab.equiv_congr cd e x = cd (e (ab.symm x)) := rfl /-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e lemma perm_congr_def {α β : Type*} (e : α ≃ β) (p : equiv.perm α) : e.perm_congr p = (e.symm.trans p).trans e := rfl @[simp] lemma perm_congr_symm {α β : Type*} (e : α ≃ β) : e.perm_congr.symm = e.symm.perm_congr := rfl @[simp] lemma perm_congr_apply {α β : Type*} (e : α ≃ β) (p : equiv.perm α) (x) : e.perm_congr p x = e (p (e.symm x)) := rfl lemma perm_congr_symm_apply {α β : Type*} (e : α ≃ β) (p : equiv.perm β) (x) : e.perm_congr.symm p x = e.symm (p (e x)) := rfl protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] @[simp] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by { rw [← set.image_comp], simp } @[simp] lemma image_preimage {α β} (e : α ≃ β) (s : set β) : e '' (e ⁻¹' s) = s := e.surjective.image_preimage s @[simp] lemma preimage_image {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e '' s) = s := set.preimage_image_eq s e.injective protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' sᶜ = (f '' s)ᶜ := set.image_compl_eq f.bijective /-- If `α` is an empty type, then it is equivalent to the `empty` type. -/ def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ /-- `false` is equivalent to `empty`. -/ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id /-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/ def {u' v'} equiv_pempty {α : Sort v'} (h : α → false) : α ≃ pempty.{u'} := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ /-- `false` is equivalent to `pempty`. -/ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id /-- `empty` is equivalent to `pempty`. -/ def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ /-- `pempty` types from any two universes are equivalent. -/ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim /-- If `α` is not `nonempty`, then it is equivalent to `empty`. -/ def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ /-- If `α` is not `nonempty`, then it is equivalent to `pempty`. -/ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ /-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ /-- `true` is equivalent to `punit`. -/ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial /-- `ulift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def ulift {α : Type v} : ulift.{u} α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ /-- `plift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ /-- equivalence of propositions is the same as iff -/ def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q := { to_fun := h.mp, inv_fun := h.mpr, left_inv := λ x, rfl, right_inv := λ y, rfl } /-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁` is equivalent to the type of maps `α₂ → β₂`. -/ @[congr, simps apply] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := { to_fun := λ f, e₂ ∘ f ∘ e₁.symm, inv_fun := λ f, e₂.symm ∘ f ∘ e₁, left_inv := λ f, funext $ λ x, by simp, right_inv := λ f, funext $ λ x, by simp } lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) := by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] } @[simp] lemma arrow_congr_refl {α β : Sort*} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := rfl @[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := rfl /-- A version of `equiv.arrow_congr` in `Type`, rather than `Sort`. The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`, because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`. -/ @[congr, simps apply] def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := equiv.arrow_congr hα hβ @[simp] lemma arrow_congr'_refl {α β : Type*} : arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') := rfl @[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm := rfl /-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/ @[simps apply] def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e @[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl @[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl -- This should not be a simp lemma as long as `(∘)` is reducible: -- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using -- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination. lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) := by apply arrow_congr_comp section binary_op variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp instance [is_associative α₁ f] : is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_associative_right e.surjective instance [is_idempotent α₁ f] : is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_idempotent_right e.surjective instance [is_left_cancel α₁ f] : is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩ instance [is_right_cancel α₁ f] : is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩ end binary_op /-- `punit` sorts in any two universes are equivalent. -/ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩ section /-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/ def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩ /-- The sort of maps from `punit` is equivalent to the codomain. -/ def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by { ext ⟨⟩, refl }, λ u, rfl⟩ /-- The sort of maps from `true` is equivalent to the codomain. -/ def true_arrow_equiv (α : Sort*) : (true → α) ≃ α := ⟨λ f, f trivial, λ a u, a, λ f, by { ext ⟨⟩, refl }, λ u, rfl⟩ /-- The sort of maps from `empty` is equivalent to `punit`. -/ def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ /-- The sort of maps from `pempty` is equivalent to `punit`. -/ def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ /-- The sort of maps from `false` is equivalent to `punit`. -/ def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end /-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/ @[congr, simps apply] def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩ @[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm := rfl /-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/ @[simps apply] def prod_comm (α β : Type*) : α × β ≃ β × α := ⟨prod.swap, prod.swap, λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl /-- Type product is associative up to an equivalence. -/ @[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, (p.1.1, p.1.2, p.2), λp, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} : equiv.prod_assoc α β γ ⁻¹' s.prod (t.prod u) = (s.prod t).prod u := by { ext, simp [and_assoc] } section /-- `punit` is a right identity for type product up to an equivalence. -/ @[simps apply] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ /-- `punit` is a left identity for type product up to an equivalence. -/ @[simps apply] def punit_prod (α : Type*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ /-- `empty` type is a right absorbing element for type product up to an equivalence. -/ def prod_empty (α : Type*) : α × empty ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) /-- `empty` type is a left absorbing element for type product up to an equivalence. -/ def empty_prod (α : Type*) : empty × α ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) /-- `pempty` type is a right absorbing element for type product up to an equivalence. -/ def prod_pempty (α : Type*) : α × pempty ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) /-- `pempty` type is a left absorbing element for type product up to an equivalence. -/ def pempty_prod (α : Type*) : pempty × α ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum /-- `psum` is equivalent to `sum`. -/ def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/ @[simps apply] def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ := ⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩ @[simp] lemma sum_congr_trans {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} (e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) : (equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) := by { ext i, cases i; refl } @[simp] lemma sum_congr_symm {α β γ δ : Sort*} (e : α ≃ β) (f : γ ≃ δ) : (equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) := rfl @[simp] lemma sum_congr_refl {α β : Sort*} : equiv.sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := by { ext i, cases i; refl } namespace perm /-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/ @[reducible] def sum_congr {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) : equiv.perm (α ⊕ β) := equiv.sum_congr ea eb @[simp] lemma sum_congr_apply {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) (x : α ⊕ β) : sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x @[simp] lemma sum_congr_trans {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) (g : equiv.perm α) (h : equiv.perm β) : (sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) := equiv.sum_congr_trans e f g h @[simp] lemma sum_congr_symm {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) : (sum_congr e f).symm = sum_congr (e.symm) (f.symm) := equiv.sum_congr_symm e f @[simp] lemma sum_congr_refl {α β : Sort*} : sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := equiv.sum_congr_refl end perm /-- `bool` is equivalent the sum of two `punit`s. -/ def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ /-- `Prop` is noncomputably equivalent to `bool`. -/ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ /-- Sum of types is commutative up to an equivalence. -/ @[simps apply] def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α := ⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩ @[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl /-- Sum of types is associative up to an equivalence. -/ def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr), sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr, by rintros (⟨_ | _⟩ | _); refl, by rintros (_ | ⟨_ | _⟩); refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl /-- Sum with `empty` is equivalent to the original type. -/ def sum_empty (α : Type*) : α ⊕ empty ≃ α := ⟨sum.elim id (empty.rec _), inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] lemma sum_empty_apply_inl {α} (a) : sum_empty α (sum.inl a) = a := rfl /-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/ def empty_sum (α : Sort*) : empty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] lemma empty_sum_apply_inr {α} (a) : empty_sum α (sum.inr a) = a := rfl /-- Sum with `pempty` is equivalent to the original type. -/ def sum_pempty (α : Type*) : α ⊕ pempty ≃ α := ⟨sum.elim id (pempty.rec _), inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] lemma sum_pempty_apply_inl {α} (a) : sum_pempty α (sum.inl a) = a := rfl /-- The sum of `pempty` with any `Sort*` is equivalent to the right summand. -/ def pempty_sum (α : Sort*) : pempty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] lemma pempty_sum_apply_inr {α} (a) : pempty_sum α (sum.inr a) = a := rfl /-- `option α` is equivalent to `α ⊕ punit` -/ def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ @[simp] lemma option_equiv_sum_punit_none {α} : option_equiv_sum_punit α none = sum.inr punit.star := rfl @[simp] lemma option_equiv_sum_punit_some {α} (a) : option_equiv_sum_punit α (some a) = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_coe {α} (a : α) : option_equiv_sum_punit α a = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_symm_inl {α} (a) : (option_equiv_sum_punit α).symm (sum.inl a) = a := rfl @[simp] lemma option_equiv_sum_punit_symm_inr {α} (a) : (option_equiv_sum_punit α).symm (sum.inr a) = none := rfl /-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/ def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α := { to_fun := λ o, option.get o.2, inv_fun := λ x, ⟨some x, dec_trivial⟩, left_inv := λ o, subtype.eq $ option.some_get _, right_inv := λ x, option.get_some _ _ } /-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `α` and `β` to be types from the same universe, so it cannot by used directly to transfer theorems about sigma types to theorems about sum types. In many cases one can use `ulift` to work around this difficulty. -/ def sum_equiv_sigma_bool (α β : Type u) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, s.elim (λ x, ⟨tt, x⟩) (λ x, ⟨ff, x⟩), λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ /-- `sigma_preimage_equiv f` for `f : α → β` is the natural equivalence between the type of all fibres of `f` and the total space `α`. -/ @[simps] def sigma_preimage_equiv {α β : Type*} (f : α → β) : (Σ y : β, {x // f x = y}) ≃ α := ⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩ /-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/ def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) : s ≃ Σ x : α, {y | (x, y) ∈ s} := { to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩, inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩, left_inv := λ ⟨⟨x, y⟩, h⟩, rfl, right_inv := λ ⟨x, y, h⟩, rfl } end section sum_compl /-- For any predicate `p` on `α`, the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}` is naturally equivalent to `α`. -/ def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] : {a // p a} ⊕ {a // ¬ p a} ≃ α := { to_fun := sum.elim coe coe, inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩, left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], }, right_inv := λ a, by { dsimp, split_ifs; refl } } @[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // p a}) : sum_compl p (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // ¬ p a}) : sum_compl p (sum.inr x) = x := rfl @[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : p a) : (sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h @[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : ¬ p a) : (sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h end sum_compl section subtype_preimage variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β) /-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`, the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/ @[simps] def subtype_preimage : {x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) := { to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a, inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩, funext $ λ ⟨a, h⟩, dif_pos h⟩, left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a, (by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }), right_inv := λ x, funext $ λ ⟨a, h⟩, show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } } lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) : ((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ := dif_pos h lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) : ((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ := dif_neg h end subtype_preimage section fun_unique variables (α β) [unique α] /-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/ @[simps] def fun_unique : (α → β) ≃ β := { to_fun := λ f, f (default α), inv_fun := λ b a, b, left_inv := λ f, funext $ λ a, congr_arg f $ subsingleton.elim _ _, right_inv := λ b, rfl } end fun_unique section /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ /-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent to the type of dependent functions of two arguments (i.e., functions to the space of functions). -/ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := λ f x y, f ⟨x,y⟩, inv_fun := λ f x, f x.1 x.2, left_inv := λ f, funext $ λ ⟨x,y⟩, rfl, right_inv := λ f, funext $ λ x, funext $ λ y, rfl } end section /-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/ @[simps apply symm_apply] def psigma_equiv_sigma {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i, β i := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and `Σ a, β₂ a`. -/ @[simps apply] def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a := ⟨λ a, ⟨a.1, F a.1 a.2⟩, λ a, ⟨a.1, (F a.1).symm a.2⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ @[simp] lemma sigma_congr_right_trans {α} {β₁ β₂ β₃ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) (G : Π a, β₂ a ≃ β₃ a) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_symm {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := by { ext1 x, cases x, refl } namespace perm /-- A family of permutations `Π a, perm (β a)` generates a permuation `perm (Σ a, β₁ a)`. -/ @[reducible] def sigma_congr_right {α} {β : α → Sort*} (F : Π a, perm (β a)) : perm (Σ a, β a) := equiv.sigma_congr_right F @[simp] lemma sigma_congr_right_trans {α} {β : α → Sort*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := equiv.sigma_congr_right_trans F G @[simp] lemma sigma_congr_right_symm {α} {β : α → Sort*} (F : Π a, perm (β a)) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := equiv.sigma_congr_right_symm F @[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := equiv.sigma_congr_right_refl end perm /-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/ @[simps apply] def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} (e : α₁ ≃ α₂) : (Σ a:α₁, β (e a)) ≃ (Σ a:α₂, β a) := ⟨λ a, ⟨e a.1, a.2⟩, λ a, ⟨e.symm a.1, @@eq.rec β a.2 (e.right_inv a.1).symm⟩, λ ⟨a, b⟩, match e.symm (e a), e.left_inv a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ e) _ (@@eq.rec β b (congr_arg e h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match e (e.symm a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ /-- Transporting a sigma type through an equivalence of the base -/ def sigma_congr_left' {α₁ α₂} {β : α₁ → Sort*} (f : α₁ ≃ α₂) : (Σ a:α₁, β a) ≃ (Σ a:α₂, β (f.symm a)) := (sigma_congr_left f.symm).symm /-- Transporting a sigma type through an equivalence of the base and a family of equivalences of matching fibers -/ def sigma_congr {α₁ α₂} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} (f : α₁ ≃ α₂) (F : ∀ a, β₁ a ≃ β₂ (f a)) : sigma β₁ ≃ sigma β₂ := (sigma_congr_right F).trans (sigma_congr_left f) /-- `sigma` type with a constant fiber is equivalent to the product. -/ @[simps apply symm_apply] def sigma_equiv_prod (α β : Type*) : (Σ_:α, β) ≃ α × β := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type is equivalent to the product. -/ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : Π a, β₁ a ≃ β) : sigma β₁ ≃ α × β := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section prod_congr variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂) /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `β₁ × α₁` and `β₂ × α₁`. -/ def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ := { to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩, inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) : prod_congr_left e (b, a) = (e a b, a) := rfl lemma prod_congr_refl_right (e : β₁ ≃ β₂) : prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `α₁ × β₁` and `α₁ × β₂`. -/ def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ := { to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩, inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) : prod_congr_right e (a, b) = (a, e a b) := rfl lemma prod_congr_refl_left (e : β₁ ≃ β₂) : prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_left_trans_prod_comm : (prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_right_trans_prod_comm : (prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_congr_right_sigma_equiv_prod : (sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) = (sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_equiv_prod_sigma_congr_right : (sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) = (prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm := by { ext ⟨a, b⟩ : 1, simp } /-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend on the first component. A typical example is a shear mapping, explaining the name of this declaration. -/ @[simps {fully_applied := ff}] def prod_shear {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := { to_fun := λ x : α₁ × β₁, (e₁ x.1, e₂ x.1 x.2), inv_fun := λ y : α₂ × β₂, (e₁.symm y.1, (e₂ $ e₁.symm y.1).symm y.2), left_inv := by { rintro ⟨x₁, y₁⟩, simp only [symm_apply_apply] }, right_inv := by { rintro ⟨x₁, y₁⟩, simp only [apply_symm_apply] } } end prod_congr namespace perm variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁) /-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to `(a, e b)` and keeping the other `(a', b)` fixed. -/ def prod_extend_right : perm (α₁ × β₁) := { to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab, inv_fun := λ ab, if ab.fst = a then (a, e.symm ab.snd) else ab, left_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] }, right_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] } } @[simp] lemma prod_extend_right_apply_eq (b : β₁) : prod_extend_right a e (a, b) = (a, e b) := if_pos rfl lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) : prod_extend_right a e (a', b) = (a', b) := if_neg h lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁} (h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a := by { contrapose! h, exact prod_extend_right_apply_ne _ h _ } @[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) : (prod_extend_right a e ab).fst = ab.fst := begin rw [prod_extend_right, coe_fn_mk], split_ifs with h, { rw h }, { refl } end end perm section /-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions `γ → α` and `γ → β`. -/ def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ /-- Functions `α → β → γ` are equivalent to functions on `α × β`. -/ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨uncurry, curry, curry_uncurry, uncurry_curry⟩ open sum /-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions on `α` and on `β`. -/ def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p, sum.elim p.1 p.2, λ f, by { ext ⟨⟩; refl }, λ p, by { cases p, refl }⟩ /-- Type product is right distributive with respect to type sum up to an equivalence. -/ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl q := (inl q.1, q.2) | inr q := (inr q.1, q.2) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl /-- Type product is left distributive with respect to type sum up to an equivalence. -/ def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl /-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is equivalent to the sum of products `Σ i, (α i × β)`. -/ def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) : ((Σ i, α i) × β) ≃ (Σ i, (α i × β)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, λ p, (⟨p.1, p.2.1⟩, p.2.2), λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ /-- The product `bool × α` is equivalent to `α ⊕ α`. -/ def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (unit × α) ⊕ (unit × α) : sum_prod_distrib _ _ _ ... ≃ α ⊕ α : sum_congr (punit_prod _) (punit_prod _) /-- The function type `bool → α` is equivalent to `α × α`. -/ def bool_to_equiv_prod (α : Type u) : (bool → α) ≃ α × α := calc (bool → α) ≃ ((unit ⊕ unit) → α) : (arrow_congr bool_equiv_punit_sum_punit (equiv.refl α)) ... ≃ (unit → α) × (unit → α) : sum_arrow_equiv_prod_arrow _ _ _ ... ≃ α × α : prod_congr (punit_arrow_equiv _) (punit_arrow_equiv _) @[simp] lemma bool_to_equiv_prod_apply {α : Type u} (f : bool → α) : bool_to_equiv_prod α f = (f ff, f tt) := rfl @[simp] lemma bool_to_equiv_prod_symm_apply_ff {α : Type u} (p : α × α) : (bool_to_equiv_prod α).symm p ff = p.1 := rfl @[simp] lemma bool_to_equiv_prod_symm_apply_tt {α : Type u} (p : α × α) : (bool_to_equiv_prod α).symm p tt = p.2 := rfl end section open sum nat /-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/ def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ /-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/ def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm /-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/ def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end /-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/ def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β := { to_fun := list.map e, inv_fun := list.map e.symm, left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id], right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] } /-- `fin n` is equivalent to `{m // m < n}`. -/ def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ /-- If `α` is equivalent to `β`, then `unique α` is equivalent to `β`. -/ def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := λ h, @equiv.unique _ _ h e.symm, inv_fun := λ h, @equiv.unique _ _ h e, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } section open subtype /-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. -/ def subtype_congr {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := ⟨λ x, ⟨e x, (h _).1 x.2⟩, λ y, ⟨e.symm y, (h _).2 (by { simp, exact y.2 })⟩, λ ⟨x, h⟩, subtype.ext_val $ by simp, λ ⟨y, h⟩, subtype.ext_val $ by simp⟩ @[simp] lemma subtype_congr_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) : e.subtype_congr h x = ⟨e x, (h _).1 x.2⟩ := rfl @[simp] lemma subtype_congr_symm_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) (y : {y // q y}) : (e.subtype_congr h).symm y = ⟨e.symm y, (h _).2 $ (e.apply_symm_apply y).symm ▸ y.2⟩ := rfl /-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to `{x // q x}`. -/ @[simps] def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} := subtype_congr (equiv.refl _) e /-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent to the subtype `{b // p b}`. -/ def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) : {a : α // p (e a)} ≃ {b : β // p b} := subtype_congr e $ by simp /-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/ def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := e.symm.subtype_equiv_of_subtype.symm /-- If two predicates are equal, then the corresponding subtypes are equivalent. -/ def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_congr (equiv.refl α) (assume a, h ▸ iff.rfl) /-- The subtypes corresponding to equal sets are equivalent. -/ @[simps apply] def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_congr_prop h /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This version allows the “inner” predicate to depend on `h : p a`. -/ def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/ def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) : {x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_congr_right $ λ x, exists_prop /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_congr_right $ assume x, ⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩ /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) : subtype p ≃ α := ⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ ⟨⟨x, h⟩, y⟩, rfl, λ ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : subtype q, p x) ≃ Σ x : α, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2 /-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then `Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/ def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : subtype p, {x : α // f x = y}) ≃ α := calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x) ... ≃ α : sigma_preimage_equiv f /-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent to `{x // p x}`. -/ def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : subtype q, {x : α // f x = y}) ≃ subtype p := calc (Σ y : subtype q, {x : α // f x = y}) ≃ Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_congr_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) /-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the `sigma` type such that for all `i` we have `(f i).fst = i`. -/ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ /-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent to the set of functions `Π a, {b : β a // p a b}`. -/ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.ext_val rfl }⟩ /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} : {c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) := ⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩ end section subtype_equiv_codomain variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X} /-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x` is equivalent to the codomain `Y`. -/ def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y := (subtype_preimage _ f).trans $ @fun_unique {x' // ¬ x' ≠ x} _ $ show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _ (show unique {x' // x' = x}, from { default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h }) (subtype_congr_right $ λ a, not_not) @[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : (subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl @[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y) (g : {g : X → Y // g ∘ coe = f}) : subtype_equiv_codomain f g = (g : X → Y) x := rfl lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) : ((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) = λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y, by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl @[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) : ((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y := rfl @[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) : ((subtype_equiv_codomain f).symm y : X → Y) x = y := dif_neg (not_not.mpr rfl) lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) : ((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ := dif_pos h end subtype_equiv_codomain namespace set open set /-- `univ α` is equivalent to `α`. -/ @[simps apply symm_apply] protected def univ (α) : @univ α ≃ α := ⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ /-- An empty set is equivalent to the `empty` type. -/ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h /-- An empty set is equivalent to a `pempty` type. -/ protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h /-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x, or.inl x.2⟩ | (sum.inr x) := ⟨x, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } /-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg $ λ h, H ⟨h, ha⟩ @[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ := rfl @[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ := rfl -- TODO: Any reason to use the same universe? /-- A singleton set is equivalent to a `punit` type. -/ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ /-- Equal sets are equivalent. -/ @[simps apply symm_apply] protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x, h ▸ x.2⟩, inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } /-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/ protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.subset_def]) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) @[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) (b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ := rfl @[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) (b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ := rfl @[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) (b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl /-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/ protected def sum_compl {α} (s : set α) [decidable_pred s] : s ⊕ (sᶜ : set α) ≃ α := calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : sᶜ) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } @[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred s] {x : s} : (equiv.set.sum_compl s).symm x = sum.inl x := by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx @[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α} [decidable_pred s] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x := by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx /-- `sum_diff_subset s t` is the natural equivalence between `s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/ protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred s] : s ⊕ (t \ s : set α) ≃ t := calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) : (equiv.set.union (by simp [inter_diff_self])).symm ... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] }) @[simp] lemma sum_diff_subset_apply_inl {α} {s t : set α} (h : s ⊆ t) [decidable_pred s] (x : s) : equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl @[simp] lemma sum_diff_subset_apply_inr {α} {s t : set α} (h : s ⊆ t) [decidable_pred s] (x : t \ s) : equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl lemma sum_diff_subset_symm_apply_of_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred s] {x : t} (hx : x.1 ∈ s) : (equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inl], exact subtype.eq rfl, end lemma sum_diff_subset_symm_apply_of_not_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred s] {x : t} (hx : x.1 ∉ s) : (equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inr], exact subtype.eq rfl, end /-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent to `s ⊕ t`. -/ protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } /-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences `e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences between `sᶜ` and `tᶜ`. -/ protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred s] [decidable_pred t] (e₀ : s ≃ t) : {e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) := { to_fun := λ e, subtype_congr e (λ a, not_congr $ iff.symm $ maps_to.mem_iff (maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩) (surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2 ⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)), inv_fun := λ e₁, subtype.mk (calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm ... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁ ... ≃ β : set.sum_compl t) (λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply, set.sum_compl_apply_inl, set.sum_compl_symm_apply]), left_inv := λ e, begin ext x, by_cases hx : x ∈ s, { simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩, sum.map_inl, sum_congr_apply, trans_apply, subtype.coe_mk, set.sum_compl_apply_inl] }, { simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr, subtype_congr_apply, set.sum_compl_apply_inr, trans_apply, sum_congr_apply, subtype.coe_mk] }, end, right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_congr_apply, set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans, subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] } /-- The set product of two sets is equivalent to the type product of their coercions to types. -/ protected def prod {α β} (s : set α) (t : set β) : s.prod t ≃ s × t := @subtype_prod_equiv_prod α β s t /-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩, λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ /-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/ @[simps apply] protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (H.inj_on s) lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) : (λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) := begin ext ⟨b, a, has, rfl⟩, have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2, simp [equiv.set.image, equiv.set.image_of_inj_on, hf, this], end /-- If `f : α → β` is an injective function, then `α` is equivalent to the range of `f`. -/ @[simps apply] protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := { to_fun := λ x, ⟨f x, mem_range_self _⟩, inv_fun := λ x, classical.some x.2, left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)), right_inv := λ x, subtype.eq $ classical.some_spec x.2 } theorem apply_range_symm {α β} (f : α → β) (H : injective f) (b : range f) : f ((set.range f H).symm b) = b := begin conv_rhs { rw ←((set.range f H).right_inv b), }, simp, end /-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/ protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ /-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm /-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/ protected def powerset {α} (S : set α) : 𝒫 S ≃ set S := { to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α), inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩, left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩, right_inv := λ x, by ext; simp } end set /-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/ @[simps apply] noncomputable def of_bijective {α β} (f : α → β) (hf : bijective f) : α ≃ β := (equiv.set.range f hf.1).trans $ (set_congr hf.2.range_eq).trans $ equiv.set.univ β lemma of_bijective_apply_symm_apply {α β} (f : α → β) (hf : bijective f) (x : β) : f ((of_bijective f hf).symm x) = x := (of_bijective f hf).apply_symm_apply x @[simp] lemma of_bijective_symm_apply_apply {α β} (f : α → β) (hf : bijective f) (x : α) : (of_bijective f hf).symm (f x) = x := (of_bijective f hf).symm_apply_apply x /-- If `f` is an injective function, then its domain is equivalent to its range. -/ @[simps apply] noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ _root_.set.range f := of_bijective (λ x, ⟨f x, set.mem_range_self x⟩) ⟨λ x y hxy, hf $ by injections, λ ⟨_, x, rfl⟩, ⟨x, rfl⟩⟩ /-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`. Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/ def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } section swap variable [decidable_eq α] /-- A helper function for `equiv.swap`. -/ def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ @[simp] theorem swap_self (a : α) : swap a a = equiv.refl _ := ext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := ext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases h : b = a; simp [swap_apply_def, h], } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := ext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } lemma swap_eq_update (i j : α) : ⇑(equiv.swap i j) = update (update id j i) i j := funext $ λ x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def] lemma comp_swap_eq_update (i j : α) (f : α → β) : f ∘ equiv.swap i j = update (update f j (f i)) i (f j) := by rw [swap_eq_update, comp_update, comp_update, comp.right_id] @[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma trans_swap_trans_symm [decidable_eq β] (a b : β) (e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) := symm_trans_swap_trans a b e.symm @[simp] lemma swap_apply_self (i j a : α) : swap i j (swap i j a) = a := by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply] /-- A function is invariant to a swap if it is equal at both elements -/ lemma apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k := begin by_cases hi : k = i, { rw [hi, swap_apply_left, hv] }, by_cases hj : k = j, { rw [hj, swap_apply_right, hv] }, rw swap_apply_of_ne_of_ne hi hj, end namespace perm @[simp] lemma sum_congr_swap_refl {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : α) : equiv.perm.sum_congr (equiv.swap i j) (equiv.refl β) = equiv.swap (sum.inl i) (sum.inl j) := begin ext x, cases x, { simp [sum.map, swap_apply_def], split_ifs; refl}, { simp [sum.map, swap_apply_of_ne_of_ne] }, end @[simp] lemma sum_congr_refl_swap {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : β) : equiv.perm.sum_congr (equiv.refl α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := begin ext x, cases x, { simp [sum.map, swap_apply_of_ne_of_ne] }, { simp [sum.map, swap_apply_def], split_ifs; refl}, end end perm /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap protected lemma exists_unique_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∃! x, p x) ↔ ∃! y, q y := begin split, { rintro ⟨a, ha₁, ha₂⟩, exact ⟨f a, h.1 ha₁, λ b hb, f.symm_apply_eq.1 (ha₂ (f.symm b) (h.2 (by simpa using hb)))⟩ }, { rintro ⟨b, hb₁, hb₂⟩, exact ⟨f.symm b, h.2 (by simpa using hb₁), λ y hy, (eq_symm_apply f).2 (hb₂ _ (h.1 hy))⟩ } end protected lemma exists_unique_congr_left' {p : α → Prop} (f : α ≃ β) : (∃! x, p x) ↔ (∃! y, p (f.symm y)) := equiv.exists_unique_congr f (λx, by simp) protected lemma exists_unique_congr_left {p : β → Prop} (f : α ≃ β) : (∃! x, p (f x)) ↔ (∃! y, p y) := (equiv.exists_unique_congr_left' f.symm).symm protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) := begin split; intros h₂ x, { rw [←f.right_inv x], apply h.mp, apply h₂ }, apply h.mpr, apply h₂ end protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) := (equiv.forall_congr f.symm (λ x, h.symm)).symm -- We next build some higher arity versions of `equiv.forall_congr`. -- Although they appear to just be repeated applications of `equiv.forall_congr`, -- unification of metavariables works better with these versions. -- In particular, they are necessary in `equiv_rw`. -- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics, -- it's rare to have axioms involving more than 3 elements at once.) universes ua1 ua2 ub1 ub2 ug1 ug2 variables {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {γ₁ : Sort ug1} {γ₂ : Sort ug2} protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) : (∀x y, p x y) ↔ (∀x y, q x y) := begin apply equiv.forall_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) : (∀x y, p x y) ↔ (∀x y, q x y) := (equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := begin apply equiv.forall₂_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := (equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) : (∀x, p x) ↔ (∀y, p (f.symm y)) := equiv.forall_congr f (λx, by simp) protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) : (∀x, p (f x)) ↔ (∀y, p y) := (equiv.forall_congr_left' f.symm).symm section variables (P : α → Sort w) (e : α ≃ β) /-- Transport dependent functions through an equivalence of the base space. -/ @[simps] def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) := { to_fun := λ f x, f (e.symm x), inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end, left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { dsimp, rw e.symm_apply_apply })), right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { rw e.apply_symm_apply })) } end section variables (P : β → Sort w) (e : α ≃ β) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) := (Pi_congr_left' P e.symm).symm end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a))) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibers. -/ def Pi_congr : (Π a, W a) ≃ (Π b, Z b) := (equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁) end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) := (Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm end end equiv lemma function.injective.swap_apply [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := begin by_cases hx : z = x, by simp [hx], by_cases hy : z = y, by simp [hy], rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)] end lemma function.injective.swap_comp [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := funext $ λ z, hf.swap_apply _ _ _ instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq /-- If both `α` and `β` are singletons, then `α ≃ β`. -/ def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` is a singleton, then it is equivalent to any `punit`. -/ def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique /-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/ def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α := { to_fun := λ p, p.1, inv_fun := λ a, (a, a), left_inv := λ p, subsingleton.elim _ _, right_inv := λ p, subsingleton.elim _ _, } /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β] (f : α → β) (g : β → α) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- `unique (unique α)` is equivalent to `unique α`. -/ def unique_unique_equiv : unique (unique α) ≃ unique α := equiv_of_subsingleton_of_subsingleton (λ h, h.default) (λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }) namespace quot /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : quot ra ≃ quot rb := { to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1), inv_fun := quot.map e.symm (assume b₁ b₂ h, (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)), left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] }, right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } } /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : quot r ≃ quot r' := quot.congr (equiv.refl α) eq /-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α` by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/ protected def congr_left {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := @quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply]) end quot namespace quotient /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) : quotient ra ≃ quotient rb := quot.congr e eq /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : setoid α} (eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' := quot.congr_right eq end quotient /-- If a function is a bijection between two sets `s` and `t`, then it induces an equivalence between the the types `↥s` and ``↥t`. -/ noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set α} {t : set β} (f : α → β) (h : set.bij_on f s t) : s ≃ t := equiv.of_bijective _ h.bijective namespace function lemma update_comp_equiv {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) : update f a v ∘ g = update (f ∘ g) (g.symm a) v := by rw [←update_comp _ g.injective, g.apply_symm_apply] lemma update_apply_equiv_apply {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') : update f a v (g a') = update (f ∘ g) (g.symm a) v a' := congr_fun (update_comp_equiv f g a v) a' end function /-- The composition of an updated function with an equiv on a subset can be expressed as an updated function. -/ lemma dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {s : set α} (e : β ≃ s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α] [∀ j, decidable (j ∈ s)] : (λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) = function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x := begin ext i, by_cases h : i ∈ s, { rw [dif_pos h, function.update_apply_equiv_apply, equiv.symm_symm, function.comp, function.update_apply, function.update_apply, dif_pos h], have h_coe : (⟨i, h⟩ : s) = e j ↔ i = e j := subtype.ext_iff.trans (by rw subtype.coe_mk), simp_rw h_coe, congr, }, { have : i ≠ e j, by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this }, simp [h, this] } end
55c8de70cc85ee8cfe967d8daad6c8a7f4085cb6
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/polynomial/field_division.lean
ee8b817bbe288afc856bf2b9c7102638185a32ae
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,754
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import algebra.gcd_monoid.basic import data.polynomial.derivative import data.polynomial.ring_division import data.set.pairwise import ring_theory.coprime.lemmas import ring_theory.euclidean_domain /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section integral_domain variables [comm_ring R] [integral_domain R] [normalization_monoid R] instance : normalization_monoid (polynomial R) := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : polynomial R} : (norm_unit p : polynomial R) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : polynomial R) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp end integral_domain section field variables [field R] {p q : polynomial R} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, begin rw [eq_C_of_degree_le_zero h] at hp0 hp, exact hp (is_unit.map (C.to_monoid_hom : R →* _) (is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))), end) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] theorem irreducible_of_monic {p : polynomial R} (hp1 : p.monic) (hp2 : p ≠ 1) : irreducible p ↔ (∀ f g : polynomial R, f.monic → g.monic → f * g = p → f = 1 ∨ g = 1) := ⟨λ hp3 f g hf hg hfg, or.cases_on (hp3.is_unit_or_is_unit hfg.symm) (assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf) (assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug), λ hp3, ⟨mt (eq_one_of_is_unit_of_monic hp1) hp2, λ f g hp, have hf : f ≠ 0, from λ hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 }, have hg : g ≠ 0, from λ hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 }, or.imp (λ hf, is_unit_of_mul_eq_one _ _ hf) (λ hg, is_unit_of_mul_eq_one _ _ hg) $ hp3 (f * C f.leading_coeff⁻¹) (g * C g.leading_coeff⁻¹) (monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $ by rw [mul_assoc, mul_left_comm _ g, ← mul_assoc, ← C_mul, ← mul_inv₀, ← leading_coeff_mul, ← hp, monic.def.1 hp1, inv_one, C_1, mul_one]⟩⟩ /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [field k] {f : R →+* k} {p : polynomial R} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [f.map_inv, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← f.map_inv, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : polynomial R} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : polynomial R} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← gcd_is_unit_iff, ← gcd_is_unit_iff, gcd_map, is_unit_map] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, f.map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp lemma mem_roots_map [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := begin rw mem_roots (show p.map f ≠ 0, by exact map_ne_zero hp), dsimp only [is_root], rw polynomial.eval_map, end lemma mem_root_set [field k] [algebra R k] {x : k} (hp : p ≠ 0) : x ∈ p.root_set k ↔ aeval x p = 0 := iff.trans multiset.mem_to_finset (mem_roots_map hp) lemma root_set_C_mul_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := begin ext x, rw [set.mem_singleton_iff, mem_root_set, aeval_mul, aeval_C, aeval_X_pow, mul_eq_zero], { simp_rw [ring_hom.map_eq_zero, pow_eq_zero_iff (nat.pos_of_ne_zero hn), or_iff_right_iff_imp], exact λ ha', (ha ha').elim }, { exact mul_ne_zero (mt C_eq_zero.mp ha) (pow_ne_zero n X_ne_zero) }, end lemma root_set_monomial {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [←C_mul_X_pow_eq_monomial, root_set_C_mul_X_pow hn ha] lemma root_set_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : polynomial R).root_set S = {0} := by { rw [←one_mul (X ^ n : polynomial R), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial R)) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := by simp [hp] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : polynomial R} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff (polynomial R), normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← f.map_inv, ← map_C, ← map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from monic.prime_of_degree_eq_one (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), (normalize_associated _).prime this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := (prime_of_degree_eq_one hp1).irreducible theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on (λ i : I, polynomial.X - polynomial.C (s i))) := λ i j hij, have h : s j - s i ≠ 0, from sub_ne_zero_of_ne $ function.injective.ne H hij.symm, ⟨polynomial.C (s j - s i)⁻¹, -polynomial.C (s j - s i)⁻¹, by rw [neg_mul_eq_neg_mul_symm, ← sub_eq_add_neg, ← mul_sub, sub_sub_sub_cancel_left, ← polynomial.C_sub, ← polynomial.C_mul, inv_mul_cancel h, polynomial.C_1]⟩ /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end lemma prod_multiset_root_eq_finset_root {p : polynomial R} (hzero : p ≠ 0) : (multiset.map (λ (a : R), X - C a) p.roots).prod = ∏ a in (multiset.to_finset p.roots), (λ (a : R), (X - C a) ^ (root_multiplicity a p)) a := by simp only [count_roots hzero, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : polynomial R) : (multiset.map (λ (a : R), X - C a) p.roots).prod ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, is_unit_one, multiset.prod_zero, multiset.map_zero, is_unit.dvd] }, rw prod_multiset_root_eq_finset_root hp0, have hcoprime : pairwise (is_coprime on λ (a : R), polynomial.X - C (id a)) := pairwise_coprime_X_sub function.injective_id, have H : pairwise (is_coprime on λ (a : R), (polynomial.X - C (id a)) ^ (root_multiplicity a p)), { intros a b hdiff, exact (hcoprime a b hdiff).pow }, apply finset.prod_dvd_of_coprime (pairwise.pairwise_on H (↑(multiset.to_finset p.roots) : set R)), intros a h, rw multiset.mem_to_finset at h, exact pow_root_multiplicity_dvd p a end lemma roots_C_mul (p : polynomial R) {a : R} (hzero : a ≠ 0) : (C a * p).roots = p.roots := begin by_cases hpzero : p = 0, { simp only [hpzero, mul_zero] }, rw multiset.ext, intro b, have prodzero : C a * p ≠ 0, { simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] }, rw [count_roots hpzero, count_roots prodzero, root_multiplicity_mul prodzero], have mulzero : root_multiplicity b (C a) = 0, { simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] }, simp only [mulzero, zero_add] end lemma roots_normalize : (normalize p).roots = p.roots := begin by_cases hzero : p = 0, { rw [hzero, normalize_zero], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, rw [normalize_apply, mul_comm, coe_norm_unit_of_ne_zero hzero, roots_C_mul _ (inv_ne_zero hcoeff)], }, end end field end polynomial
2fa79abba8f280630955feec55287ee69ccfc98b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/order/basic.lean
f6b3f7c08e713ec038aa0f16160eb39e913fc858
[ "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
28,258
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import logic.basic data.sum data.set.basic algebra.order open function /- TODO: automatic construction of dual definitions / theorems -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} lemma antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _ instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _ instance [preorder α] : is_strict_order α (<) := {} instance [preorder α] : is_strict_order α (>) := {} instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin resetI, cases A, cases B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := preorder.ext H; cases A; cases B; injection this; congr' theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := partial_order.ext H; cases A; cases B; injection this; congr' /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } end monotone /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.linear_order α } instance : Π [inhabited α], inhabited (order_dual α) := id end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone def preorder.lift {α β} (f : α → β) (i : preorder β) : preorder α := by exactI { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } def partial_order.lift {α β} (f : α → β) (inj : injective f) (i : partial_order β) : partial_order α := by exactI { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f (by apply_instance) } def linear_order.lift {α β} (f : α → β) (inj : injective f) (i : linear_order β) : linear_order α := by exactI { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj (by apply_instance) } def decidable_linear_order.lift {α β} (f : α → β) (inj : injective f) (i : decidable_linear_order β) : decidable_linear_order α := by exactI { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj (by apply_instance) } instance subtype.preorder {α} [i : preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val i instance subtype.partial_order {α} [i : partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective i instance subtype.linear_order {α} [i : linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective i instance subtype.decidable_linear_order {α} [i : decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val subtype.val_injective i instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /- additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@dense α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ lemma trans_trichotomous_left [is_trans α r] [is_trichotomous α r] {a b c : α} : ¬r b a → r b c → r a c := begin intros h₁ h₂, rcases trichotomous_of r a b with h₃|h₃|h₃, exact trans h₃ h₂, rw h₃, exact h₂, exfalso, exact h₁ h₃ end lemma trans_trichotomous_right [is_trans α r] [is_trichotomous α r] {a b c : α} : r a b → ¬r c b → r a c := begin intros h₁ h₂, rcases trichotomous_of r b c with h₃|h₃|h₃, exact trans h₁ h₃, rw ←h₃, exact h₁, exfalso, exact h₂ h₃ end variables {s : β → β → Prop} {t : γ → γ → Prop} theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } section prio set_option default_priority 100 -- see Note [default priority] /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. end prio /-- Construct a linear order from a `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, ..partial_order_of_SO r } /-- Construct a decidable linear order from a `is_strict_total_order'` relation -/ def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α := by letI LO := linear_order_of_STO' r; exact { decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x), ..LO } noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_irrefl_of_is_asymm α r _ } @[priority 100] -- see Note [lower instance priority] instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ @[priority 100] -- see Note [lower instance priority] instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) @[priority 100] -- see Note [lower instance priority] instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) end prio @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance noncomputable def decidable_linear_order_of_is_well_order (r : α → α → Prop) [is_well_order α r] : decidable_linear_order α := by { haveI := linear_order_of_STO' r, exact classical.DLO α } instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf is_well_order.wf is_well_order.wf } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ (trans ab bc) }, { exact prod.lex.left _ _ ab }, { exact prod.lex.left _ _ bc }, { exact prod.lex.right _ (trans ab bc) } end, wf := prod.lex_wf is_well_order.wf is_well_order.wf } /-- An unbounded or cofinal set -/ def unbounded (r : α → α → Prop) (s : set α) : Prop := ∀ a, ∃ b ∈ s, ¬ r b a /-- A bounded or final set -/ def bounded (r : α → α → Prop) (s : set α) : Prop := ∃a, ∀ b ∈ s, r b a @[simp] lemma not_bounded_iff {r : α → α → Prop} (s : set α) : ¬bounded r s ↔ unbounded r s := begin classical, simp only [bounded, unbounded, not_forall, not_exists, exists_prop, not_and, not_not] end @[simp] lemma not_unbounded_iff {r : α → α → Prop} (s : set α) : ¬unbounded r s ↔ bounded r s := by { classical, rw [not_iff_comm, not_bounded_iff] } namespace well_founded /-- If `r` is a well founded relation, then any nonempty set has a minimum element with respect to `r`. -/ theorem has_min {α} {r : α → α → Prop} (H : well_founded r) (s : set α) : s.nonempty → ∃ a ∈ s, ∀ x ∈ s, ¬ r x a | ⟨a, ha⟩ := (acc.rec_on (H.apply a) $ λ x _ IH, classical.not_imp_not.1 $ λ hne hx, hne $ ⟨x, hx, λ y hy hyx, hne $ IH y hyx hy⟩) ha /-- The minimum element of a nonempty set in a well-founded order -/ noncomputable def min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) : α := classical.some (H.has_min p h) theorem min_mem {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) : H.min p h ∈ p := let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h theorem not_lt_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) {x} (xp : x ∈ p) : ¬ r x (H.min p h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp open set protected noncomputable def sup {α} {r : α → α → Prop} (wf : well_founded r) (s : set α) (h : bounded r s) : α := wf.min { x | ∀a ∈ s, r a x } h protected lemma lt_sup {α} {r : α → α → Prop} (wf : well_founded r) {s : set α} (h : bounded r s) {x} (hx : x ∈ s) : r x (wf.sup s h) := min_mem wf { x | ∀a ∈ s, r a x } h x hx section open_locale classical protected noncomputable def succ {α} {r : α → α → Prop} (wf : well_founded r) (x : α) : α := if h : ∃y, r x y then wf.min { y | r x y } h else x protected lemma lt_succ {α} {r : α → α → Prop} (wf : well_founded r) {x : α} (h : ∃y, r x y) : r x (wf.succ x) := by { rw [well_founded.succ, dif_pos h], apply min_mem } end protected lemma lt_succ_iff {α} {r : α → α → Prop} [wo : is_well_order α r] {x : α} (h : ∃y, r x y) (y : α) : r y (wo.wf.succ x) ↔ r y x ∨ y = x := begin split, { intro h', have : ¬r x y, { intro hy, rw [well_founded.succ, dif_pos] at h', exact wo.wf.not_lt_min _ h hy h' }, rcases trichotomous_of r x y with hy | hy | hy, exfalso, exact this hy, right, exact hy.symm, left, exact hy }, rintro (hy | rfl), exact trans hy (wo.wf.lt_succ h), exact wo.wf.lt_succ h end end well_founded variable (r) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) theorem directed_on_image {s} {f : β → α} : directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s := by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage] theorem directed_on.mono {s : set α} (h : directed_on r s) {r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) : directed_on r' s := λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩ theorem directed_comp {ι} (f : ι → β) (g : β → α) : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl variable {r} theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) : directed rb (g ∘ f) := (directed_comp rb f g).2 $ hf.mono hg section prio set_option default_priority 100 -- see Note [default priority] class directed_order (α : Type u) extends preorder α := (directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k) end prio
4ee00b605a9c1e9adcaeacfb26000c71574e40c5
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/analysis/normed_space/real_inner_product.lean
2ad029a04da2c9a37904e731d8220b4f5b7f638c
[ "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
50,726
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel -/ import algebra.quadratic_discriminant import linear_algebra.bilinear_form import tactic.apply_fun import tactic.monotonicity import topology.metric_space.pi_Lp /-! # Inner Product Space This file defines real inner product space and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. ## Main statements Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. ## Implementation notes We decide to develop the theory of real inner product spaces and that of complex inner product spaces separately. ## Tags inner product space, norm, orthogonal projection ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open real set open_locale big_operators open_locale classical open_locale topological_space universes u v w variables {α : Type u} {F : Type v} {G : Type w} /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (α : Type*) := (inner : α → α → ℝ) export has_inner (inner) section prio set_option default_priority 100 -- see Note [default priority] -- the norm is embedded in the inner product space structure -- to avoid definitional equality issues. See Note [forgetful inheritance]. /-- An inner product space is a real vector space with an additional operation called inner product. Inner product spaces over complex vector space will be defined in another file. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that it is equal to `sqrt (inner x x)` to be able to put instances on `ℝ` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (α : Type*) extends normed_group α, normed_space ℝ α, has_inner α := (norm_eq_sqrt_inner : ∀ (x : α), ∥x∥ = sqrt (inner x x)) (comm : ∀ x y, inner x y = inner y x) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = r * inner x y) end prio /-! ### Constructing a normed space structure from a scalar product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (F : Type*) [add_comm_group F] [semimodule ℝ F] := (inner : F → F → ℝ) (comm : ∀ x y, inner x y = inner y x) (nonneg : ∀ x, 0 ≤ inner x x) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = r * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [semimodule ℝ F] [c : inner_product_space.core F] include c /-- Inner product constructed from an `inner_product_space.core` structure -/ def to_has_inner : has_inner F := { inner := c.inner } local attribute [instance] to_has_inner lemma inner_comm (x y : F) : inner x y = inner y x := c.comm x y lemma inner_add_left (x y z : F) : inner (x + y) z = inner x z + inner y z := c.add_left _ _ _ lemma inner_add_right (x y z : F) : inner x (y + z) = inner x y + inner x z := by { rw [inner_comm, inner_add_left], simp [inner_comm] } lemma inner_smul_left (x y : F) (r : ℝ) : inner (r • x) y = r * inner x y := c.smul_left _ _ _ lemma inner_smul_right (x y : F) (r : ℝ) : inner x (r • y) = r * inner x y := by { rw [inner_comm, inner_smul_left, inner_comm] } /-- Norm constructed from an `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (inner x x) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (inner x x) := rfl lemma inner_self_eq_norm_square (x : F) : inner x x = ∥x∥ * ∥x∥ := (mul_self_sqrt (c.nonneg _)).symm /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self (x y : F) : inner (x + y) (x + y) = inner x x + 2 * inner x y + inner y y := by simpa [inner_add_left, inner_add_right, two_mul, add_assoc] using inner_comm _ _ /-- Cauchy–Schwarz inequality -/ lemma inner_mul_inner_self_le (x y : F) : inner x y * inner x y ≤ inner x x * inner y y := begin have : ∀ t, 0 ≤ inner y y * t * t + 2 * inner x y * t + inner x x, from assume t, calc 0 ≤ inner (x+t•y) (x+t•y) : c.nonneg _ ... = inner y y * t * t + 2 * inner x y * t + inner x x : by { simp only [inner_add_add_self, inner_smul_right, inner_smul_left], ring }, have := discriminant_le_zero this, rw discrim at this, have h : (2 * inner x y)^2 - 4 * inner y y * inner x x = 4 * (inner x y * inner x y - inner x x * inner y y) := by ring, rw h at this, linarith end /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs (inner x y) ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin rw abs_mul_abs_self, have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = inner x x * inner y y, simp only [inner_self_eq_norm_square], ring, rw this, exact inner_mul_inner_self_le _ _ end /-- Normed group structure constructed from an `inner_product_space.core` structure. -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { assume h, rw [norm_eq_sqrt_inner, sqrt_eq_zero] at h, { exact c.definite x h }, { exact c.nonneg x } }, { rintros rfl, have : inner ((0 : ℝ) • (0 : F)) 0 = 0 * inner (0 : F) 0 := inner_smul_left _ _ _, simp at this, simp [norm, this] } end, norm_neg := assume x, begin have A : (- (1 : ℝ)) • x = -x, by simp, rw [norm_eq_sqrt_inner, norm_eq_sqrt_inner, ← A, inner_smul_left, inner_smul_right], simp, end, triangle := assume x y, begin have := calc ∥x + y∥ * ∥x + y∥ = inner (x + y) (x + y) : by rw inner_self_eq_norm_square ... = inner x x + 2 * inner x y + inner y y : inner_add_add_self _ _ ... ≤ inner x x + 2 * (∥x∥ * ∥y∥) + inner y y : by linarith [abs_inner_le_norm x y, le_abs_self (inner x y)] ... = (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥) : by { simp only [inner_self_eq_norm_square], ring }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end } local attribute [instance] to_normed_group /-- Normed space structure constructed from an `inner_product_space.core` structure. -/ def to_normed_space : normed_space ℝ F := { norm_smul_le := assume r x, le_of_eq $ begin have A : 0 ≤ ∥r∥ * ∥x∥ := mul_nonneg (abs_nonneg _) (sqrt_nonneg _), rw [norm_eq_sqrt_inner, sqrt_eq_iff_mul_self_eq _ A, inner_smul_left, inner_smul_right, inner_self_eq_norm_square], { calc abs(r) * ∥x∥ * (abs(r) * ∥x∥) = (abs(r) * abs(r)) * (∥x∥ * ∥x∥) : by ring ... = r * (r * (∥x∥ * ∥x∥)) : by { rw abs_mul_abs_self, ring } }, { exact c.nonneg _ } end } end inner_product_space.of_core /-- Given an `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product. -/ def inner_product_space.of_core [add_comm_group F] [semimodule ℝ F] (c : inner_product_space.core F) : inner_product_space F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group F _ _ c, letI : normed_space ℝ F := @inner_product_space.of_core.to_normed_space F _ _ c, exact { norm_eq_sqrt_inner := λ x, rfl, .. c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space α] export inner_product_space (norm_eq_sqrt_inner) section basic_properties lemma inner_comm (x y : α) : inner x y = inner y x := inner_product_space.comm x y lemma inner_add_left {x y z : α} : inner (x + y) z = inner x z + inner y z := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : α} : inner x (y + z) = inner x y + inner x z := by { rw [inner_comm, inner_add_left], simp [inner_comm] } lemma inner_smul_left {x y : α} {r : ℝ} : inner (r • x) y = r * inner x y := inner_product_space.smul_left _ _ _ lemma inner_smul_right {x y : α} {r : ℝ} : inner x (r • y) = r * inner x y := by { rw [inner_comm, inner_smul_left, inner_comm] } variables (α) /-- The inner product as a bilinear form. -/ def bilin_form_of_inner : bilin_form ℝ α := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } variables {α} /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → α) (x : α) : inner (∑ i in s, f i) x = ∑ i in s, inner (f i) x := bilin_form.map_sum_left (bilin_form_of_inner α) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → α) (x : α) : inner x (∑ i in s, f i) = ∑ i in s, inner x (f i) := bilin_form.map_sum_right (bilin_form_of_inner α) _ _ _ @[simp] lemma inner_zero_left {x : α} : inner 0 x = 0 := by { rw [← zero_smul ℝ (0:α), inner_smul_left, zero_mul] } @[simp] lemma inner_zero_right {x : α} : inner x 0 = 0 := by { rw [inner_comm, inner_zero_left] } @[simp] lemma inner_self_eq_zero {x : α} : inner x x = 0 ↔ x = 0 := ⟨λ h, by simpa [h] using norm_eq_sqrt_inner x, λ h, by simp [h]⟩ lemma inner_self_nonneg {x : α} : 0 ≤ inner x x := begin classical, by_cases h : x = 0, { simp [h] }, { have : 0 < sqrt (inner x x), { rw ← norm_eq_sqrt_inner, exact norm_pos_iff.mpr h }, exact le_of_lt (sqrt_pos.1 this) } end @[simp] lemma inner_self_nonpos {x : α} : inner x x ≤ 0 ↔ x = 0 := ⟨λ h, inner_self_eq_zero.1 (le_antisymm h inner_self_nonneg), λ h, h.symm ▸ le_of_eq inner_zero_left⟩ @[simp] lemma inner_neg_left {x y : α} : inner (-x) y = -inner x y := by { rw [← neg_one_smul ℝ x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : α} : inner x (-y) = -inner x y := by { rw [inner_comm, inner_neg_left, inner_comm] } @[simp] lemma inner_neg_neg {x y : α} : inner (-x) (-y) = inner x y := by simp lemma inner_sub_left {x y z : α} : inner (x - y) z = inner x z - inner y z := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : α} : inner x (y - z) = inner x y - inner x z := by { simp [sub_eq_add_neg, inner_add_right] } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : α} : inner (x + y) (x + y) = inner x x + 2 * inner x y + inner y y := by simpa [inner_add_left, inner_add_right, two_mul, add_assoc] using inner_comm _ _ /-- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : α} : inner (x - y) (x - y) = inner x x - 2 * inner x y + inner y y := begin simp only [inner_sub_left, inner_sub_right, two_mul], simpa [sub_eq_add_neg, add_comm, add_left_comm] using inner_comm _ _ end /-- Parallelogram law -/ lemma parallelogram_law {x y : α} : inner (x + y) (x + y) + inner (x - y) (x - y) = 2 * (inner x x + inner y y) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality -/ lemma inner_mul_inner_self_le (x y : α) : inner x y * inner x y ≤ inner x x * inner y y := begin have : ∀ t, 0 ≤ inner y y * t * t + 2 * inner x y * t + inner x x, from assume t, calc 0 ≤ inner (x+t•y) (x+t•y) : inner_self_nonneg ... = inner y y * t * t + 2 * inner x y * t + inner x x : by { simp only [inner_add_add_self, inner_smul_right, inner_smul_left], ring }, have := discriminant_le_zero this, rw discrim at this, have h : (2 * inner x y)^2 - 4 * inner y y * inner x x = 4 * (inner x y * inner x y - inner x x * inner y y) := by ring, rw h at this, linarith end end basic_properties section norm lemma inner_self_eq_norm_square (x : α) : inner x x = ∥x∥ * ∥x∥ := by { rw norm_eq_sqrt_inner, exact (mul_self_sqrt inner_self_nonneg).symm } /-- Expand the square -/ lemma norm_add_pow_two {x y : α} : ∥x + y∥^2 = ∥x∥^2 + 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_add_add_self } /-- Same lemma as above but in a different form -/ lemma norm_add_mul_self {x y : α} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_sub_pow_two {x y : α} : ∥x - y∥^2 = ∥x∥^2 - 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_sub_sub_self } /-- Same lemma as above but in a different form -/ lemma norm_sub_mul_self {x y : α} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : α) : abs (inner x y) ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin rw abs_mul_abs_self, have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = inner x x * inner y y, simp only [inner_self_eq_norm_square], ring, rw this, exact inner_mul_inner_self_le _ _ end lemma parallelogram_law_with_norm {x y : α} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { simp only [(inner_self_eq_norm_square _).symm], exact parallelogram_law } /-- The inner product, in terms of the norm. -/ lemma inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : α) : inner x y = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := begin rw norm_add_mul_self, ring end /-- The inner product, in terms of the norm. -/ lemma inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : α) : inner x y = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := begin rw norm_sub_mul_self, ring end /-- The inner product, in terms of the norm. -/ lemma inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : α) : inner x y = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 := begin rw [norm_add_mul_self, norm_sub_mul_self], ring end /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_iff_inner_eq_zero (x y : α) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ inner x y = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square {x y : α} (h : inner x y = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_square_eq_norm_square_add_norm_square_iff_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_iff_inner_eq_zero (x y : α) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ inner x y = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square {x y : α} (h : inner x y = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_square_eq_norm_square_add_norm_square_iff_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma inner_add_sub_eq_zero_iff (x y : α) : inner (x + y) (x - y) = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp [←inner_self_eq_norm_square, inner_add_left, inner_sub_right, inner_comm y x, sub_eq_zero, add_comm (inner x y)] end /-- The inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_inner_div_norm_mul_norm_le_one (x y : α) : abs (inner x y / (∥x∥ * ∥y∥)) ≤ 1 := begin rw abs_div, by_cases h : 0 = abs (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_inner_le_norm x y using 1, rw [abs_mul, abs_of_nonneg (norm_nonneg x), abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma inner_smul_self_left (x : α) (r : ℝ) : inner (r • x) x = r * (∥x∥ * ∥x∥) := by rw [inner_smul_left, ←inner_self_eq_norm_square] /-- The inner product of a vector with a multiple of itself. -/ lemma inner_smul_self_right (x : α) (r : ℝ) : inner x (r • x) = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←inner_self_eq_norm_square] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : α} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : abs (inner x (r • x) / (∥x∥ * ∥r • x∥)) = 1 := begin rw [inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (abs r), mul_assoc, abs_div, abs_mul r, abs_mul (abs r), abs_abs, div_self], exact mul_ne_zero (λ h, hr (eq_zero_of_abs_eq_zero h)) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero (eq_zero_of_abs_eq_zero h)))) end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : α} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : inner x (r • x) / (∥x∥ * ∥r • x∥) = 1 := begin rw [inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (abs r), mul_assoc, abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : α} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : inner x (r • x) / (∥x∥ * ∥r • x∥) = -1 := begin rw [inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (abs r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : α) : abs (inner x y / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, exact h }, refine and.intro hx0 _, set r := inner x y / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : inner x t = 0, { rw [ht, inner_sub_right, inner_smul_right, hr, ←inner_self_eq_norm_square, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, inner_self_eq_norm_square, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), abs_div, abs_mul, abs_of_nonneg (norm_nonneg _), abs_of_nonneg (norm_nonneg _), ←real.norm_eq_abs, ←norm_smul] at h, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, rw [pow_two, pow_two, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square, inner_add_add_self] at h2, conv_rhs at h2 { congr, congr, skip, rw [inner_smul_right, inner_comm, ht0, mul_zero, mul_zero] }, symmetry' at h2, rw [add_zero, add_left_eq_self, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma inner_div_norm_mul_norm_eq_one_iff (x y : α) : inner x y / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun abs at ha, norm_num at ha, rcases (abs_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma inner_div_norm_mul_norm_eq_neg_one_iff (x y : α) : inner x y / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun abs at ha, norm_num at ha, rcases (abs_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → α) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → α) (h₂ : ∑ i in s₂, w₂ i = 0) : inner (∑ i₁ in s₁, w₁ i₁ • v₁ i₁) (∑ i₂ in s₂, w₂ i₂ • v₂ i₂) = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, inner_smul_left, inner_smul_right, inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] end norm /-! ### Inner product space structure on product spaces -/ -- TODO [Lean 3.15]: drop some of these `show`s /-- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space (ι : Type*) [fintype ι] (f : ι → Type*) [Π i, inner_product_space (f i)] : inner_product_space (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_eq_sqrt_inner := begin assume x, have : (2 : ℝ)⁻¹ * 2 = 1, by norm_num, simp [inner, pi_Lp.norm_eq, norm_eq_sqrt_inner, sqrt_eq_rpow, ← rpow_mul (inner_self_nonneg), this], end, comm := λ x y, finset.sum_congr rfl $ λ i hi, inner_comm (x i) (y i), add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = r * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } /-- The type of real numbers is an inner product space. -/ instance real.inner_product_space : inner_product_space ℝ := { inner := (*), norm_eq_sqrt_inner := λ x, by simp [inner, norm_eq_abs, sqrt_mul_self_eq_abs], comm := mul_comm, add_left := add_mul, smul_left := λ _ _ _, mul_assoc _ _ _ } /-- The standard Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), ℝ) section pi_Lp local attribute [reducible] pi_Lp variables (n : Type*) [fintype n] instance : finite_dimensional ℝ (euclidean_space n) := by apply_instance @[simp] lemma findim_euclidean_space : finite_dimensional.findim ℝ (euclidean_space n) = fintype.card n := by simp lemma findim_euclidean_space_fin {n : ℕ} : finite_dimensional.findim ℝ (euclidean_space (fin n)) = n := by simp end pi_Lp /-! ### Orthogonal projection in inner product spaces -/ section orthogonal open filter /-- Existence of minimizers Let `u` be a point in an inner product space, and let `K` be a nonempty complete convex subset. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set α} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (𝓝 δ), { have h : tendsto (λ n:ℕ, δ) at_top (𝓝 δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (𝓝 δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):α)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):α), let wq := ((w q):α), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (abs((2:ℝ)) * ∥u - half•(wq + wp)∥) * (abs((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw abs_of_nonneg, exact add_nonneg zero_le_one zero_le_one } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by { rw [norm_smul], refl } ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, show wp - wq = (u - wq) - (u - wp), abel, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) (le_of_lt nat.one_div_pos_of_nat)) (le_of_lt nat.one_div_pos_of_nat)), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (𝓝 ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers in the above theorem -/ theorem norm_eq_infi_iff_inner_le_zero {K : set α} (h : convex K) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) (w - v) ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := inner (u - v) (w - v), let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+abs(θ)*∥w-v∥*(abs(θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:α) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:α) - v) + ∥(w:α) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end /-- Existence of minimizers. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (K : subspace ℝ α) (h : is_complete (↑K : set α)) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (↑K : set α), ∥u - w∥ := exists_norm_eq_infi_of_complete_convex ⟨0, K.zero_mem⟩ h K.convex /-- Characterization of minimizers in the above theorem. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` if and only if for all `w ∈ K`, `inner (u - v) w = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero (K : subspace ℝ α) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set α), ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) w = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, { rwa [norm_eq_infi_iff_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : inner (u - v) w ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : inner (u - v) w ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_inner_le_zero, exacts [submodule.convex _, hv] end /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) := (exists_norm_eq_infi_of_complete_subspace K h v).some /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : orthogonal_projection_fn h v ∈ K := (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : ∀ w ∈ K, inner (v - orthogonal_projection_fn h v) w = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem h v), exact (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {K : submodule ℝ α} (h : is_complete (K : set α)) {u v : α} (hvm : v ∈ K) (hvo : ∀ w ∈ K, inner (u - v) w = 0) : v = orthogonal_projection_fn h u := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : v - orthogonal_projection_fn h u ∈ K := submodule.sub_mem K hvm (orthogonal_projection_fn_mem h u), have huo : inner (u - orthogonal_projection_fn h u) (v - orthogonal_projection_fn h u) = 0 := orthogonal_projection_fn_inner_eq_zero h u _ hvs, have huv : inner (u - v) (v - orthogonal_projection_fn h u) = 0 := hvo _ hvs, have houv : inner ((u - orthogonal_projection_fn h u) - (u - v)) (v - orthogonal_projection_fn h u) = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end /-- The orthogonal projection onto a complete subspace. For most purposes, `orthogonal_projection`, which removes the `is_complete` hypothesis and is the identity map when the subspace is not complete, should be used instead. -/ def orthogonal_projection_of_complete {K : submodule ℝ α} (h : is_complete (K : set α)) : linear_map ℝ α α := { to_fun := orthogonal_projection_fn h, map_add' := λ x y, begin have hm : orthogonal_projection_fn h x + orthogonal_projection_fn h y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem h x) (orthogonal_projection_fn_mem h y), have ho : ∀ w ∈ K, inner (x + y - (orthogonal_projection_fn h x + orthogonal_projection_fn h y)) w = 0, { intros w hw, rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, orthogonal_projection_fn_inner_eq_zero h _ w hw, add_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn h x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem h x), have ho : ∀ w ∈ K, inner (c • x - c • orthogonal_projection_fn h x) w = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, mul_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end } /-- The orthogonal projection onto a subspace, which is expected to be complete. If the subspace is not complete, this uses the identity map instead. -/ def orthogonal_projection (K : submodule ℝ α) : linear_map ℝ α α := if h : is_complete (K : set α) then orthogonal_projection_of_complete h else linear_map.id /-- The definition of `orthogonal_projection` using `if`. -/ lemma orthogonal_projection_def (K : submodule ℝ α) : orthogonal_projection K = if h : is_complete (K : set α) then orthogonal_projection_of_complete h else linear_map.id := rfl @[simp] lemma orthogonal_projection_fn_eq {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : orthogonal_projection_fn h v = orthogonal_projection K v := by { rw [orthogonal_projection_def, dif_pos h], refl } /-- The orthogonal projection is in the given subspace. -/ lemma orthogonal_projection_mem {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : orthogonal_projection K v ∈ K := begin rw ←orthogonal_projection_fn_eq h, exact orthogonal_projection_fn_mem h v end /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (K : submodule ℝ α) (v : α) : ∀ w ∈ K, inner (v - orthogonal_projection K v) w = 0 := begin simp_rw orthogonal_projection_def, split_ifs, { exact orthogonal_projection_fn_inner_eq_zero h v }, { simp }, end /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {K : submodule ℝ α} (h : is_complete (K : set α)) {u v : α} (hvm : v ∈ K) (hvo : ∀ w ∈ K, inner (u - v) w = 0) : v = orthogonal_projection K u := begin rw ←orthogonal_projection_fn_eq h, exact eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hvm hvo end /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal (K : submodule ℝ α) : submodule ℝ α := { carrier := {v | ∀ u ∈ K, inner u v = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } /-- When a vector is in `K.orthogonal`. -/ lemma submodule.mem_orthogonal (K : submodule ℝ α) (v : α) : v ∈ K.orthogonal ↔ ∀ u ∈ K, inner u v = 0 := iff.rfl /-- When a vector is in `K.orthogonal`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (K : submodule ℝ α) (v : α) : v ∈ K.orthogonal ↔ ∀ u ∈ K, inner v u = 0 := by simp_rw [submodule.mem_orthogonal, inner_comm] /-- A vector in `K` is orthogonal to one in `K.orthogonal`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : α} {K : submodule ℝ α} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : inner u v = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `K.orthogonal` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : α} {K : submodule ℝ α} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : inner v u = 0 := inner_comm u v ▸ submodule.inner_right_of_mem_orthogonal hu hv /-- `K` and `K.orthogonal` have trivial intersection. -/ lemma submodule.orthogonal_disjoint (K : submodule ℝ α) : disjoint K K.orthogonal := begin simp_rw [submodule.disjoint_def, submodule.mem_orthogonal], exact λ x hx ho, inner_self_eq_zero.1 (ho x hx) end variables (α) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule ℝ α` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule ℝ α) (order_dual $ submodule ℝ α) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {α} /-- `K` is contained in `K.orthogonal.orthogonal`. -/ lemma submodule.le_orthogonal_orthogonal (K : submodule ℝ α) : K ≤ K.orthogonal.orthogonal := (submodule.orthogonal_gc α).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule ℝ α) : K₁.orthogonal ⊓ K₂.orthogonal = (K₁ ⊔ K₂).orthogonal := (submodule.orthogonal_gc α).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule ℝ α) : (⨅ i, (K i).orthogonal) = (supr K).orthogonal := (submodule.orthogonal_gc α).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule ℝ α) : (⨅ K ∈ s, submodule.orthogonal K) = (Sup s).orthogonal := (submodule.orthogonal_gc α).l_Sup.symm /-- If `K` is complete, `K` and `K.orthogonal` span the whole space. -/ lemma submodule.sup_orthogonal_of_is_complete {K : submodule ℝ α} (h : is_complete (K : set α)) : K ⊔ K.orthogonal = ⊤ := begin rw submodule.eq_top_iff', intro x, rw submodule.mem_sup, rcases exists_norm_eq_infi_of_complete_subspace K h x with ⟨v, hv, hvm⟩, rw norm_eq_infi_iff_inner_eq_zero K hv at hvm, use [v, hv, x - v], split, { rw submodule.mem_orthogonal', exact hvm }, { exact add_sub_cancel'_right _ _ } end /-- If `K` is complete, `K` and `K.orthogonal` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_is_complete {K : submodule ℝ α} (h : is_complete (K : set α)) : is_compl K K.orthogonal := ⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩ end orthogonal
ce8ae9c2185f367f628e28993bd493b34b6c74ca
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/set/intervals/basic.lean
26c6b19a2aa43dc9d76306d15537225d5261c25e
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
50,996
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, Patrick Massot, Yury Kudryashov, Rémy Degenne -/ import algebra.ordered_group import data.set.basic /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). TODO: This is just the beginning; a lot of rules are missing -/ universe u namespace set open set section intervals variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} lemma Ioo_def (a b : α) : {x | a < x ∧ x < b} = Ioo a b := rfl lemma Ico_def (a b : α) : {x | a ≤ x ∧ x < b} = Ico a b := rfl lemma Iio_def (a : α) : {x | x < a} = Iio a := rfl lemma Icc_def (a b : α) : {x | a ≤ x ∧ x ≤ b} = Icc a b := rfl lemma Iic_def (b : α) : {x | x ≤ b} = Iic b := rfl lemma Ioc_def (a b : α) : {x | a < x ∧ x ≤ b} = Ioc a b := rfl lemma Ici_def (a : α) : {x | a ≤ x} = Ici a := rfl lemma Ioi_def (a : α) : {x | a < x} = Ioi a := rfl @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : @Ici (order_dual α) _ a = @Iic α _ a := rfl @[simp] lemma dual_Iic : @Iic (order_dual α) _ a = @Ici α _ a := rfl @[simp] lemma dual_Ioi : @Ioi (order_dual α) _ a = @Iio α _ a := rfl @[simp] lemma dual_Iio : @Iio (order_dual α) _ a = @Ioi α _ a := rfl @[simp] lemma dual_Icc : @Icc (order_dual α) _ a b = @Icc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : @Ioc (order_dual α) _ a b = @Ico α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : @Ico (order_dual α) _ a b = @Ioc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : @Ioo (order_dual α) _ a b = @Ioo α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, le_trans hx.1 hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_le_of_lt hx.1 hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_lt_of_le hx.1 hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, lt_trans ha hb, exists_between⟩ @[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a @[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a lemma nonempty_Icc_subtype (h : a ≤ b) : nonempty (Icc a b) := nonempty.to_subtype (nonempty_Icc.mpr h) lemma nonempty_Ico_subtype (h : a < b) : nonempty (Ico a b) := nonempty.to_subtype (nonempty_Ico.mpr h) lemma nonempty_Ioc_subtype (h : a < b) : nonempty (Ioc a b) := nonempty.to_subtype (nonempty_Ioc.mpr h) /-- An interval `Ici a` is nonempty. -/ instance nonempty_Ici_subtype : nonempty (Ici a) := nonempty.to_subtype nonempty_Ici /-- An interval `Iic a` is nonempty. -/ instance nonempty_Iic_subtype : nonempty (Iic a) := nonempty.to_subtype nonempty_Iic lemma nonempty_Ioo_subtype [densely_ordered α] (h : a < b) : nonempty (Ioo a b) := nonempty.to_subtype (nonempty_Ioo.mpr h) /-- In a `no_top_order`, the intervals `Ioi` are nonempty. -/ instance nonempty_Ioi_subtype [no_top_order α] : nonempty (Ioi a) := nonempty.to_subtype nonempty_Ioi /-- In a `no_bot_order`, the intervals `Iio` are nonempty. -/ instance nonempty_Iio_subtype [no_bot_order α] : nonempty (Iio a) := nonempty.to_subtype nonempty_Iio @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, le_trans h hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici (order_dual α) _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, lt_of_lt_of_le h hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Icc_subset_Ioo (ha : a₂ < a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ := λ x hx, ⟨lt_of_lt_of_le ha hx.1, lt_of_le_of_lt hx.2 hb⟩ lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Iic_self : Ioc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h (le_refl _) lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := λ x, and.imp_right $ λ h', lt_of_le_of_lt h' h lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λx hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λx hx, le_of_lt hx lemma Ico_subset_Ici_self : Ico a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ lemma Icc_ssubset_Icc_left (hI : a₂ ≤ b₂) (ha : a₂ < a₁) (hb : b₁ ≤ b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc (le_of_lt ha) hb)).mpr ⟨a₂, left_mem_Icc.mpr hI, not_and.mpr (λ f g, lt_irrefl a₂ (lt_of_lt_of_le ha f))⟩ lemma Icc_ssubset_Icc_right (hI : a₂ ≤ b₂) (ha : a₂ ≤ a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc ha (le_of_lt hb))).mpr ⟨b₂, right_mem_Icc.mpr hI, (λ f, lt_irrefl b₁ (lt_of_lt_of_le hb f.2))⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λx hx, lt_of_le_of_lt h hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λx hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl lemma mem_Icc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Icc a b := Ioo_subset_Icc_self h lemma mem_Ico_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ico a b := Ioo_subset_Ico_self h lemma mem_Ioc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ioc a b := Ioo_subset_Ioc_self h lemma mem_Icc_of_Ico (h : x ∈ Ico a b) : x ∈ Icc a b := Ico_subset_Icc_self h lemma mem_Icc_of_Ioc (h : x ∈ Ioc a b) : x ∈ Icc a b := Ioc_subset_Icc_self h lemma mem_Ici_of_Ioi (h : x ∈ Ioi a) : x ∈ Ici a := Ioi_subset_Ici_self h lemma mem_Iic_of_Iio (h : x ∈ Iio a) : x ∈ Iic a := Iio_subset_Iic_self h end intervals section partial_order variables {α : Type u} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] @[simp] lemma Icc_diff_left : Icc a b \ {a} = Ioc a b := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm] @[simp] lemma Icc_diff_right : Icc a b \ {b} = Ico a b := ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc] @[simp] lemma Ico_diff_left : Ico a b \ {a} = Ioo a b := ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm] @[simp] lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b := ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne] @[simp] lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b := by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right] @[simp] lemma Ici_diff_left : Ici a \ {a} = Ioi a := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm] @[simp] lemma Iic_diff_right : Iic a \ {a} = Iio a := ext $ λ x, by simp [lt_iff_le_and_ne] @[simp] lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} := by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)] @[simp] lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} := by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)] @[simp] lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} := by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] } @[simp] lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} := by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)] @[simp] lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} := by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)] @[simp] lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt] @[simp] lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm lemma Ioo_union_left (hab : a < b) : Ioo a b ∪ {a} = Ico a b := by rw [← Ico_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Ico.2 hab)] lemma Ioo_union_right (hab : a < b) : Ioo a b ∪ {b} = Ioc a b := by simpa only [dual_Ioo, dual_Ico] using @Ioo_union_left (order_dual α) _ b a hab lemma Ioc_union_left (hab : a ≤ b) : Ioc a b ∪ {a} = Icc a b := by rw [← Icc_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Icc.2 hab)] lemma Ico_union_right (hab : a ≤ b) : Ico a b ∪ {b} = Icc a b := by simpa only [dual_Ioc, dual_Icc] using @Ioc_union_left (order_dual α) _ b a hab lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ ({Ici a, Ioi a} : set (set α)) := classical.by_cases (λ h : a ∈ s, or.inl $ subset.antisymm hc $ by rw [← Ioi_union_left, union_subset_iff]; simp *) (λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho) lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ ({Iic a, Iio a} : set (set α)) := @mem_Ici_Ioi_of_subset_of_subset (order_dual α) _ a s ho hc lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) : s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) := begin classical, by_cases ha : a ∈ s; by_cases hb : b ∈ s, { refine or.inl (subset.antisymm hc _), rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha, ← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho }, { refine (or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_right], exact subset_diff_singleton hc hb }, { rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } }, { refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_left], exact subset_diff_singleton hc ha }, { rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } }, { refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho), rw [← Ico_diff_left, ← Icc_diff_right], apply_rules [subset_diff_singleton] } end lemma mem_Ioo_or_eq_endpoints_of_mem_Icc {x : α} (hmem : x ∈ Icc a b) : x = a ∨ x = b ∨ x ∈ Ioo a b := begin rw [mem_Icc, le_iff_lt_or_eq, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb | hxb⟩, { exact or.inr (or.inr ⟨hxa, hxb⟩) }, { exact or.inr (or.inl hxb) }, all_goals { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_left_of_mem_Ico {x : α} (hmem : x ∈ Ico a b) : x = a ∨ x ∈ Ioo a b := begin rw [mem_Ico, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb⟩, { exact or.inr ⟨hxa, hxb⟩ }, { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_right_of_mem_Ioc {x : α} (hmem : x ∈ Ioc a b) : x = b ∨ x ∈ Ioo a b := begin have := @mem_Ioo_or_eq_left_of_mem_Ico (order_dual α) _ b a x, rw [dual_Ioo, dual_Ico] at this, exact this hmem end lemma Ici_singleton_of_top {a : α} (h_top : ∀ x, x ≤ a) : Ici a = {a} := begin ext, exact ⟨λ h, le_antisymm (h_top _) h, λ h, le_of_eq h.symm⟩, end lemma Iic_singleton_of_bot {a : α} (h_bot : ∀ x, a ≤ x) : Iic a = {a} := @Ici_singleton_of_top (order_dual α) _ a h_bot end partial_order section order_top variables {α : Type u} [order_top α] {a : α} @[simp] lemma Ici_top : Ici (⊤ : α) = {⊤} := Ici_singleton_of_top (λ _, le_top) @[simp] lemma Iic_top : Iic (⊤ : α) = univ := eq_univ_of_forall $ λ x, le_top @[simp] lemma Icc_top : Icc a ⊤ = Ici a := by simp [← Ici_inter_Iic] @[simp] lemma Ioc_top : Ioc a ⊤ = Ioi a := by simp [← Ioi_inter_Iic] end order_top section order_bot variables {α : Type u} [order_bot α] {a : α} @[simp] lemma Iic_bot : Iic (⊥ : α) = {⊥} := Iic_singleton_of_bot (λ _, bot_le) @[simp] lemma Ici_bot : Ici (⊥ : α) = univ := @Iic_top (order_dual α) _ @[simp] lemma Icc_bot : Icc ⊥ a = Iic a := by simp [← Ici_inter_Iic] @[simp] lemma Ico_bot : Ico ⊥ a = Iio a := by simp [← Ici_inter_Iio] end order_bot section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} lemma not_mem_Ici : c ∉ Ici a ↔ c < a := not_le lemma not_mem_Iic : c ∉ Iic b ↔ b < c := not_le lemma not_mem_Icc_of_lt (ha : c < a) : c ∉ Icc a b := not_mem_subset Icc_subset_Ici_self $ not_mem_Ici.mpr ha lemma not_mem_Icc_of_gt (hb : b < c) : c ∉ Icc a b := not_mem_subset Icc_subset_Iic_self $ not_mem_Iic.mpr hb lemma not_mem_Ico_of_lt (ha : c < a) : c ∉ Ico a b := not_mem_subset Ico_subset_Ici_self $ not_mem_Ici.mpr ha lemma not_mem_Ioc_of_gt (hb : b < c) : c ∉ Ioc a b := not_mem_subset Ioc_subset_Iic_self $ not_mem_Iic.mpr hb lemma not_mem_Ioi : c ∉ Ioi a ↔ c ≤ a := not_lt lemma not_mem_Iio : c ∉ Iio b ↔ b ≤ c := not_lt lemma not_mem_Ioc_of_le (ha : c ≤ a) : c ∉ Ioc a b := not_mem_subset Ioc_subset_Ioi_self $ not_mem_Ioi.mpr ha lemma not_mem_Ico_of_ge (hb : b ≤ c) : c ∉ Ico a b := not_mem_subset Ico_subset_Iio_self $ not_mem_Iio.mpr hb lemma not_mem_Ioo_of_le (ha : c ≤ a) : c ∉ Ioo a b := not_mem_subset Ioo_subset_Ioi_self $ not_mem_Ioi.mpr ha lemma not_mem_Ioo_of_ge (hb : b ≤ c) : c ∉ Ioo a b := not_mem_subset Ioo_subset_Iio_self $ not_mem_Iio.mpr hb @[simp] lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le @[simp] lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le @[simp] lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt @[simp] lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt @[simp] lemma Ici_diff_Ici : Ici a \ Ici b = Ico a b := by rw [diff_eq, compl_Ici, Ici_inter_Iio] @[simp] lemma Ici_diff_Ioi : Ici a \ Ioi b = Icc a b := by rw [diff_eq, compl_Ioi, Ici_inter_Iic] @[simp] lemma Ioi_diff_Ioi : Ioi a \ Ioi b = Ioc a b := by rw [diff_eq, compl_Ioi, Ioi_inter_Iic] @[simp] lemma Ioi_diff_Ici : Ioi a \ Ici b = Ioo a b := by rw [diff_eq, compl_Ici, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iic : Iic b \ Iic a = Ioc a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iic] @[simp] lemma Iio_diff_Iic : Iio b \ Iic a = Ioo a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iio : Iic b \ Iio a = Icc a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iic] @[simp] lemma Iio_diff_Iio : Iio b \ Iio a = Ico a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iio] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := exists_between h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases exists_between h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := exists_between (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le ca (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := by rw [← diff_eq_empty, Iio_diff_Iic, Ioo_eq_empty_iff] /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ lemma Ioo_union_Ioi' (h₁ : c < b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioo, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto, }, { have hxb : x < b, from lt_of_le_of_lt (le_of_not_gt hc) h₁, tauto, }, end lemma Ioo_union_Ioi (h : c < max a b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioo_union_Ioi' h, }, { rw min_comm, simp [*, min_eq_left_of_lt], }, end lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioo_union_Ici lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Ico_union_Ici lemma Ico_union_Ici' (h₁ : c ≤ b) : Ico a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ico, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto, }, { have hxb : x < b, from lt_of_lt_of_le (lt_of_not_ge hc) h₁, tauto, }, end lemma Ico_union_Ici (h : c ≤ max a b) : Ico a b ∪ Ici c = Ici (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ico_union_Ici' h, }, { simp [*] }, end lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_le_of_lt h)) Ioi_subset_Ioc_union_Ioi lemma Ioc_union_Ioi' (h₁ : c ≤ b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioc, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto, }, { have hxb : x ≤ b, from le_trans (le_of_not_gt hc) h₁, tauto, }, end lemma Ioc_union_Ioi (h : c ≤ max a b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioc_union_Ioi' h, }, { simp [*] }, end lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (λ hx, le_trans h (le_of_lt hx))) Ici_subset_Icc_union_Ioi lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b := subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self) @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioc_union_Ici lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b := subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self) @[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Icc_union_Ici lemma Icc_union_Ici' (h₁ : c ≤ b) : Icc a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Icc, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto, }, { have hxb : x ≤ b, from le_trans (le_of_not_ge hc) h₁, tauto, }, end lemma Icc_union_Ici (h : c ≤ max a b) : Icc a b ∪ Ici c = Ici (min a c) := begin cases le_or_lt a b with hab hab; simp [hab] at h, { exact Icc_union_Ici' h, }, { cases h, { simp [*], }, { have hca : c ≤ a, from le_trans h (le_of_lt hab), simp [*], }, }, end /-! #### An infinite and a finite interval -/ lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans (le_of_lt hx) h) and.right) Iic_subset_Iio_union_Icc lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_lt_of_le hx h) and.right) Iio_subset_Iio_union_Ico lemma Iio_union_Ico' (h₁ : c ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iio, mem_Ico, lt_max_iff], by_cases hc : c ≤ x, { tauto, }, { have hxb : x < b, from lt_of_lt_of_le (lt_of_not_ge hc) h₁, tauto, }, end lemma Iio_union_Ico (h : min c d ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ico' h, }, { simp [*] }, end lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Ioc lemma Iic_union_Ioc' (h₁ : c < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Ioc, le_max_iff], by_cases hc : c < x, { tauto, }, { have hxb : x ≤ b, from le_trans (le_of_not_gt hc) (le_of_lt h₁), tauto, }, end lemma Iic_union_Ioc (h : min c d < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Ioc' h, }, { rw max_comm, simp [*, max_eq_right_of_lt h], }, end lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ioo lemma Iio_union_Ioo' (h₁ : c < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin ext x, cases lt_or_le x b with hba hba, { simp [hba, h₁] }, { simp only [mem_Iio, mem_union_eq, mem_Ioo, lt_max_iff], refine or_congr iff.rfl ⟨and.right, _⟩, exact λ h₂, ⟨h₁.trans_le hba, h₂⟩ }, end lemma Iio_union_Ioo (h : min c d < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ioo' h, }, { rw max_comm, simp [*, max_eq_right_of_lt h], }, end lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b := subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Icc lemma Iic_union_Icc' (h₁ : c ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Icc, le_max_iff], by_cases hc : c ≤ x, { tauto, }, { have hxb : x ≤ b, from le_trans (le_of_not_ge hc) h₁, tauto, }, end lemma Iic_union_Icc (h : min c d ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin cases le_or_lt c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Icc' h, }, { cases h, { have hdb : d ≤ b, from le_trans (le_of_lt hcd) h, simp [*], }, { simp [*], }, }, end lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b := subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ico /-! #### Two finite intervals, `I?o` and `Ic?` -/ lemma Ioo_subset_Ioo_union_Ico : Ioo a c ⊆ Ioo a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioo_union_Ico lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Ico_union_Ico lemma Ico_union_Ico' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ico, min_le_iff, lt_max_iff], by_cases hc : c ≤ x; by_cases hd : x < d, { tauto, }, { have hax : a ≤ x, from le_trans h₂ (le_of_not_gt hd), tauto, }, { have hxb : x < b, from lt_of_lt_of_le (lt_of_not_ge hc) h₁, tauto, }, { tauto, }, end lemma Ico_union_Ico (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ico_union_Ico' h₂ h₁, }, all_goals { simp [*] }, end lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Ico_union_Icc lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioo_union_Icc /-! #### Two finite intervals, `I?c` and `Io?` -/ lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ioo lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Ico_subset_Icc_union_Ioo lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Icc_subset_Icc_union_Ioc lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Ioc lemma Ioc_union_Ioc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioc, min_lt_iff, le_max_iff], by_cases hc : c < x; by_cases hd : x ≤ d, { tauto, }, { have hax : a < x, from lt_of_le_of_lt h₂ (lt_of_not_ge hd), tauto, }, { have hxb : x ≤ b, from le_trans (le_of_not_gt hc) h₁, tauto, }, { tauto, }, end lemma Ioc_union_Ioc (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ioc_union_Ioc' h₂ h₁, }, all_goals { simp [*] }, end /-! #### Two finite intervals with a common point -/ lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c := subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ico lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c := subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Icc_union_Ico lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c := subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Icc_union_Icc lemma Icc_union_Icc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Icc, min_le_iff, le_max_iff], by_cases hc : c ≤ x; by_cases hd : x ≤ d, { tauto, }, { have hax : a ≤ x, from le_trans h₂ (le_of_not_ge hd), tauto, }, { have hxb : x ≤ b, from le_trans (le_of_not_ge hc) h₁, tauto, }, { tauto, }, end /-- We cannot replace `<` by `≤` in the hypotheses. Otherwise for `b < a = d < c` the l.h.s. is `∅` and the r.h.s. is `{a}`. -/ lemma Icc_union_Icc (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin cases le_or_lt a b with hab hab; cases le_or_lt c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, hab, hcd] at h₁ h₂, { exact Icc_union_Icc' (le_of_lt h₂) (le_of_lt h₁), }, all_goals { simp [*, min_eq_left_of_lt, max_eq_left_of_lt, min_eq_right_of_lt, max_eq_right_of_lt], }, end lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c := subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Icc lemma Ioo_union_Ioo' (h₁ : c < b) (h₂ : a < d) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioo, min_lt_iff, lt_max_iff], by_cases hc : c < x; by_cases hd : x < d, { tauto, }, { have hax : a < x, from lt_of_lt_of_le h₂ (le_of_not_gt hd), tauto, }, { have hxb : x < b, from lt_of_le_of_lt (le_of_not_gt hc) h₁, tauto, }, { tauto, }, end lemma Ioo_union_Ioo (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, hab, hcd] at h₁ h₂, { exact Ioo_union_Ioo' h₂ h₁, }, all_goals { simp [*, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, le_of_lt h₂, le_of_lt h₁], }, end end linear_order section lattice section inf variables {α : Type u} [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) := by { ext x, simp [Iio] } end inf section sup variables {α : Type u} [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := by { ext x, simp [Ioi] } end sup section both variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] include ht lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl end both end lattice section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} lemma Ioc_inter_Ioo_of_left_lt (h : b₁ < b₂) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioc (max a₁ a₂) b₁ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_left_iff_imp.2 (λ h', lt_of_le_of_lt h' h)] lemma Ioc_inter_Ioo_of_right_le (h : b₂ ≤ b₁) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (max a₁ a₂) b₂ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_right_iff_imp.2 (λ h', (le_trans (le_of_lt h') h))] lemma Ioo_inter_Ioc_of_left_le (h : b₁ ≤ b₂) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioo (max a₁ a₂) b₁ := by rw [inter_comm, Ioc_inter_Ioo_of_right_le h, max_comm] lemma Ioo_inter_Ioc_of_right_lt (h : b₂ < b₁) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (max a₁ a₂) b₂ := by rw [inter_comm, Ioc_inter_Ioo_of_left_lt h, max_comm] @[simp] lemma Ico_diff_Iio : Ico a b \ Iio c = Ico (max a c) b := ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio : Ico a b ∩ Iio c = Ico a (min b c) := ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} @[simp] lemma Ioc_union_Ioc_right : Ioc a b ∪ Ioc a c = Ioc a (max b c) := by rw [Ioc_union_Ioc, min_self]; exact (min_le_left _ _).trans (le_max_left _ _) @[simp] lemma Ioc_union_Ioc_left : Ioc a c ∪ Ioc b c = Ioc (min a b) c := by rw [Ioc_union_Ioc, max_self]; exact (min_le_right _ _).trans (le_max_right _ _) @[simp] lemma Ioc_union_Ioc_symm : Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b) := by { rw max_comm, apply Ioc_union_Ioc; rw max_comm; exact min_le_max } @[simp] lemma Ioc_union_Ioc_union_Ioc_cycle : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc (min a (min b c)) (max a (max b c)) := begin rw [Ioc_union_Ioc, Ioc_union_Ioc], ac_refl, all_goals { solve_by_elim [min_le_left_of_le, min_le_right_of_le, le_max_left_of_le, le_max_right_of_le, le_refl] { max_depth := 5 }} end end linear_order /-! ### Lemmas about membership of arithmetic operations -/ section ordered_comm_group variables {α : Type*} [ordered_comm_group α] {a b c d : α} /-! `inv_mem_Ixx_iff`, `sub_mem_Ixx_iff` -/ @[to_additive] lemma inv_mem_Icc_iff : a⁻¹ ∈ set.Icc c d ↔ a ∈ set.Icc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ (and_congr inv_le' le_inv') @[to_additive] lemma inv_mem_Ico_iff : a⁻¹ ∈ set.Ico c d ↔ a ∈ set.Ioc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ (and_congr inv_lt' le_inv') @[to_additive] lemma inv_mem_Ioc_iff : a⁻¹ ∈ set.Ioc c d ↔ a ∈ set.Ico (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ (and_congr inv_le' lt_inv') @[to_additive] lemma inv_mem_Ioo_iff : a⁻¹ ∈ set.Ioo c d ↔ a ∈ set.Ioo (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ (and_congr inv_lt' lt_inv') end ordered_comm_group section ordered_add_comm_group variables {α : Type*} [ordered_add_comm_group α] {a b c d : α} /-! `add_mem_Ixx_iff_left` -/ lemma add_mem_Icc_iff_left : a + b ∈ set.Icc c d ↔ a ∈ set.Icc (c - b) (d - b) := (and_congr sub_le_iff_le_add le_sub_iff_add_le).symm lemma add_mem_Ico_iff_left : a + b ∈ set.Ico c d ↔ a ∈ set.Ico (c - b) (d - b) := (and_congr sub_le_iff_le_add lt_sub_iff_add_lt).symm lemma add_mem_Ioc_iff_left : a + b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c - b) (d - b) := (and_congr sub_lt_iff_lt_add le_sub_iff_add_le).symm lemma add_mem_Ioo_iff_left : a + b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c - b) (d - b) := (and_congr sub_lt_iff_lt_add lt_sub_iff_add_lt).symm /-! `add_mem_Ixx_iff_right` -/ lemma add_mem_Icc_iff_right : a + b ∈ set.Icc c d ↔ b ∈ set.Icc (c - a) (d - a) := (and_congr sub_le_iff_le_add' le_sub_iff_add_le').symm lemma add_mem_Ico_iff_right : a + b ∈ set.Ico c d ↔ b ∈ set.Ico (c - a) (d - a) := (and_congr sub_le_iff_le_add' lt_sub_iff_add_lt').symm lemma add_mem_Ioc_iff_right : a + b ∈ set.Ioc c d ↔ b ∈ set.Ioc (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' le_sub_iff_add_le').symm lemma add_mem_Ioo_iff_right : a + b ∈ set.Ioo c d ↔ b ∈ set.Ioo (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' lt_sub_iff_add_lt').symm /-! `sub_mem_Ixx_iff_left` -/ lemma sub_mem_Icc_iff_left : a - b ∈ set.Icc c d ↔ a ∈ set.Icc (c + b) (d + b) := (and_congr le_sub_iff_add_le sub_le_iff_le_add) lemma sub_mem_Ico_iff_left : a - b ∈ set.Ico c d ↔ a ∈ set.Ico (c + b) (d + b) := (and_congr le_sub_iff_add_le sub_lt_iff_lt_add) lemma sub_mem_Ioc_iff_left : a - b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c + b) (d + b) := (and_congr lt_sub_iff_add_lt sub_le_iff_le_add) lemma sub_mem_Ioo_iff_left : a - b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c + b) (d + b) := (and_congr lt_sub_iff_add_lt sub_lt_iff_lt_add) /-! `sub_mem_Ixx_iff_right` -/ lemma sub_mem_Icc_iff_right : a - b ∈ set.Icc c d ↔ b ∈ set.Icc (a - d) (a - c) := (and_comm _ _).trans $ (and_congr sub_le le_sub) lemma sub_mem_Ico_iff_right : a - b ∈ set.Ico c d ↔ b ∈ set.Ioc (a - d) (a - c) := (and_comm _ _).trans $ (and_congr sub_lt le_sub) lemma sub_mem_Ioc_iff_right : a - b ∈ set.Ioc c d ↔ b ∈ set.Ico (a - d) (a - c) := (and_comm _ _).trans $ (and_congr sub_le lt_sub) lemma sub_mem_Ioo_iff_right : a - b ∈ set.Ioo c d ↔ b ∈ set.Ioo (a - d) (a - c) := (and_comm _ _).trans $ (and_congr sub_lt lt_sub) -- I think that symmetric intervals deserve attention and API: they arise all the time, -- for instance when considering metric balls in `ℝ`. lemma mem_Icc_iff_abs_le {R : Type*} [linear_ordered_add_comm_group R] {x y z : R} : abs (x - y) ≤ z ↔ y ∈ Icc (x - z) (x + z) := abs_le.trans $ (and_comm _ _).trans $ and_congr sub_le neg_le_sub_iff_le_add end ordered_add_comm_group section linear_ordered_add_comm_group variables {α : Type u} [linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp [*, not_le.2 h'], }, { use max x (x + dy), simp [*, le_refl] } end end linear_ordered_add_comm_group end set
3eb4f5e7d6e7e4b5e70a16272c505a1271be87b3
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Server/Rpc/Basic.lean
31fa53666bb51d304cdc9e220a727c97a27ef7c1
[ "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
4,364
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Data.Lsp.Extra /-! Allows LSP clients to make Remote Procedure Calls to the server. The single use case for these is to allow the infoview UI to refer to and manipulate heavy-weight objects residing on the server. It would be inefficient to serialize these into JSON and send over. For example, the client can format an `Expr` without transporting the whole `Environment`. All RPC requests are relative to an open file and an RPC session for that file. The client must first connect to the session using `$/lean/rpc/connect`. -/ namespace Lean.Server /-- Monads with an RPC session in their state. -/ class MonadRpcSession (m : Type → Type) where rpcStoreRef (typeName : Name) (obj : NonScalar) : m Lsp.RpcRef rpcGetRef (r : Lsp.RpcRef) : m (Option (Name × NonScalar)) rpcReleaseRef (r : Lsp.RpcRef) : m Bool export MonadRpcSession (rpcStoreRef rpcGetRef rpcReleaseRef) instance {m n : Type → Type} [MonadLift m n] [MonadRpcSession m] : MonadRpcSession n where rpcStoreRef typeName obj := liftM (rpcStoreRef typeName obj : m _) rpcGetRef r := liftM (rpcGetRef r : m _) rpcReleaseRef r := liftM (rpcReleaseRef r : m _) /-- `RpcEncoding α β` means that `α` may participate in RPC calls with its on-the-wire LSP encoding being `β`. This is useful when `α` contains fields which must be marshalled in a special way. In particular, we encode `WithRpcRef` fields as opaque references rather than send their content. Structures with `From/ToJson` use JSON as their `RpcEncoding`. Structures containing non-JSON-serializable fields can be auto-encoded in two ways: - `deriving RpcEncoding` acts like `From/ToJson` but marshalls any `WithRpcRef` fields as `Lsp.RpcRef`s. - `deriving RpcEncoding with { withRef := true }` generates an encoding for `WithRpcRef TheType`. -/ -- TODO(WN): for Lean.js, have third parameter defining the client-side structure; -- or, compile `WithRpcRef` to "opaque reference" on the client class RpcEncoding (α : Type) (β : outParam Type) where rpcEncode {m : Type → Type} [Monad m] [MonadRpcSession m] : α → m β rpcDecode {m : Type → Type} [Monad m] [MonadRpcSession m] : β → ExceptT String m α export RpcEncoding (rpcEncode rpcDecode) instance [FromJson α] [ToJson α] : RpcEncoding α α where rpcEncode := pure rpcDecode := pure instance [RpcEncoding α β] : RpcEncoding (Option α) (Option β) where rpcEncode v := match v with | none => none | some v => some <$> rpcEncode v rpcDecode v := match v with | none => none | some v => some <$> rpcDecode v -- TODO(WN): instance [RpcEncoding α β] [Traversable t] : RpcEncoding (t α) (t β) instance [RpcEncoding α β] : RpcEncoding (Array α) (Array β) where rpcEncode a := a.mapM rpcEncode rpcDecode b := b.mapM rpcDecode instance [RpcEncoding α α'] [RpcEncoding β β'] : RpcEncoding (α × β) (α' × β') where rpcEncode := fun (a, b) => do let a' ← rpcEncode a let b' ← rpcEncode b return (a', b') rpcDecode := fun (a', b') => do let a ← rpcDecode a' let b ← rpcDecode b' return (a, b) structure RpcEncoding.DerivingParams where withRef : Bool := false /-- Marks fields to encode as opaque references in LSP packets. -/ structure WithRpcRef (α : Type u) where val : α deriving Inhabited namespace WithRpcRef variable {m : Type → Type} [Monad m] [MonadRpcSession m] /-- This is unsafe because we must ensure that: - the stored `NonScalar` is never used to access the value as a type other than `α` - the type `α` is not a scalar -/ protected unsafe def encodeUnsafe [Monad m] (typeName : Name) (r : WithRpcRef α) : m Lsp.RpcRef := do let obj := @unsafeCast α NonScalar r.val rpcStoreRef typeName obj protected unsafe def decodeUnsafeAs (α) (typeName : Name) (r : Lsp.RpcRef) : ExceptT String m (WithRpcRef α) := do match (← rpcGetRef r) with | none => throw s!"RPC reference '{r}' is not valid" | some (nm, obj) => if nm != typeName then throw s!"RPC call type mismatch in reference '{r}'\nexpected '{typeName}', got '{nm}'" WithRpcRef.mk <| @unsafeCast NonScalar α obj end WithRpcRef end Lean.Server
c2989944e474e8cc9462276ebb87ebfc1fb3fe50
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/constants_spec.lean
12475b8740e9f39ec3dd9de934df9914c4f9a90a
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
2,614
lean
/- Specifications file for constants_spec.cairo Do not modify the constant definitions, structure definitions, or automatic specifications. Do not change the name or arguments of the user specifications and soundness theorems. You may freely move the definitions around in the file. You may add definitions and theorems wherever you wish in this file. -/ import starkware.cairo.lean.semantics.soundness.prelude namespace starkware.cairo.common.cairo_secp.constants variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F] -- End of automatically generated prelude. -- Main scope definitions. @[reducible] def SECP_REM := 2 ^ 32 + 2 ^ 9 + 2 ^ 8 + 2 ^ 7 + 2 ^ 6 + 2 ^ 4 + 1 @[reducible] def BASE := 2 ^ 86 @[reducible] def P0 := 77371252455336262886226991 @[reducible] def P1 := 77371252455336267181195263 @[reducible] def P2 := 19342813113834066795298815 @[reducible] def N0 := 10428087374290690730508609 @[reducible] def N1 := 77371252455330678278691517 @[reducible] def N2 := 19342813113834066795298815 @[reducible] def BETA := 7 -- End of main scope definitions. /- Useful calculations collected here. -/ @[reducible] def secp_n := N0 + BASE * N1 + BASE^2 * N2 lemma BASE_nonneg: 0 ≤ (↑BASE : ℤ) := by { unfold BASE, simp_int_casts, norm_num1 } lemma BASE_div_4_nonneg: 0 ≤ (↑BASE : ℤ) / 4 := int.div_nonneg BASE_nonneg (by norm_num) lemma SECP_REM_nonneg: 0 ≤ (↑SECP_REM : ℤ) := by { unfold SECP_REM, simp_int_casts, norm_num1 } lemma BASE_ne_zero_aux : (BASE : F) ≠ 0 := begin suffices : ((BASE : nat) : F) ≠ ((0 : nat) : F), { simpa }, intro h, have:= PRIME.nat_coe_field_inj _ _ h, { norm_num at this}, repeat {dsimp only [BASE, PRIME], norm_num } end lemma BASE_ne_zero_aux' : (2 : F)^86 ≠ 0 := begin suffices : ((2^86 : nat) : F) ≠ ((0 : nat) : F), { simpa }, intro h, have:= PRIME.nat_coe_field_inj _ _ h, { norm_num at this}, repeat {dsimp only [BASE, PRIME], norm_num } end @[irreducible] def SECP_PRIME : ℕ := BASE^3 / 4 - SECP_REM theorem SECP_PRIME_eq : (↑SECP_PRIME : ℤ) = (↑BASE : ℤ)^3 / 4 - ↑SECP_REM := begin simp only [SECP_PRIME], rw int.coe_nat_sub, rotate, { dsimp only [SECP_REM, BASE], norm_num }, refl, end /-- Some bounds use 3 * BASE - 1, and some use 3 * (BASE - 1). This theorem mediates between them. -/ theorem bound_slack : (3 : ℤ) * (BASE - 1) ≤ 3 * BASE - 1 := by { unfold BASE, simp_int_casts, norm_num } theorem bound_lt_prime : (3 : ℤ) * BASE - 1 < PRIME := by { unfold BASE, unfold PRIME, simp_int_casts, norm_num } end starkware.cairo.common.cairo_secp.constants
33d0d740485565d5e62c4a6c8ecbefc56fbca164
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Meta/Tactic/Injection.lean
c465c7e61526d7d215dc1a75fc380dcb8486e9b8
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,443
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 inductive InjectionResultCore := | 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 pure $ InjectionResultCore.subgoal mvarId aCtor.nfields | _ => throwTacticEx `injection mvarId "ill-formed noConfusion auxiliary construction" | _, _ => throwTacticEx `injection mvarId "equality of constructor applications expected" inductive InjectionResult := | 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) => 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) 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
9f95cefc658c8b716b8e53ed423d2330397920f6
eee9431f1775ed555dbf09e29e071194c6d586bf
/ACE/ex03.lean
06929cb8c8541a0a2aca21224a1ed8dbcf8b9546
[]
no_license
Paox2/myWorkInCollege
0d60abceb28d0228576f87ceb9f0a0aaeb944144
fadf8a93b27a56b2f5d8f0063087fdb71390cf93
refs/heads/master
1,679,972,166,761
1,617,740,970,000
1,617,740,970,000
256,950,200
0
0
null
null
null
null
UTF-8
Lean
false
false
5,605
lean
/- COMP2009-ACE Exercise 03 (Predicate logic) This exercise has 2 parts. In the 1st part you are supposed to formally define what certain relation bewteen humans are (like Father, brother-in-law etc). Here we use Lean only as a syntax and type checker. In the 2nd part we play logic poker again :-) but this time for predicate logic. -/ -- Wendi Han 20126355 namespace family -- Given the following type, predicates and relations: constant People : Type constants Male Female : People → Prop -- Male x means x is male -- Female x means x is fmeale constant Parent : People → People → Prop -- Parent x y means x is a parent of y constant Married : People → People → Prop -- Married x y means x is married to y /- Define the following relations (People → People → Prop) using the predicates and relations above: - Father x y = x is the father of y - Brother x y = x is the brother of y - Grandmother x y = x is the grandmother of y - FatherInLaw x y = x is the father-in-law of y - SisterInLaw x y = x is the sister in law of y - Uncle x y = x is the uncle of y If you are not sure about the definition of these terms, check them in wikipedia. If there is more than one option choose one. -/ /- As an example: here is the definition of Father: -/ def Father (x y : People) : Prop := Parent x y ∧ Male x -- insert your definitions here -- A sibling is a gender neutral word for a relative that shares at least one parent with the subject. def Sibling (x y : People) : Prop := ∃ z : People, Parent z y ∧ Parent z x def Brother (x y : People) : Prop := Sibling x y ∧ Male x def Grandmother (x y : People) : Prop := (∃ z : People, Parent x z ∧ Parent z y) ∧ Female x def FatherInLaw (x y : People) : Prop := (∃ z : People, Father x z ∧ Married z y) ∧ Male x def SisterInLaw (x y : People) : Prop := Female x ∧ ((∃ z : People, Sibling x z ∧ Married z y) ∨ (∃ z :People, Sibling z y ∧ Married x z)) def Uncle (x y : People) : Prop := (∃ z : People, Parent z y ∧ Brother x z) ∨ (∃ z : People, Parent z y ∧ (∃ a : People, Sibling a z ∧ Married a x) ∧ Male x) end family namespace poker /- We play the game of logic poker - but this time with predicate logic :-) You have to classify the propositions into a) provable intuitionistically (i.e. in plain lean) b) provable classically (using em : P ∨ ¬ P or raa : ¬¬ P → P). c) not provable classically. and then you have to prove the propositions in a) and b) accordingly. Here is how you score: We start with 10 points :-) For any proposition which you didn't classify correctly (or not at all) you loose 1 point. :-( For any proposition which is provable but you didn't prove you loose 1 point. :-( We stop subtracting points at 0. :-) Write the classification as a comment using -- after the proposition. You are only allowed to use the tactics introduced in the lecture (i.e. assume, exact, apply, constructor, cases, left, right, have, trivial, existsi, reflexivity, rewrite) Please only use the tactics in the way indicated in the script, otherwise you may lose upto 2 style points. For propositions classified into c) just keep "sorry," as the proof. -/ variable A : Type variables PP QQ : A → Prop variables RR : A → A → Prop variables P Q R : Prop open classical theorem raa : ¬ ¬ P → P := begin assume nnp, cases (em P) with p np, exact p, have f : false, apply nnp, exact np, cases f, end theorem ex01 : (∀ x:A, ∃ y : A , RR x y) → (∃ y : A, ∀ x : A, RR x y) := -- c) not provable classically begin sorry, end theorem ex02 : (∃ y : A, ∀ x : A, RR x y) → (∀ x:A, ∃ y : A , RR x y) := -- a) provable intuitionistically begin assume h, cases h with y r, assume x, existsi y, apply r, end theorem ex03 : ∀ x y : A, x = y → RR x y → RR x x := -- a) provable intuitionistically begin assume x y, assume h, rewrite h, assume r, exact r, end theorem ex04 : ∀ x y z : A, x ≠ y → x ≠ z → y ≠ z := -- c) not provable classically. begin sorry, end theorem ex05 : ∀ x y z : A, x = y → x ≠ z → y ≠ z := -- a) provable intuitionistically begin assume x y z, assume h a, rewrite<- h, exact a, end theorem ex06 : ∀ x y z : A, x ≠ y → (x ≠ z ∨ y ≠ z) := -- b) provable classically begin assume x y z, assume h, cases (em (y=z)) with a b, left, rewrite<- a, exact h, right, exact b, end theorem ex07 : ¬ ¬ (∀ x : A, PP x) → ∀ x : A, ¬ ¬ PP x := -- a) provable intuitionistically begin assume nnh x np, apply nnh, assume p, apply np, apply p, end theorem ex08 : (∀ x : A, ¬ ¬ PP x) → ¬ ¬ ∀ x : A, PP x := -- b) provable classically begin assume h, assume np, apply np, assume x, apply raa, apply h, end theorem ex09 : (∃ x : A, true) → (∃ x:A, PP x) → ∀ x : A,PP x := -- c) not provable classically. begin sorry, end theorem ex10 : (∃ x : A, true) → (∃ x:A, PP x → ∀ x : A,PP x) := -- b) provable classically begin cases (em (∀ x : A, PP x)) with p np, assume h, cases h with x t, existsi x, assume ppx, exact p, assume h, have f : ∃ x : A, ¬ PP x, apply raa, assume n, apply np, assume x, apply raa, assume npp, apply n, existsi x, exact npp, cases f with x npx, existsi x, assume p, have f : false, apply npx, exact p, cases f, end end poker
3f2a1c0d87fdf8ba5919f99867838bf7bc20c5f1
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/abel.lean
3fbfe92b7ffed7a6032042d23e2af783105db4b6
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
13,130
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 tactic.norm_num /-! # The `abel` tactic Evaluate expressions in the language of additive, commutative monoids and groups. -/ namespace tactic namespace abel meta structure cache := (α : expr) (univ : level) (α0 : expr) (is_group : bool) (inst : expr) meta def mk_cache (e : expr) : tactic cache := do α ← infer_type e, c ← mk_app ``add_comm_monoid [α] >>= mk_instance, cg ← try_core (mk_app ``add_comm_group [α] >>= mk_instance), u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, α0 ← expr.of_nat α 0, match cg with | (some cg) := return ⟨α, u, α0, tt, cg⟩ | _ := return ⟨α, u, α0, ff, c⟩ end meta def cache.app (c : cache) (n : name) (inst : expr) : list expr → expr := (@expr.const tt n [c.univ] c.α inst).mk_app meta def cache.mk_app (c : cache) (n inst : name) (l : list expr) : tactic expr := do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ c.app n m l meta def add_g : name → name | (name.mk_string s p) := name.mk_string (s ++ "g") p | n := n meta def cache.iapp (c : cache) (n : name) : list expr → expr := c.app (if c.is_group then add_g n else n) c.inst def term {α} [add_comm_monoid α] (n : ℕ) (x a : α) : α := n •ℕ x + a def termg {α} [add_comm_group α] (n : ℤ) (x a : α) : α := n •ℤ x + a meta def cache.mk_term (c : cache) (n x a : expr) : expr := c.iapp ``term [n, x, a] meta def cache.int_to_expr (c : cache) (n : ℤ) : tactic expr := expr.of_int (if c.is_group then `(ℤ) else `(ℕ)) n meta inductive normal_expr : Type | zero (e : expr) : normal_expr | nterm (e : expr) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr meta def normal_expr.e : normal_expr → expr | (normal_expr.zero e) := e | (normal_expr.nterm e _ _ _) := e meta instance : has_coe normal_expr expr := ⟨normal_expr.e⟩ meta instance : has_coe_to_fun normal_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ meta def normal_expr.term' (c : cache) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr := normal_expr.nterm (c.mk_term n.1 x a) n x a meta def normal_expr.zero' (c : cache) : normal_expr := normal_expr.zero c.α0 meta def normal_expr.to_list : normal_expr → list (ℤ × expr) | (normal_expr.zero _) := [] | (normal_expr.nterm _ (_, n) x a) := (n, x) :: a.to_list open normal_expr meta def normal_expr.to_string (e : normal_expr) : string := " + ".intercalate $ (to_list e).map $ λ ⟨n, e⟩, to_string n ++ " • (" ++ to_string e ++ ")" meta def normal_expr.pp (e : normal_expr) : tactic format := do l ← (to_list e).mmap (λ ⟨n, e⟩, do pe ← pp e, return (to_fmt n ++ " • (" ++ pe ++ ")")), return $ format.join $ l.intersperse ↑" + " meta instance : has_to_tactic_format normal_expr := ⟨normal_expr.pp⟩ meta def normal_expr.refl_conv (e : normal_expr) : tactic (normal_expr × expr) := do p ← mk_eq_refl e, return (e, p) theorem const_add_term {α} [add_comm_monoid α] (k n x a a') (h : k + a = a') : k + @term α _ n x a = term n x a' := by simp [h.symm, term]; ac_refl theorem const_add_termg {α} [add_comm_group α] (k n x a a') (h : k + a = a') : k + @termg α _ n x a = termg n x a' := by simp [h.symm, termg]; ac_refl theorem term_add_const {α} [add_comm_monoid α] (n x a k a') (h : a + k = a') : @term α _ n x a + k = term n x a' := by simp [h.symm, term, add_assoc] theorem term_add_constg {α} [add_comm_group α] (n x a k a') (h : a + k = a') : @termg α _ n x a + k = termg n x a' := by simp [h.symm, termg, add_assoc] theorem term_add_term {α} [add_comm_monoid α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @term α _ n₁ x a₁ + @term α _ n₂ x a₂ = term n' x a' := by simp [h₁.symm, h₂.symm, term, add_nsmul]; ac_refl theorem term_add_termg {α} [add_comm_group α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @termg α _ n₁ x a₁ + @termg α _ n₂ x a₂ = termg n' x a' := by simp [h₁.symm, h₂.symm, termg, add_gsmul]; ac_refl theorem zero_term {α} [add_comm_monoid α] (x a) : @term α _ 0 x a = a := by simp [term] theorem zero_termg {α} [add_comm_group α] (x a) : @termg α _ 0 x a = a := by simp [termg] meta def eval_add (c : cache) : normal_expr → normal_expr → tactic (normal_expr × expr) | (zero _) e₂ := do p ← mk_app ``zero_add [e₂], return (e₂, p) | e₁ (zero _) := do p ← mk_app ``add_zero [e₁], return (e₁, p) | he₁@(nterm e₁ n₁ x₁ a₁) he₂@(nterm e₂ n₂ x₂ a₂) := if expr.lex_lt x₁ x₂ then do (a', h) ← eval_add a₁ he₂, return (term' c n₁ x₁ a', c.iapp ``term_add_const [n₁.1, x₁, a₁, e₂, a', h]) else if x₁ ≠ x₂ then do (a', h) ← eval_add he₁ a₂, return (term' c n₂ x₂ a', c.iapp ``const_add_term [e₁, n₂.1, x₂, a₂, a', h]) else do (n', h₁) ← mk_app ``has_add.add [n₁.1, n₂.1] >>= norm_num.eval_field, (a', h₂) ← eval_add a₁ a₂, let k := n₁.2 + n₂.2, let p₁ := c.iapp ``term_add_term [n₁.1, x₁, a₁, n₂.1, a₂, n', a', h₁, h₂], if k = 0 then do p ← mk_eq_trans p₁ (c.iapp ``zero_term [x₁, a']), return (a', p) else return (term' c (n', k) x₁ a', p₁) theorem term_neg {α} [add_comm_group α] (n x a n' a') (h₁ : -n = n') (h₂ : -a = a') : -@termg α _ n x a = termg n' x a' := by simp [h₂.symm, h₁.symm, termg]; ac_refl meta def eval_neg (c : cache) : normal_expr → tactic (normal_expr × expr) | (zero e) := do p ← c.mk_app ``neg_zero ``add_group [], return (zero' c, p) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_neg.neg [n.1] >>= norm_num.eval_field, (a', h₂) ← eval_neg a, return (term' c (n', -n.2) x a', c.app ``term_neg c.inst [n.1, x, a, n', a', h₁, h₂]) def smul {α} [add_comm_monoid α] (n : ℕ) (x : α) : α := n •ℕ x def smulg {α} [add_comm_group α] (n : ℤ) (x : α) : α := n •ℤ x theorem zero_smul {α} [add_comm_monoid α] (c) : smul c (0 : α) = 0 := by simp [smul] theorem zero_smulg {α} [add_comm_group α] (c) : smulg c (0 : α) = 0 := by simp [smulg] theorem term_smul {α} [add_comm_monoid α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smul c a = a') : smul c (@term α _ n x a) = term n' x a' := by simp [h₂.symm, h₁.symm, term, smul, nsmul_add, mul_nsmul] theorem term_smulg {α} [add_comm_group α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smulg c a = a') : smulg c (@termg α _ n x a) = termg n' x a' := by simp [h₂.symm, h₁.symm, termg, smulg, gsmul_add, gsmul_mul] meta def eval_smul (c : cache) (k : expr × ℤ) : normal_expr → tactic (normal_expr × expr) | (zero _) := return (zero' c, c.iapp ``zero_smul [k.1]) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_mul.mul [k.1, n.1] >>= norm_num.eval_field, (a', h₂) ← eval_smul a, return (term' c (n', k.2 * n.2) x a', c.iapp ``term_smul [k.1, n.1, x, a, n', a', h₁, h₂]) theorem term_atom {α} [add_comm_monoid α] (x : α) : x = term 1 x 0 := by simp [term] theorem term_atomg {α} [add_comm_group α] (x : α) : x = termg 1 x 0 := by simp [termg] meta def eval_atom (c : cache) (e : expr) : tactic (normal_expr × expr) := do n1 ← c.int_to_expr 1, return (term' c (n1, 1) e (zero' c), c.iapp ``term_atom [e]) lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h theorem unfold_smul {α} [add_comm_monoid α] (n) (x y : α) (h : smul n x = y) : n •ℕ x = y := h theorem unfold_smulg {α} [add_comm_group α] (n : ℕ) (x y : α) (h : smulg (int.of_nat n) x = y) : n •ℕ x = y := h theorem unfold_gsmul {α} [add_comm_group α] (n : ℤ) (x y : α) (h : smulg n x = y) : gsmul n x = y := h lemma subst_into_smul {α} [add_comm_monoid α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smul α _ tl tr = t) : smul l r = t := by simp [prl, prr, prt] lemma subst_into_smulg {α} [add_comm_group α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smulg α _ tl tr = t) : smulg l r = t := by simp [prl, prr, prt] meta def eval (c : cache) : expr → tactic (normal_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add c e₁' e₂', p ← c.mk_app ``norm_num.subst_into_add ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | `(%%e₁ - %%e₂) := do e₂' ← mk_app ``has_neg.neg [e₂], e ← mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p], return (e', p') | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg c e₁, p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(nsmul %%e₁ %%e₂) := do n ← if c.is_group then mk_app ``int.of_nat [e₁] else return e₁, (e', p) ← eval $ c.iapp ``smul [n, e₂], return (e', c.iapp ``unfold_smul [e₁, e₂, e', p]) | `(gsmul %%e₁ %%e₂) := do guardb c.is_group, (e', p) ← eval $ c.iapp ``smul [e₁, e₂], return (e', c.app ``unfold_gsmul c.inst [e₁, e₂, e', p]) | `(smul %%e₁ %%e₂) := do guard (¬ c.is_group), (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, n ← e₁'.to_nat, (e₂', p₂) ← eval e₂, (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) | `(smulg %%e₁ %%e₂) := do guardb c.is_group, (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, n ← e₁'.to_int, (e₂', p₂) ← eval e₂, (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) | e := eval_atom c e meta def eval' (c : cache) (e : expr) : tactic (expr × expr) := do (e', p) ← eval c e, return (e', p) @[derive has_reflect] inductive normalize_mode | raw | term instance : inhabited normalize_mode := ⟨normalize_mode.term⟩ meta def normalize (mode := normalize_mode.term) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.term := [``term.equations._eqn_1, ``termg.equations._eqn_1, ``add_zero, ``one_nsmul, ``one_gsmul, ``gsmul_zero] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do c ← mk_cache e, (new_e, pr) ← match mode with | normalize_mode.raw := eval' c | normalize_mode.term := trans_conv (eval' c) (simplify lemmas []) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end abel namespace interactive open interactive interactive.types lean.parser open tactic.abel local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *additive*, commutative monoids and groups. This version of `abel` fails if the target is not an equality that is provable by the axioms of commutative monoids/groups. -/ meta def abel1 : tactic unit := do `(%%e₁ = %%e₂) ← target, c ← mk_cache e₁, (e₁', p₁) ← eval c e₁, (e₂', p₂) ← eval c e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def abel.mode : lean.parser abel.normalize_mode := with_desc "(raw|term)?" $ do mode ← ident?, match mode with | none := return abel.normalize_mode.term | some `term := return abel.normalize_mode.term | some `raw := return abel.normalize_mode.raw | _ := failed end /-- Evaluate expressions in the language of *additive*, commutative monoids and groups. It attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails, it falls back to rewriting all monoid expressions into a normal form. If there is an `at` specifier, it rewrites the given target into a normal form. ```lean example {α : Type*} {a b : α} [add_comm_monoid α] : a + (b + a) = a + a + b := by abel example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel example {α : Type*} {a b : α} [add_comm_group α] (hyp : a + a - a = b - b) : a = 0 := by { abel at hyp, exact hyp } ``` -/ meta def abel (SOP : parse abel.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := abel1 | _ := failed end <|> do ns ← loc.get_locals, tt ← tactic.replace_at (normalize SOP) ns loc.include_goal | fail "abel failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "abel", category := doc_category.tactic, decl_names := [`tactic.interactive.abel], tags := ["arithmetic", "decision procedure"] } end interactive end tactic
4db1996b86b3c64efeb7ee47b9b14bf389383183
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/meta/declaration.lean
0f125589fc4e2848a9bef6374993a21086831cb7
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
5,187
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.expr init.meta.name init.meta.task /- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. For definitions marked as regular, we also have a hint for constraints such as (f a) =?= (f b) if self_opt == true, then checker will first try to solve (a =?= b), only if it fails, it unfolds f. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during type checking. Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator). Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel. -/ inductive reducibility_hints | opaque : reducibility_hints | abbrev : reducibility_hints | regular : nat → bool → reducibility_hints /- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/ meta inductive declaration /- definition: name, list universe parameters, type, value, is_trusted -/ | defn : name → list name → expr → expr → reducibility_hints → bool → declaration /- theorem: name, list universe parameters, type, value (remark: theorems are always trusted) -/ | thm : name → list name → expr → task expr → declaration /- constant assumption: name, list universe parameters, type, is_trusted -/ | cnst : name → list name → expr → bool → declaration /- axiom : name → list universe parameters, type (remark: axioms are always trusted) -/ | ax : name → list name → expr → declaration meta def mk_definition (n : name) (ls : list name) (v : expr) (e : expr) : declaration := declaration.defn n ls v e (reducibility_hints.regular 1 tt) tt meta def declaration.to_name : declaration → name | (declaration.defn n ls t v h tr) := n | (declaration.thm n ls t v) := n | (declaration.cnst n ls t tr) := n | (declaration.ax n ls t) := n meta def declaration.univ_params : declaration → list name | (declaration.defn n ls t v h tr) := ls | (declaration.thm n ls t v) := ls | (declaration.cnst n ls t tr) := ls | (declaration.ax n ls t) := ls meta def declaration.type : declaration → expr | (declaration.defn n ls t v h tr) := t | (declaration.thm n ls t v) := t | (declaration.cnst n ls t tr) := t | (declaration.ax n ls t) := t meta def declaration.value : declaration → expr | (declaration.defn n ls t v h tr) := v | (declaration.thm n ls t v) := v^.get | _ := default expr meta def declaration.update_type : declaration → expr → declaration | (declaration.defn n ls t v h tr) new_t := declaration.defn n ls new_t v h tr | (declaration.thm n ls t v) new_t := declaration.thm n ls new_t v | (declaration.cnst n ls t tr) new_t := declaration.cnst n ls new_t tr | (declaration.ax n ls t) new_t := declaration.ax n ls new_t meta def declaration.update_name : declaration → name → declaration | (declaration.defn n ls t v h tr) new_n := declaration.defn new_n ls t v h tr | (declaration.thm n ls t v) new_n := declaration.thm new_n ls t v | (declaration.cnst n ls t tr) new_n := declaration.cnst new_n ls t tr | (declaration.ax n ls t) new_n := declaration.ax new_n ls t meta def declaration.update_value : declaration → expr → declaration | (declaration.defn n ls t v h tr) new_v := declaration.defn n ls t new_v h tr | (declaration.thm n ls t v) new_v := declaration.thm n ls t (task.pure new_v) | d new_v := d meta def declaration.to_definition : declaration → declaration | (declaration.cnst n ls t tr) := declaration.defn n ls t (default expr) reducibility_hints.abbrev tr | (declaration.ax n ls t) := declaration.thm n ls t (task.pure (default expr)) | d := d /- Instantiate a universe polymorphic declaration type with the given universes. -/ meta constant declaration.instantiate_type_univ_params : declaration → list level → option expr /- Instantiate a universe polymorphic declaration value with the given universes. -/ meta constant declaration.instantiate_value_univ_params : declaration → list level → option expr
4fb7698d3a9394794664555ba111b86c023c16ef
c3de33d4701e6113627153fe1103b255e752ed7d
/data/bool.lean
05d912c8928f9b6b0c4a53a03915885f336ec20b
[]
no_license
jroesch/library_dev
77d2b246ff47ab05d55cb9706a37d3de97038388
4faa0a45c6aa7eee6e661113c2072b8840bff79b
refs/heads/master
1,611,281,606,352
1,495,661,644,000
1,495,661,644,000
92,340,430
0
0
null
1,495,663,344,000
1,495,663,344,000
null
UTF-8
Lean
false
false
4,692
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad -/ -- TODO(Jeremy): these used to be proved by rec_simp. Write a special tactic for these, or -- get auto or super to do them. namespace bool -- TODO(Jeremy): is this right? @[simp] theorem coe_tt : (↑tt : Prop) := dec_trivial theorem band_tt (a : bool) : a && tt = a := by cases a; refl theorem tt_band (a : bool) : tt && a = a := by cases a; refl theorem band_ff (a : bool) : a && ff = ff := by cases a; refl theorem ff_band (a : bool) : ff && a = ff := by cases a; refl theorem bor_tt (a : bool) : a || tt = tt := by cases a; refl theorem tt_bor (a : bool) : tt || a = tt := by cases a; refl theorem bor_ff (a : bool) : a || ff = a := by cases a; refl theorem ff_bor (a : bool) : ff || a = a := by cases a; refl attribute [simp] band_tt tt_band band_ff ff_band bor_tt tt_bor bor_ff ff_bor theorem band_eq_tt (a b : bool) : (a && b = tt) = (a = tt ∧ b = tt) := by cases a; cases b; simp theorem band_eq_ff (a b : bool) : (a && b = ff) = (a = ff ∨ b = ff) := by cases a; cases b; simp theorem bor_eq_tt (a b : bool) : (a || b = tt) = (a = tt ∨ b = tt) := by cases a; cases b; simp theorem bor_eq_ff (a b : bool) : (a || b = ff) = (a = ff ∧ b = ff) := by cases a; cases b; simp theorem dichotomy (b : bool) : b = ff ∨ b = tt := by cases b; simp @[simp] theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl @[simp] theorem cond_tt {A : Type} (t e : A) : cond tt t e = t := rfl theorem eq_tt_of_ne_ff {a : bool} : a ≠ ff → a = tt := by cases a; simp theorem eq_ff_of_ne_tt {a : bool} : a ≠ tt → a = ff := by cases a; simp theorem absurd_of_eq_ff_of_eq_tt {B : Prop} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := by cases a; contradiction @[simp] theorem bor_comm (a b : bool) : a || b = b || a := by cases a; cases b; simp @[simp] theorem bor_assoc (a b c : bool) : (a || b) || c = a || (b || c) := by cases a; cases b; simp @[simp] theorem bor_left_comm (a b c : bool) : a || (b || c) = b || (a || c) := by cases a; cases b; simp theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ∨ b = tt := begin cases a, simp, intro h, simp [h], simp end theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt := by simp [H] theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt := by simp [H] @[simp] theorem band_self (a : bool) : a && a = a := by cases a; simp @[simp] theorem band_comm (a b : bool) : a && b = b && a := by cases a; simp @[simp] theorem band_assoc (a b c : bool) : (a && b) && c = a && (b && c) := by cases a; simp @[simp] theorem band_left_comm (a b c : bool) : a && (b && c) = b && (a && c) := by cases a; simp theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt := begin cases a, simp at H, simp [H] end theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := begin cases a, simp [H₁, H₂], simp [H₂] end theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt := begin cases a, contradiction, simp at H, exact H end @[simp] theorem bnot_false : bnot ff = tt := rfl @[simp] theorem bnot_true : bnot tt = ff := rfl @[simp] theorem bnot_bnot (a : bool) : bnot (bnot a) = a := by cases a; simp theorem eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt := by cases a; simp theorem eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff := by cases a; simp definition bxor : bool → bool → bool | ff ff := ff | ff tt := tt | tt ff := tt | tt tt := ff @[simp] lemma ff_bxor_ff : bxor ff ff = ff := rfl @[simp] lemma ff_bxor_tt : bxor ff tt = tt := rfl @[simp] lemma tt_bxor_ff : bxor tt ff = tt := rfl @[simp] lemma tt_bxor_tt : bxor tt tt = ff := rfl @[simp] lemma bxor_self (a : bool) : bxor a a = ff := by cases a; simp @[simp] lemma bxor_ff (a : bool) : bxor a ff = a := by cases a; simp @[simp] lemma bxor_tt (a : bool) : bxor a tt = bnot a := by cases a; simp @[simp] lemma ff_bxor (a : bool) : bxor ff a = a := by cases a; simp @[simp] lemma tt_bxor (a : bool) : bxor tt a = bnot a := by cases a; simp @[simp] lemma bxor_comm (a b : bool) : bxor a b = bxor b a := by cases a; simp @[simp] lemma bxor_assoc (a b c : bool) : bxor (bxor a b) c = bxor a (bxor b c) := by cases a; cases b; simp @[simp] lemma bxor_left_comm (a b c : bool) : bxor a (bxor b c) = bxor b (bxor a c) := by cases a; cases b; simp end bool
4908b900e558dce13e1b55286d017dea67923a95
5e42295de7f5bcdf224b94603a8ec29b17c2d367
/normalizer3.lean
fef5e86fc3237e764a8706167463016ac3c70810
[]
no_license
pnmadelaine/lean_polya
9369e0d87dce773f91383bb58ac6fde0a00a1a40
1c62b0b3fa71044b0225ce28030627d251b08ebc
refs/heads/master
1,590,161,172,243
1,515,010,019,000
1,515,010,019,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,170
lean
import datatypes norm_num-- blackboard namespace polya section aux #check expr.is_numeral meta def is_num : expr → bool | `(bit0 %%e) := is_num e | `(bit1 %%e) := is_num e | `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) := tt | `(-%%a) := is_num a | `(%%a / %%b) := is_num a && is_num b | _ := ff meta def mk_neg : expr → expr | `((-%%lhs) * %%rhs) := `(%%lhs * %%rhs : ℚ) | `(%%lhs * %%rhs) := `((-%%lhs) * %%rhs : ℚ) | a := `((-1 : ℚ)*%%a) meta def get_sum_components : expr → list expr | `(%%lhs + %%rhs) := rhs::(get_sum_components lhs) | `(%%lhs - %%rhs) := mk_neg rhs::(get_sum_components lhs) | a := [a] meta def get_prod_components : expr → list expr | `(%%lhs * %%rhs) := rhs::(get_prod_components lhs) | a := [a] meta def is_sum (e : expr) : bool := e.is_app_of ``has_add.add || e.is_app_of ``has_sub.sub meta def is_prod (e : expr) : bool := e.is_app_of ``has_mul.mul || e.is_app_of ``rat.pow open tactic meta def get_comps_of_mul (e : expr) : tactic (expr × ℚ) := match e with | `(%%lhs * %%rhs) := (do c ← eval_expr ℚ lhs, return (rhs, c)) <|> return (e, 1) | `(%%num / %%denom) := (do c ← eval_expr ℚ denom, return (num, 1/c)) <|> return (e, 1) | f := return (f, 1) end meta def get_comps_of_exp (e : expr) : tactic (expr × ℤ) := match e with | `(rat.pow %%base %%exp) := (do z ← eval_expr ℤ exp, return (base, z)) <|> return (e, 1) | f := return (f, 1) end end aux /-meta mutual inductive sterm, term with sterm : Type | scaled : ℚ → term → sterm with term : Type | add_term : list sterm → term | mul_term : list (term × ℤ) → term | atom : expr → term-/ meta inductive term : Type | add_term : rb_map term ℚ → term | mul_term : rb_map term ℤ → term | atom : expr → term namespace term meta def order : term → term → ordering | (add_term m) (add_term n) := @has_ordering.cmp _ (@list.has_ordering _ ⟨order⟩) m.keys n.keys | (add_term _) _ := ordering.gt | _ (add_term _) := ordering.lt | (mul_term m) (mul_term n) := @has_ordering.cmp _ (@list.has_ordering _ ⟨order⟩) m.keys n.keys | (mul_term _) (atom _) := ordering.gt | (atom _) (mul_term _) := ordering.lt | (atom e1) (atom e2) := has_ordering.cmp e1 e2 meta instance : has_ordering term := ⟨order⟩ meta def add_term_empty : term := add_term mk_rb_map meta def mul_term_empty : term := mul_term mk_rb_map end term meta structure sterm := (coeff : ℚ) (body : term) private meta def add_term_coeff_pair (map : rb_map term ℚ) (st : term × ℚ) : rb_map term ℚ := match map.find st.1 with | none := map.insert st.1 st.2 | some c := map.insert st.1 (st.2 + c) end private meta def add_term_coeff_pair_list (map : rb_map term ℚ) (l : list (term × ℚ)) : rb_map term ℚ := l.foldl add_term_coeff_pair map private meta def add_sterm (map : rb_map term ℚ) (st : sterm) : rb_map term ℚ := add_term_coeff_pair map (st.body, st.coeff) meta def add_term_of_sterm_list (l : list sterm) : term := term.add_term $ l.foldl add_sterm mk_rb_map private meta def pow_term_exp (map : rb_map term ℤ) (pr : term × ℤ) : rb_map term ℤ := match map.find pr.1 with | none := map.insert pr.1 pr.2 | some c := map.insert pr.1 (pr.2 + c) end private meta def pow_term_exp_list (map : rb_map term ℤ) (l : list (term × ℤ)) : rb_map term ℤ := l.foldl pow_term_exp map meta def mul_term_of_term_exp_list (l : list (term × ℤ)) : term := term.mul_term $ l.foldl pow_term_exp mk_rb_map meta def term.is_zero : term → bool | (term.add_term m) := m.size = 0 | _ := ff meta def sterm.is_zero (st : sterm) : bool := st.body.is_zero || (st.coeff = 0) meta def term.scale (q : ℚ) (t : term) : sterm := ⟨q, t⟩ meta def sterm.scale (q : ℚ) (st : sterm) : sterm := { st with coeff := st.coeff * q } meta def sterm.of_pair (pr : term × ℚ) : sterm := ⟨pr.2, pr.1⟩ open tactic private meta def expr.to_term_aux (tst : expr → tactic sterm) : expr → tactic term | e := if is_sum e then let scs := get_sum_components e in add_term_of_sterm_list <$> scs.mmap tst else if is_prod e then let scs := get_prod_components e in do scs' ← scs.mmap get_comps_of_exp, mul_term_of_term_exp_list <$> scs'.mmap (λ pr, do tm ← expr.to_term_aux pr.1, return (tm, pr.2)) else return $ term.atom e private meta def split_num_nonnum_prod_comps : list expr → list expr × list expr | [] := ([], []) | (e::l) := let (t1, t2) := split_num_nonnum_prod_comps l in if is_num e then (e::t1, t2) else (t1, e::t2) private meta def fold_op_app_aux (op : pexpr) : expr → list expr → tactic expr | h [] := return h | h (h'::t) := do h'' ← to_expr ``(%%op %%h %%h'), fold_op_app_aux h'' t private meta def fold_op_app (op : pexpr) (dflt : expr) : list expr → tactic expr | [] := return dflt | (h::t) := fold_op_app_aux op h t meta def expr.to_sterm : expr → tactic sterm | e := if is_num e then do q ← eval_expr ℚ e, return ⟨q, (term.atom `(1 : ℚ))⟩ else if is_prod e then let scs := get_prod_components e, (numcs, nnumcs) := split_num_nonnum_prod_comps scs in do numcs' ← numcs.mmap (eval_expr ℚ), let q := numcs'.foldl (*) 1, sterm.mk q <$> ((fold_op_app ``((*)) `(1 : ℚ) nnumcs) >>= expr.to_term_aux expr.to_sterm) else sterm.mk 1 <$> expr.to_term_aux expr.to_sterm e /-match e with | `(%%c*%%t) := if is_num c then do q ← eval_expr ℚ c, sterm.scale q <$> expr.to_sterm t else sterm.mk 1 <$> expr.to_term_aux expr.to_sterm e | t := sterm.mk 1 <$> expr.to_term_aux expr.to_sterm t end -/ meta def expr.to_term : expr → tactic term := expr.to_term_aux expr.to_sterm private meta def term.to_expr_aux (ste : sterm → tactic expr) : term → tactic expr | (term.add_term l) := if l.size = 0 then return `(0 : ℚ) else do l' ← l.to_list.mmap (λ pr, ste (sterm.of_pair pr)), fold_op_app ``((+)) `(0 : ℚ) l' | (term.mul_term l) := if l.size = 0 then return `(1 : ℚ) else do l' ← l.to_list.mmap (λ pr, do e' ← term.to_expr_aux pr.1, return (e', pr.2)), let l'' := l'.map (λ pr, `(rat.pow %%(pr.1) %%(pr.2.reflect))), fold_op_app ``((*)) `(1 : ℚ) l'' | (term.atom e) := return e meta def sterm.to_expr : sterm → tactic expr | ⟨c, t⟩ := if t.is_zero || (c = 0) then return `(0 : ℚ) else do t' ← term.to_expr_aux sterm.to_expr t, return `(%%(c.reflect)*%%t' : ℚ) meta def term.to_expr : term → tactic expr := term.to_expr_aux sterm.to_expr meta def term.to_tactic_format (e : term) : tactic format := do ex ← e.to_expr, tactic_format_expr ex meta def sterm.to_tactic_format (e : sterm) : tactic format := do ex ← e.to_expr, tactic_format_expr ex meta instance term.has_to_tactic_format : has_to_tactic_format term := ⟨term.to_tactic_format⟩ meta instance sterm.has_to_tactic_format : has_to_tactic_format sterm := ⟨sterm.to_tactic_format⟩ section canonize private meta def coeff_and_terms_of_sterm_z_list : list (sterm × ℤ) → ℚ × list (term × ℤ) | [] := (1, []) | ((⟨c, tm⟩, z)::t) := let (q, l) := coeff_and_terms_of_sterm_z_list t in (q * rat.pow c z, (tm, z)::l) /-private meta def coeff_and_terms_of_sterm_z_list : ℚ → list (term × ℤ) → list (sterm × ℤ) → ℚ × list (term × ℤ) | acc l [] := (acc, l) | acc l ((sterm.scaled c tm, z)::t) := (tm, z)::coeff_and_terms_of_sterm_z_list (acc*rat.pow c z) t-/ -- only applies to add_term private meta def term.leading_coeff : term → ℚ | (term.add_term l) := match l.to_list with | [] := 1 | ((_, c)::t) := c end | _ := 1 -- only applies to add_term private meta def term.scale_coeffs (c : ℚ) : term → term | (term.add_term l) := term.add_term $ l.map (λ c', c*c') | a := a -- doesn't flatten private meta def term.canonize_aux (stc : sterm → tactic sterm) : term → tactic sterm | (term.add_term l) := do l' ← add_term_of_sterm_list <$> l.to_list.mmap (λ pr, stc (sterm.of_pair pr)), let c := term.leading_coeff l', return ⟨c, term.scale_coeffs (1/c) l'⟩ /- do l' : list (sterm × expr) ← l.to_list.mmap (λ st, do st' ← stc (sterm.of_pair st), e ← st'.to_expr, return (st', e)), let l' := (l'.qsort (λ pr1 pr2 : sterm × expr, pr2.2.lt pr1.2)).map prod.fst, match l' with | [] := return $ sterm.mk 1 term.add_term_empty | [st] := return st | (⟨c, tm⟩)::t := if c = 1 then return $ sterm.mk 1 (add_term_of_sterm_list l') else return $ sterm.mk c (add_term_of_sterm_list (l'.map (sterm.scale (1/c)))) end-/ | (term.mul_term l) := do l' ← l.to_list.mmap (λ pr, do t' ← term.canonize_aux pr.1, return (t', pr.2)), let (q, l'') := coeff_and_terms_of_sterm_z_list l', return ⟨q, mul_term_of_term_exp_list l''⟩ /- do l' ← l.to_list.mmap (λ pr, do t' ← term.canonize_aux pr.1, e ← t'.to_expr, return ((t', pr.2), e)), let l' := (l'.qsort (λ pr1 pr2 : (sterm × ℤ) × expr, pr2.2.lt pr1.2)), let l' := l'.map prod.fst, let (q, l'') := coeff_and_terms_of_sterm_z_list l', return $ sterm.mk q (mul_term_of_term_exp_list l'')-/ | (term.atom e) := return $ sterm.mk 1 (term.atom e) -- doesn't flatten private meta def sterm.canonize_aux : sterm → tactic sterm | ⟨c, t⟩ := do sterm.mk c' t' ← term.canonize_aux sterm.canonize_aux t, return $ sterm.mk (c*c') t' /-private meta def flatten_sum_list : list (term × ℚ) → list (term × ℚ) | [] := [] | ((term.add_term tm, c)::t) := (tm.to_list.map (λ pr : term × ℚ, (pr.1, pr.2*c))).append (flatten_sum_list t) | (h::t) := h::flatten_sum_list t private meta def flatten_prod_list : list (term × ℤ) → list (term × ℤ) | [] := [] | ((term.mul_term l, z)::t) := (l.to_list.map (λ pr : term × ℤ, (pr.1, pr.2*z))).append (flatten_prod_list t) | (h::t) := h::flatten_prod_list t-/ private meta def scale_list {α} [has_mul α] (l : list (term × α)) (q : α) : list (term × α) := l.map (λ pr, {pr with snd := pr.snd * q}) private meta def flatten_sum_term_aux (t : term) (coeff : ℚ) (map : rb_map term ℚ) : rb_map term ℚ := match t with | term.add_term l := add_term_coeff_pair_list map (scale_list l.to_list coeff) | _ := map.insert t coeff end private meta def flatten_sum_term (map : rb_map term ℚ) : rb_map term ℚ := map.fold mk_rb_map flatten_sum_term_aux private meta def flatten_mul_term_aux (t : term) (exp : ℤ) (map : rb_map term ℤ) : rb_map term ℤ := match t with | term.mul_term l := pow_term_exp_list map (scale_list l.to_list exp) | _ := map.insert t exp end private meta def flatten_mul_term (map : rb_map term ℤ) : rb_map term ℤ := map.fold mk_rb_map flatten_mul_term_aux private meta def term.flatten : term → term | (term.add_term l) := term.add_term $ flatten_sum_term l --$ rb_map.of_list (flatten_sum_list l.to_list) | (term.mul_term l) := term.mul_term $ flatten_mul_term l --$ rb_map.of_list (flatten_prod_list l.to_list) | a := a private meta def sterm.flatten : sterm → sterm | (sterm.mk c t) := sterm.mk c (term.flatten t) meta def sterm.canonize : sterm → tactic sterm := sterm.canonize_aux ∘ sterm.flatten meta def term.canonize (t : term) : tactic sterm := term.canonize_aux sterm.canonize (term.flatten t) meta def expr.canonize (e : expr) : tactic sterm := match e with | `(0 : ℚ) := return $ sterm.mk 0 (term.add_term_empty) | _ := expr.to_sterm e >>= sterm.canonize end meta def expr.canonize_to_expr (e : expr) : tactic expr := match e with | `(0 : ℚ) := return e | _ := expr.to_sterm e >>= sterm.canonize >>= sterm.to_expr end theorem canonized_inequality {P : Prop} (h : P) (canP : Prop) : canP := sorry meta def prove_inequality (lhs rhs pf : expr) (op : gen_comp) : tactic expr := do sterm.mk clhs tlhs ← expr.canonize lhs, --trace "tlhs", trace tlhs, srhs ← expr.canonize rhs, --trace "srhs", trace srhs, elhs ← tlhs.to_expr, if clhs = 0 then do erhs ← srhs.to_expr, tp ← op.reverse.to_function erhs elhs, mk_app ``canonized_inequality [pf, tp] else do erhs ← (srhs.scale (1/clhs)).to_expr, tp ← ((if clhs < 0 then gen_comp.reverse else id) op).to_function elhs erhs, --to_expr ``(%%op %%elhs %%erhs), mk_app ``canonized_inequality [pf, tp] meta def canonize_hyp : expr → tactic expr | e := do tp ← infer_type e, match tp with /-| `(0 > %%e) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(0 > %%ce)] | `(0 ≥ %%e) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(0 ≥ %%ce)] | `(0 < %%e) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(0 < %%ce)] | `(0 ≤ %%e) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(0 ≤ %%ce)] | `(%%e > 0) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(%%ce > 0)] | `(%%e ≥ 0) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(%%ce ≥ 0)] | `(%%e < 0) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(%%ce < 0)] | `(%%e ≤ 0) := do ce ← expr.canonize e, mk_app ``canonized_inequality [e, `(%%ce ≤ 0)]-/ | `(%%lhs ≤ %%rhs) := prove_inequality lhs rhs e gen_comp.le | `(%%lhs < %%rhs) := prove_inequality lhs rhs e gen_comp.lt | `(%%lhs ≥ %%rhs) := prove_inequality lhs rhs e gen_comp.ge | `(%%lhs > %%rhs) := prove_inequality lhs rhs e gen_comp.gt | `(%%lhs = %%rhs) := prove_inequality lhs rhs e gen_comp.eq | `(%%lhs ≠ %%rhs) := prove_inequality lhs rhs e gen_comp.ne | _ := /-trace e >>-/ do s ← to_string <$> pp e, fail $ "didn't recognize " ++ s end end canonize constants a b c u v w z y x: ℚ run_cmd (expr.to_term `(1*a + 3*(b + c) + 5*b)) >>= term.canonize >>= trace run_cmd expr.canonize `(rat.pow (1*u + (2*rat.pow (1*rat.pow v 2 + 23*1) 3) + 1*z) 3) >>= trace end polya
cd517ebd4923fb9ab7148524b05aced2557710b0
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/functor/reflects_isomorphisms.lean
381f1b336220aea7209fbe4bb8f0574f4af2f6d9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,849
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.functor.fully_faithful /-! # Functors which reflect isomorphisms A functor `F` reflects isomorphisms if whenever `F.map f` is an isomorphism, `f` was too. It is formalized as a `Prop` valued typeclass `reflects_isomorphisms F`. Any fully faithful functor reflects isomorphisms. -/ open category_theory namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ variables {C : Type u₁} [category.{v₁} C] section reflects_iso variables {D : Type u₂} [category.{v₂} D] variables {E : Type u₃} [category.{v₃} E] /-- Define what it means for a functor `F : C ⥤ D` to reflect isomorphisms: for any morphism `f : A ⟶ B`, if `F.map f` is an isomorphism then `f` is as well. Note that we do not assume or require that `F` is faithful. -/ class reflects_isomorphisms (F : C ⥤ D) : Prop := (reflects : Π {A B : C} (f : A ⟶ B) [is_iso (F.map f)], is_iso f) /-- If `F` reflects isos and `F.map f` is an iso, then `f` is an iso. -/ lemma is_iso_of_reflects_iso {A B : C} (f : A ⟶ B) (F : C ⥤ D) [is_iso (F.map f)] [reflects_isomorphisms F] : is_iso f := reflects_isomorphisms.reflects F f @[priority 100] instance of_full_and_faithful (F : C ⥤ D) [full F] [faithful F] : reflects_isomorphisms F := { reflects := λ X Y f i, by exactI ⟨⟨F.preimage (inv (F.map f)), ⟨F.map_injective (by simp), F.map_injective (by simp)⟩⟩⟩ } instance (F : C ⥤ D) (G : D ⥤ E) [reflects_isomorphisms F] [reflects_isomorphisms G] : reflects_isomorphisms (F ⋙ G) := ⟨λ _ _ f (hf : is_iso (G.map _)), by { resetI, haveI := is_iso_of_reflects_iso (F.map f) G, exact is_iso_of_reflects_iso f F }⟩ end reflects_iso end category_theory
da15a0daa2e00598858b9249f64deb738a699a77
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/intervals/basic.lean
250eba029ea6806add4885c86f8ff46718bf4f49
[ "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
54,383
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, Patrick Massot, Yury Kudryashov, Rémy Degenne -/ import order.min_max import data.set.prod /-! # Intervals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). TODO: This is just the beginning; a lot of rules are missing -/ open function order_dual (to_dual of_dual) variables {α β : Type*} namespace set section preorder variables [preorder α] {a a₁ a₂ b b₁ b₂ c x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} lemma Ioo_def (a b : α) : {x | a < x ∧ x < b} = Ioo a b := rfl lemma Ico_def (a b : α) : {x | a ≤ x ∧ x < b} = Ico a b := rfl lemma Iio_def (a : α) : {x | x < a} = Iio a := rfl lemma Icc_def (a b : α) : {x | a ≤ x ∧ x ≤ b} = Icc a b := rfl lemma Iic_def (b : α) : {x | x ≤ b} = Iic b := rfl lemma Ioc_def (a b : α) : {x | a < x ∧ x ≤ b} = Ioc a b := rfl lemma Ici_def (a : α) : {x | a ≤ x} = Ici a := rfl lemma Ioi_def (a : α) : {x | a < x} = Ioi a := rfl @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl instance decidable_mem_Ioo [decidable (a < x ∧ x < b)] : decidable (x ∈ Ioo a b) := by assumption instance decidable_mem_Ico [decidable (a ≤ x ∧ x < b)] : decidable (x ∈ Ico a b) := by assumption instance decidable_mem_Iio [decidable (x < b)] : decidable (x ∈ Iio b) := by assumption instance decidable_mem_Icc [decidable (a ≤ x ∧ x ≤ b)] : decidable (x ∈ Icc a b) := by assumption instance decidable_mem_Iic [decidable (x ≤ b)] : decidable (x ∈ Iic b) := by assumption instance decidable_mem_Ioc [decidable (a < x ∧ x ≤ b)] : decidable (x ∈ Ioc a b) := by assumption instance decidable_mem_Ici [decidable (a ≤ x)] : decidable (x ∈ Ici a) := by assumption instance decidable_mem_Ioi [decidable (a < x)] : decidable (x ∈ Ioi a) := by assumption @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : Ici (to_dual a) = of_dual ⁻¹' Iic a := rfl @[simp] lemma dual_Iic : Iic (to_dual a) = of_dual ⁻¹' Ici a := rfl @[simp] lemma dual_Ioi : Ioi (to_dual a) = of_dual ⁻¹' Iio a := rfl @[simp] lemma dual_Iio : Iio (to_dual a) = of_dual ⁻¹' Ioi a := rfl @[simp] lemma dual_Icc : Icc (to_dual a) (to_dual b) = of_dual ⁻¹' Icc b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : Ioc (to_dual a) (to_dual b) = of_dual ⁻¹' Ico b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : Ico (to_dual a) (to_dual b) = of_dual ⁻¹' Ioc b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : Ioo (to_dual a) (to_dual b) = of_dual ⁻¹' Ioo b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, hx.1.trans hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, hx.1.trans_lt hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, hx.1.trans_le hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, ha.trans hb, exists_between⟩ @[simp] lemma nonempty_Ioi [no_max_order α] : (Ioi a).nonempty := exists_gt a @[simp] lemma nonempty_Iio [no_min_order α] : (Iio a).nonempty := exists_lt a lemma nonempty_Icc_subtype (h : a ≤ b) : nonempty (Icc a b) := nonempty.to_subtype (nonempty_Icc.mpr h) lemma nonempty_Ico_subtype (h : a < b) : nonempty (Ico a b) := nonempty.to_subtype (nonempty_Ico.mpr h) lemma nonempty_Ioc_subtype (h : a < b) : nonempty (Ioc a b) := nonempty.to_subtype (nonempty_Ioc.mpr h) /-- An interval `Ici a` is nonempty. -/ instance nonempty_Ici_subtype : nonempty (Ici a) := nonempty.to_subtype nonempty_Ici /-- An interval `Iic a` is nonempty. -/ instance nonempty_Iic_subtype : nonempty (Iic a) := nonempty.to_subtype nonempty_Iic lemma nonempty_Ioo_subtype [densely_ordered α] (h : a < b) : nonempty (Ioo a b) := nonempty.to_subtype (nonempty_Ioo.mpr h) /-- In an order without maximal elements, the intervals `Ioi` are nonempty. -/ instance nonempty_Ioi_subtype [no_max_order α] : nonempty (Ioi a) := nonempty.to_subtype nonempty_Ioi /-- In an order without minimal elements, the intervals `Iio` are nonempty. -/ instance nonempty_Iio_subtype [no_min_order α] : nonempty (Iio a) := nonempty.to_subtype nonempty_Iio instance [no_min_order α] : no_min_order (Iio a) := ⟨λ a, let ⟨b, hb⟩ := exists_lt (a : α) in ⟨⟨b, lt_trans hb a.2⟩, hb⟩⟩ instance [no_min_order α] : no_min_order (Iic a) := ⟨λ a, let ⟨b, hb⟩ := exists_lt (a : α) in ⟨⟨b, hb.le.trans a.2⟩, hb⟩⟩ instance [no_max_order α] : no_max_order (Ioi a) := order_dual.no_max_order (Iio (to_dual a)) instance [no_max_order α] : no_max_order (Ici a) := order_dual.no_max_order (Iic (to_dual a)) @[simp] lemma Icc_eq_empty (h : ¬a ≤ b) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans hb) @[simp] lemma Ico_eq_empty (h : ¬a < b) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans_lt hb) @[simp] lemma Ioc_eq_empty (h : ¬a < b) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans_le hb) @[simp] lemma Ioo_eq_empty (h : ¬a < b) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans hb) @[simp] lemma Icc_eq_empty_of_lt (h : b < a) : Icc a b = ∅ := Icc_eq_empty h.not_le @[simp] lemma Ico_eq_empty_of_le (h : b ≤ a) : Ico a b = ∅ := Ico_eq_empty h.not_lt @[simp] lemma Ioc_eq_empty_of_le (h : b ≤ a) : Ioc a b = ∅ := Ioc_eq_empty h.not_lt @[simp] lemma Ioo_eq_empty_of_le (h : b ≤ a) : Ioo a b = ∅ := Ioo_eq_empty h.not_lt @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ lt_irrefl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ lt_irrefl _ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ lt_irrefl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, h.trans hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici αᵒᵈ _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, h.trans_le hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans_lt hx₁, hx₂.trans_le h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h le_rfl lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo le_rfl h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans hx₁, hx₂.trans_le h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h le_rfl lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico le_rfl h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h le_rfl lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc le_rfl h lemma Icc_subset_Ioo (ha : a₂ < a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ := λ x hx, ⟨ha.trans_le hx.1, hx.2.trans_lt hb⟩ lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Iic_self : Ioc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans_lt hx₁, hx₂.trans h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h le_rfl lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc le_rfl h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left h₁.trans_le lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := λ x, and.imp_right $ λ h', h'.trans_lt h lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, h₂.trans_lt h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λ x hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λ x hx, le_of_lt hx lemma Ico_subset_Ici_self : Ico a b ⊆ Ici a := λ x, and.left lemma Ioi_ssubset_Ici_self : Ioi a ⊂ Ici a := ⟨Ioi_subset_Ici_self, λ h, lt_irrefl a (h le_rfl)⟩ lemma Iio_ssubset_Iic_self : Iio a ⊂ Iic a := @Ioi_ssubset_Ici_self αᵒᵈ _ _ lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans hx, hx'.trans h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans_le hx, hx'.trans_lt h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans hx, hx'.trans_lt h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans_le hx, hx'.trans h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_rfl⟩, λ h x ⟨hx, hx'⟩, hx'.trans_lt h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_rfl, h₁⟩, λ h x ⟨hx, hx'⟩, h.trans_le hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_rfl⟩, λ h x ⟨hx, hx'⟩, hx'.trans h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_rfl, h₁⟩, λ h x ⟨hx, hx'⟩, h.trans hx⟩ lemma Icc_ssubset_Icc_left (hI : a₂ ≤ b₂) (ha : a₂ < a₁) (hb : b₁ ≤ b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc (le_of_lt ha) hb)).mpr ⟨a₂, left_mem_Icc.mpr hI, not_and.mpr (λ f g, lt_irrefl a₂ (ha.trans_le f))⟩ lemma Icc_ssubset_Icc_right (hI : a₂ ≤ b₂) (ha : a₂ ≤ a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc ha (le_of_lt hb))).mpr ⟨b₂, right_mem_Icc.mpr hI, (λ f, lt_irrefl b₁ (hb.trans_le f.2))⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λ x hx, h.trans_lt hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λ x hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl lemma Iic_inter_Ici : Iic a ∩ Ici b = Icc b a := inter_comm _ _ lemma Iio_inter_Ici : Iio a ∩ Ici b = Ico b a := inter_comm _ _ lemma Iic_inter_Ioi : Iic a ∩ Ioi b = Ioc b a := inter_comm _ _ lemma Iio_inter_Ioi : Iio a ∩ Ioi b = Ioo b a := inter_comm _ _ lemma mem_Icc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Icc a b := Ioo_subset_Icc_self h lemma mem_Ico_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ico a b := Ioo_subset_Ico_self h lemma mem_Ioc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ioc a b := Ioo_subset_Ioc_self h lemma mem_Icc_of_Ico (h : x ∈ Ico a b) : x ∈ Icc a b := Ico_subset_Icc_self h lemma mem_Icc_of_Ioc (h : x ∈ Ioc a b) : x ∈ Icc a b := Ioc_subset_Icc_self h lemma mem_Ici_of_Ioi (h : x ∈ Ioi a) : x ∈ Ici a := Ioi_subset_Ici_self h lemma mem_Iic_of_Iio (h : x ∈ Iio a) : x ∈ Iic a := Iio_subset_Iic_self h lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ ¬a ≤ b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Icc] lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ico] lemma Ioc_eq_empty_iff : Ioc a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ioc] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ioo] lemma _root_.is_top.Iic_eq (h : is_top a) : Iic a = univ := eq_univ_of_forall h lemma _root_.is_bot.Ici_eq (h : is_bot a) : Ici a = univ := eq_univ_of_forall h lemma _root_.is_max.Ioi_eq (h : is_max a) : Ioi a = ∅ := eq_empty_of_subset_empty $ λ b, h.not_lt lemma _root_.is_min.Iio_eq (h : is_min a) : Iio a = ∅ := eq_empty_of_subset_empty $ λ b, h.not_lt lemma Iic_inter_Ioc_of_le (h : a ≤ c) : Iic a ∩ Ioc b c = Ioc b a := ext $ λ x, ⟨λ H, ⟨H.2.1, H.1⟩, λ H, ⟨H.2, H.1, H.2.trans h⟩⟩ lemma not_mem_Icc_of_lt (ha : c < a) : c ∉ Icc a b := λ h, ha.not_le h.1 lemma not_mem_Icc_of_gt (hb : b < c) : c ∉ Icc a b := λ h, hb.not_le h.2 lemma not_mem_Ico_of_lt (ha : c < a) : c ∉ Ico a b := λ h, ha.not_le h.1 lemma not_mem_Ioc_of_gt (hb : b < c) : c ∉ Ioc a b := λ h, hb.not_le h.2 @[simp] lemma not_mem_Ioi_self : a ∉ Ioi a := lt_irrefl _ @[simp] lemma not_mem_Iio_self : b ∉ Iio b := lt_irrefl _ lemma not_mem_Ioc_of_le (ha : c ≤ a) : c ∉ Ioc a b := λ h, lt_irrefl _ $ h.1.trans_le ha lemma not_mem_Ico_of_ge (hb : b ≤ c) : c ∉ Ico a b := λ h, lt_irrefl _ $ h.2.trans_le hb lemma not_mem_Ioo_of_le (ha : c ≤ a) : c ∉ Ioo a b := λ h, lt_irrefl _ $ h.1.trans_le ha lemma not_mem_Ioo_of_ge (hb : b ≤ c) : c ∉ Ioo a b := λ h, lt_irrefl _ $ h.2.trans_le hb end preorder section partial_order variables [partial_order α] {a b c : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] @[simp] lemma Icc_eq_singleton_iff : Icc a b = {c} ↔ a = c ∧ b = c := begin refine ⟨λ h, _, _⟩, { have hab : a ≤ b := nonempty_Icc.1 (h.symm.subst $ singleton_nonempty c), exact ⟨eq_of_mem_singleton $ h.subst $ left_mem_Icc.2 hab, eq_of_mem_singleton $ h.subst $ right_mem_Icc.2 hab⟩ }, { rintro ⟨rfl, rfl⟩, exact Icc_self _ } end @[simp] lemma Icc_diff_left : Icc a b \ {a} = Ioc a b := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm] @[simp] lemma Icc_diff_right : Icc a b \ {b} = Ico a b := ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc] @[simp] lemma Ico_diff_left : Ico a b \ {a} = Ioo a b := ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm] @[simp] lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b := ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne] @[simp] lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b := by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right] @[simp] lemma Ici_diff_left : Ici a \ {a} = Ioi a := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm] @[simp] lemma Iic_diff_right : Iic a \ {a} = Iio a := ext $ λ x, by simp [lt_iff_le_and_ne] @[simp] lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} := by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)] @[simp] lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} := by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)] @[simp] lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} := by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] } @[simp] lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} := by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)] @[simp] lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} := by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)] @[simp] lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt] @[simp] lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm lemma Ioo_union_left (hab : a < b) : Ioo a b ∪ {a} = Ico a b := by rw [← Ico_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Ico.2 hab)] lemma Ioo_union_right (hab : a < b) : Ioo a b ∪ {b} = Ioc a b := by simpa only [dual_Ioo, dual_Ico] using Ioo_union_left hab.dual lemma Ioc_union_left (hab : a ≤ b) : Ioc a b ∪ {a} = Icc a b := by rw [← Icc_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Icc.2 hab)] lemma Ico_union_right (hab : a ≤ b) : Ico a b ∪ {b} = Icc a b := by simpa only [dual_Ioc, dual_Icc] using Ioc_union_left hab.dual @[simp] lemma Ico_insert_right (h : a ≤ b) : insert b (Ico a b) = Icc a b := by rw [insert_eq, union_comm, Ico_union_right h] @[simp] lemma Ioc_insert_left (h : a ≤ b) : insert a (Ioc a b) = Icc a b := by rw [insert_eq, union_comm, Ioc_union_left h] @[simp] lemma Ioo_insert_left (h : a < b) : insert a (Ioo a b) = Ico a b := by rw [insert_eq, union_comm, Ioo_union_left h] @[simp] lemma Ioo_insert_right (h : a < b) : insert b (Ioo a b) = Ioc a b := by rw [insert_eq, union_comm, Ioo_union_right h] @[simp] lemma Iio_insert : insert a (Iio a) = Iic a := ext $ λ _, le_iff_eq_or_lt.symm @[simp] lemma Ioi_insert : insert a (Ioi a) = Ici a := ext $ λ _, (or_congr_left' eq_comm).trans le_iff_eq_or_lt.symm lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ ({Ici a, Ioi a} : set (set α)) := classical.by_cases (λ h : a ∈ s, or.inl $ subset.antisymm hc $ by rw [← Ioi_union_left, union_subset_iff]; simp *) (λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho) lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ ({Iic a, Iio a} : set (set α)) := @mem_Ici_Ioi_of_subset_of_subset αᵒᵈ _ a s ho hc lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) : s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) := begin classical, by_cases ha : a ∈ s; by_cases hb : b ∈ s, { refine or.inl (subset.antisymm hc _), rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha, ← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho }, { refine (or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_right], exact subset_diff_singleton hc hb }, { rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } }, { refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_left], exact subset_diff_singleton hc ha }, { rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } }, { refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho), rw [← Ico_diff_left, ← Icc_diff_right], apply_rules [subset_diff_singleton] } end lemma eq_left_or_mem_Ioo_of_mem_Ico {x : α} (hmem : x ∈ Ico a b) : x = a ∨ x ∈ Ioo a b := hmem.1.eq_or_gt.imp_right $ λ h, ⟨h, hmem.2⟩ lemma eq_right_or_mem_Ioo_of_mem_Ioc {x : α} (hmem : x ∈ Ioc a b) : x = b ∨ x ∈ Ioo a b := hmem.2.eq_or_lt.imp_right $ and.intro hmem.1 lemma eq_endpoints_or_mem_Ioo_of_mem_Icc {x : α} (hmem : x ∈ Icc a b) : x = a ∨ x = b ∨ x ∈ Ioo a b := hmem.1.eq_or_gt.imp_right $ λ h, eq_right_or_mem_Ioo_of_mem_Ioc ⟨h, hmem.2⟩ lemma _root_.is_max.Ici_eq (h : is_max a) : Ici a = {a} := eq_singleton_iff_unique_mem.2 ⟨left_mem_Ici, λ b, h.eq_of_ge⟩ lemma _root_.is_min.Iic_eq (h : is_min a) : Iic a = {a} := h.to_dual.Ici_eq lemma Ici_injective : injective (Ici : α → set α) := λ a b, eq_of_forall_ge_iff ∘ set.ext_iff.1 lemma Iic_injective : injective (Iic : α → set α) := λ a b, eq_of_forall_le_iff ∘ set.ext_iff.1 lemma Ici_inj : Ici a = Ici b ↔ a = b := Ici_injective.eq_iff lemma Iic_inj : Iic a = Iic b ↔ a = b := Iic_injective.eq_iff end partial_order section order_top @[simp] lemma Ici_top [partial_order α] [order_top α] : Ici (⊤ : α) = {⊤} := is_max_top.Ici_eq variables [preorder α] [order_top α] {a : α} @[simp] lemma Ioi_top : Ioi (⊤ : α) = ∅ := is_max_top.Ioi_eq @[simp] lemma Iic_top : Iic (⊤ : α) = univ := is_top_top.Iic_eq @[simp] lemma Icc_top : Icc a ⊤ = Ici a := by simp [← Ici_inter_Iic] @[simp] lemma Ioc_top : Ioc a ⊤ = Ioi a := by simp [← Ioi_inter_Iic] end order_top section order_bot @[simp] lemma Iic_bot [partial_order α] [order_bot α] : Iic (⊥ : α) = {⊥} := is_min_bot.Iic_eq variables [preorder α] [order_bot α] {a : α} @[simp] lemma Iio_bot : Iio (⊥ : α) = ∅ := is_min_bot.Iio_eq @[simp] lemma Ici_bot : Ici (⊥ : α) = univ := is_bot_bot.Ici_eq @[simp] lemma Icc_bot : Icc ⊥ a = Iic a := by simp [← Ici_inter_Iic] @[simp] lemma Ico_bot : Ico ⊥ a = Iio a := by simp [← Ici_inter_Iio] end order_bot lemma Icc_bot_top [partial_order α] [bounded_order α] : Icc (⊥ : α) ⊤ = univ := by simp section linear_order variables [linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} lemma not_mem_Ici : c ∉ Ici a ↔ c < a := not_le lemma not_mem_Iic : c ∉ Iic b ↔ b < c := not_le lemma not_mem_Ioi : c ∉ Ioi a ↔ c ≤ a := not_lt lemma not_mem_Iio : c ∉ Iio b ↔ b ≤ c := not_lt @[simp] lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le @[simp] lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le @[simp] lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt @[simp] lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt @[simp] lemma Ici_diff_Ici : Ici a \ Ici b = Ico a b := by rw [diff_eq, compl_Ici, Ici_inter_Iio] @[simp] lemma Ici_diff_Ioi : Ici a \ Ioi b = Icc a b := by rw [diff_eq, compl_Ioi, Ici_inter_Iic] @[simp] lemma Ioi_diff_Ioi : Ioi a \ Ioi b = Ioc a b := by rw [diff_eq, compl_Ioi, Ioi_inter_Iic] @[simp] lemma Ioi_diff_Ici : Ioi a \ Ici b = Ioo a b := by rw [diff_eq, compl_Ici, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iic : Iic b \ Iic a = Ioc a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iic] @[simp] lemma Iio_diff_Iic : Iio b \ Iic a = Ioo a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iio : Iic b \ Iio a = Icc a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iic] @[simp] lemma Iio_diff_Iio : Iio b \ Iio a = Ico a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iio] lemma Ioi_injective : injective (Ioi : α → set α) := λ a b, eq_of_forall_gt_iff ∘ set.ext_iff.1 lemma Iio_injective : injective (Iio : α → set α) := λ a b, eq_of_forall_lt_iff ∘ set.ext_iff.1 lemma Ioi_inj : Ioi a = Ioi b ↔ a = b := Ioi_injective.eq_iff lemma Iio_inj : Iio a = Iio b ↔ a = b := Iio_injective.eq_iff lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_rfl, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨this.2.le, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioc_subset_Ioc_iff (h₁ : a₁ < b₁) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ b₁ ≤ b₂ ∧ a₂ ≤ a₁ := by { convert @Ico_subset_Ico_iff αᵒᵈ _ b₁ b₂ a₁ a₂ h₁; exact (@dual_Ico α _ _ _).symm } lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases exists_between h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := (h ⟨xa, xb⟩).1.trans xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := xa.trans (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff $ h₁.trans_lt $ h.trans_le h₂).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := exists_between (not_le.mp ba), exact lt_irrefl _ (ca.trans_le (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := by rw [←diff_eq_empty, Iio_diff_Iic, Ioo_eq_empty_iff, not_lt] /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ lemma Iic_union_Ioi_of_le (h : a ≤ b) : Iic b ∪ Ioi a = univ := eq_univ_of_forall $ λ x, (h.lt_or_le x).symm lemma Iio_union_Ici_of_le (h : a ≤ b) : Iio b ∪ Ici a = univ := eq_univ_of_forall $ λ x, (h.le_or_lt x).symm lemma Iic_union_Ici_of_le (h : a ≤ b) : Iic b ∪ Ici a = univ := eq_univ_of_forall $ λ x, (h.le_or_le x).symm lemma Iio_union_Ioi_of_lt (h : a < b) : Iio b ∪ Ioi a = univ := eq_univ_of_forall $ λ x, (h.lt_or_lt x).symm @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := Iic_union_Ici_of_le le_rfl @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := Iio_union_Ici_of_le le_rfl @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := Iic_union_Ioi_of_le le_rfl @[simp] lemma Iio_union_Ioi : Iio a ∪ Ioi a = {a}ᶜ := ext $ λ x, lt_or_lt_iff_ne /-! #### A finite and an infinite interval -/ lemma Ioo_union_Ioi' (h₁ : c < b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioo, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto }, { have hxb : x < b := (le_of_not_gt hc).trans_lt h₁, tauto }, end lemma Ioo_union_Ioi (h : c < max a b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioo_union_Ioi' h }, { rw min_comm, simp [*, min_eq_left_of_lt] }, end lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_le) Ioi_subset_Ioo_union_Ici lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left h.trans) Ici_subset_Ico_union_Ici lemma Ico_union_Ici' (h₁ : c ≤ b) : Ico a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ico, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, end lemma Ico_union_Ici (h : c ≤ max a b) : Ico a b ∪ Ici c = Ici (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ico_union_Ici' h }, { simp [*] }, end lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_lt) Ioi_subset_Ioc_union_Ioi lemma Ioc_union_Ioi' (h₁ : c ≤ b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioc, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁, tauto }, end lemma Ioc_union_Ioi (h : c ≤ max a b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioc_union_Ioi' h }, { simp [*] }, end lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := subset.antisymm (λ x hx, hx.elim and.left $ λ hx', h.trans $ le_of_lt hx') Ici_subset_Icc_union_Ioi lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b := subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self) @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_le) Ioi_subset_Ioc_union_Ici lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b := subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self) @[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left h.trans) Ici_subset_Icc_union_Ici lemma Icc_union_Ici' (h₁ : c ≤ b) : Icc a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Icc, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, end lemma Icc_union_Ici (h : c ≤ max a b) : Icc a b ∪ Ici c = Ici (min a c) := begin cases le_or_lt a b with hab hab; simp [hab] at h, { exact Icc_union_Ici' h }, { cases h, { simp [*] }, { have hca : c ≤ a := h.trans hab.le, simp [*] } }, end /-! #### An infinite and a finite interval -/ lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, (le_of_lt hx).trans h) and.right) Iic_subset_Iio_union_Icc lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_lt_of_le hx' h) and.right) Iio_subset_Iio_union_Ico lemma Iio_union_Ico' (h₁ : c ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iio, mem_Ico, lt_max_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, end lemma Iio_union_Ico (h : min c d ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ico' h }, { simp [*] }, end lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx', le_trans hx' h) and.right) Iic_subset_Iic_union_Ioc lemma Iic_union_Ioc' (h₁ : c < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Ioc, le_max_iff], by_cases hc : c < x, { tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁.le, tauto }, end lemma Iic_union_Ioc (h : min c d < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Ioc' h }, { rw max_comm, simp [*, max_eq_right_of_lt h] }, end lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_le_of_lt hx' h) and.right) Iio_subset_Iic_union_Ioo lemma Iio_union_Ioo' (h₁ : c < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin ext x, cases lt_or_le x b with hba hba, { simp [hba, h₁] }, { simp only [mem_Iio, mem_union, mem_Ioo, lt_max_iff], refine or_congr iff.rfl ⟨and.right, _⟩, exact λ h₂, ⟨h₁.trans_le hba, h₂⟩ }, end lemma Iio_union_Ioo (h : min c d < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ioo' h }, { rw max_comm, simp [*, max_eq_right_of_lt h] }, end lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b := subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx', le_trans hx' h) and.right) Iic_subset_Iic_union_Icc lemma Iic_union_Icc' (h₁ : c ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Icc, le_max_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, end lemma Iic_union_Icc (h : min c d ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin cases le_or_lt c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Icc' h }, { cases h, { have hdb : d ≤ b := hcd.le.trans h, simp [*] }, { simp [*] } }, end lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b := subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_le_of_lt hx' h) and.right) Iio_subset_Iic_union_Ico /-! #### Two finite intervals, `I?o` and `Ic?` -/ lemma Ioo_subset_Ioo_union_Ico : Ioo a c ⊆ Ioo a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_le h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioo_subset_Ioo_union_Ico lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_le h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Ico_subset_Ico_union_Ico lemma Ico_union_Ico' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ico, min_le_iff, lt_max_iff], by_cases hc : c ≤ x; by_cases hd : x < d, { tauto }, { have hax : a ≤ x := h₂.trans (le_of_not_gt hd), tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, { tauto }, end lemma Ico_union_Ico (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ico_union_Ico' h₂ h₁ }, all_goals { simp [*] }, end lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.le.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Icc_subset_Ico_union_Icc lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.le.trans h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioc_subset_Ioo_union_Icc /-! #### Two finite intervals, `I?c` and `Io?` -/ lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans_lt hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ioo lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans hx.1.le, hx.2⟩)) Ico_subset_Icc_union_Ioo lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1.le, hx.2⟩)) Icc_subset_Icc_union_Ioc lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans_lt hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Ioc lemma Ioc_union_Ioc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioc, min_lt_iff, le_max_iff], by_cases hc : c < x; by_cases hd : x ≤ d, { tauto }, { have hax : a < x := h₂.trans_lt (lt_of_not_ge hd), tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁, tauto }, { tauto }, end lemma Ioc_union_Ioc (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ioc_union_Ioc' h₂ h₁ }, all_goals { simp [*] }, end /-! #### Two finite intervals with a common point -/ lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c := subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx', ⟨hx'.1, hx'.2.trans_lt h₂⟩) (λ hx', ⟨h₁.trans_le hx'.1, hx'.2⟩)) Ioo_subset_Ioc_union_Ico lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c := subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Ico_subset_Icc_union_Ico lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c := subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Icc_subset_Icc_union_Icc lemma Icc_union_Icc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Icc, min_le_iff, le_max_iff], by_cases hc : c ≤ x; by_cases hd : x ≤ d, { tauto }, { have hax : a ≤ x := h₂.trans (le_of_not_ge hd), tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, { tauto } end /-- We cannot replace `<` by `≤` in the hypotheses. Otherwise for `b < a = d < c` the l.h.s. is `∅` and the r.h.s. is `{a}`. -/ lemma Icc_union_Icc (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin cases le_or_lt a b with hab hab; cases le_or_lt c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, hab, hcd] at h₁ h₂, { exact Icc_union_Icc' h₂.le h₁.le }, all_goals { simp [*, min_eq_left_of_lt, max_eq_left_of_lt, min_eq_right_of_lt, max_eq_right_of_lt] }, end lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c := subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Icc lemma Ioo_union_Ioo' (h₁ : c < b) (h₂ : a < d) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioo, min_lt_iff, lt_max_iff], by_cases hc : c < x; by_cases hd : x < d, { tauto }, { have hax : a < x := h₂.trans_le (le_of_not_lt hd), tauto }, { have hxb : x < b := (le_of_not_lt hc).trans_lt h₁, tauto }, { tauto } end lemma Ioo_union_Ioo (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, hab, hcd] at h₁ h₂, { exact Ioo_union_Ioo' h₂ h₁ }, all_goals { simp [*, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, le_of_lt h₂, le_of_lt h₁] }, end section lattice variables [lattice β] {f : α → β} lemma _root_.monotone_on.image_Icc_subset (hf : monotone_on f (Icc a b)) : f '' Icc a b ⊆ Icc (f a) (f b) := image_subset_iff.2 $ λ c hc, ⟨hf (left_mem_Icc.2 $ hc.1.trans hc.2) hc hc.1, hf hc (right_mem_Icc.2 $ hc.1.trans hc.2) hc.2⟩ lemma _root_.antitone_on.image_Icc_subset (hf : antitone_on f (Icc a b)) : f '' Icc a b ⊆ Icc (f b) (f a) := image_subset_iff.2 $ λ c hc, ⟨hf hc (right_mem_Icc.2 $ hc.1.trans hc.2) hc.2, hf (left_mem_Icc.2 $ hc.1.trans hc.2) hc hc.1⟩ lemma _root_.monotone.image_Icc_subset (hf : monotone f) : f '' Icc a b ⊆ Icc (f a) (f b) := (hf.monotone_on _).image_Icc_subset lemma _root_.antitone.image_Icc_subset (hf : antitone f) : f '' Icc a b ⊆ Icc (f b) (f a) := (hf.antitone_on _).image_Icc_subset end lattice end linear_order section lattice section inf variables [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Ioc_inter_Iic (a b c : α) : Ioc a b ∩ Iic c = Ioc a (b ⊓ c) := by rw [← Ioi_inter_Iic, ← Ioi_inter_Iic, inter_assoc, Iic_inter_Iic] end inf section sup variables [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ico_inter_Ici (a b c : α) : Ico a b ∩ Ici c = Ico (a ⊔ c) b := by rw [← Ici_inter_Iio, ← Ici_inter_Iio, ← Ici_inter_Ici, inter_right_comm] end sup section both variables [lattice α] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] end both end lattice section linear_order variables [linear_order α] [linear_order β] {f : α → β} {a a₁ a₂ b b₁ b₂ c d : α} @[simp] lemma Ioi_inter_Ioi : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := ext $ λ _, sup_lt_iff.symm @[simp] lemma Iio_inter_Iio : Iio a ∩ Iio b = Iio (a ⊓ b) := ext $ λ _, lt_inf_iff.symm lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioo_of_left_lt (h : b₁ < b₂) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioc (max a₁ a₂) b₁ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_left_iff_imp.2 (λ h', lt_of_le_of_lt h' h)] lemma Ioc_inter_Ioo_of_right_le (h : b₂ ≤ b₁) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (max a₁ a₂) b₂ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_right_iff_imp.2 (λ h', ((le_of_lt h').trans h))] lemma Ioo_inter_Ioc_of_left_le (h : b₁ ≤ b₂) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioo (max a₁ a₂) b₁ := by rw [inter_comm, Ioc_inter_Ioo_of_right_le h, max_comm] lemma Ioo_inter_Ioc_of_right_lt (h : b₂ < b₁) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (max a₁ a₂) b₂ := by rw [inter_comm, Ioc_inter_Ioo_of_left_lt h, max_comm] @[simp] lemma Ico_diff_Iio : Ico a b \ Iio c = Ico (max a c) b := by rw [diff_eq, compl_Iio, Ico_inter_Ici, sup_eq_max] @[simp] lemma Ioc_diff_Ioi : Ioc a b \ Ioi c = Ioc a (min b c) := ext $ by simp [iff_def] {contextual:=tt} @[simp] lemma Ioc_inter_Ioi : Ioc a b ∩ Ioi c = Ioc (a ⊔ c) b := by rw [← Ioi_inter_Iic, inter_assoc, inter_comm, inter_assoc, Ioi_inter_Ioi, inter_comm, Ioi_inter_Iic, sup_comm] @[simp] lemma Ico_inter_Iio : Ico a b ∩ Iio c = Ico a (min b c) := ext $ by simp [iff_def] {contextual:=tt} @[simp] lemma Ioc_diff_Iic : Ioc a b \ Iic c = Ioc (max a c) b := by rw [diff_eq, compl_Iic, Ioc_inter_Ioi, sup_eq_max] @[simp] lemma Ioc_union_Ioc_right : Ioc a b ∪ Ioc a c = Ioc a (max b c) := by rw [Ioc_union_Ioc, min_self]; exact (min_le_left _ _).trans (le_max_left _ _) @[simp] lemma Ioc_union_Ioc_left : Ioc a c ∪ Ioc b c = Ioc (min a b) c := by rw [Ioc_union_Ioc, max_self]; exact (min_le_right _ _).trans (le_max_right _ _) @[simp] lemma Ioc_union_Ioc_symm : Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b) := by { rw max_comm, apply Ioc_union_Ioc; rw max_comm; exact min_le_max } @[simp] lemma Ioc_union_Ioc_union_Ioc_cycle : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc (min a (min b c)) (max a (max b c)) := begin rw [Ioc_union_Ioc, Ioc_union_Ioc], ac_refl, all_goals { solve_by_elim [min_le_of_left_le, min_le_of_right_le, le_max_of_le_left, le_max_of_le_right, le_refl] { max_depth := 5 }} end end linear_order /-! ### Closed intervals in `α × β` -/ section prod variables [preorder α] [preorder β] @[simp] lemma Iic_prod_Iic (a : α) (b : β) : Iic a ×ˢ Iic b = Iic (a, b) := rfl @[simp] lemma Ici_prod_Ici (a : α) (b : β) : Ici a ×ˢ Ici b = Ici (a, b) := rfl lemma Ici_prod_eq (a : α × β) : Ici a = Ici a.1 ×ˢ Ici a.2 := rfl lemma Iic_prod_eq (a : α × β) : Iic a = Iic a.1 ×ˢ Iic a.2 := rfl @[simp] lemma Icc_prod_Icc (a₁ a₂ : α) (b₁ b₂ : β) : Icc a₁ a₂ ×ˢ Icc b₁ b₂ = Icc (a₁, b₁) (a₂, b₂) := by { ext ⟨x, y⟩, simp [and.assoc, and_comm, and.left_comm] } lemma Icc_prod_eq (a b : α × β) : Icc a b = Icc a.1 b.1 ×ˢ Icc a.2 b.2 := by simp end prod end set /-! ### Lemmas about intervals in dense orders -/ section dense variables (α) [preorder α] [densely_ordered α] {x y : α} instance : no_min_order (set.Ioo x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₁ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₁, hb₂.trans ha₂⟩, hb₂⟩ end⟩ instance : no_min_order (set.Ioc x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₁ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₁, hb₂.le.trans ha₂⟩, hb₂⟩ end⟩ instance : no_min_order (set.Ioi x) := ⟨λ ⟨a, ha⟩, begin rcases exists_between ha with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₁⟩, hb₂⟩ end⟩ instance : no_max_order (set.Ioo x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₂ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, ha₁.trans hb₁, hb₂⟩, hb₁⟩ end⟩ instance : no_max_order (set.Ico x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₂ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, ha₁.trans hb₁.le, hb₂⟩, hb₁⟩ end⟩ instance : no_max_order (set.Iio x) := ⟨λ ⟨a, ha⟩, begin rcases exists_between ha with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₂⟩, hb₁⟩ end⟩ end dense
52aa55882e877343604a5b7eed21fc886af66a65
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Tactic/Conv/Simp.lean
76cdb6fee61a0cb45d22a4ba37f9e4c2a9720bcd
[ "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
979
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Simp import Lean.Elab.Tactic.Split import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta def applySimpResult (result : Simp.Result) : TacticM Unit := do if result.proof?.isNone then changeLhs result.expr else updateLhs result.expr (← result.getProof) @[builtinTactic Lean.Parser.Tactic.Conv.simp] def evalSimp : Tactic := fun stx => withMainContext do let { ctx, dischargeWrapper, .. } ← mkSimpContext stx (eraseLocal := false) let lhs ← getLhs let result ← dischargeWrapper.with fun d? => simp lhs ctx (discharge? := d?) applySimpResult result @[builtinTactic Lean.Parser.Tactic.Conv.simpMatch] def evalSimpMatch : Tactic := fun stx => withMainContext do applySimpResult (← Split.simpMatch (← getLhs)) end Lean.Elab.Tactic.Conv
90b269451fce91c558f38047b395cf9403b01d91
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/util/Two.lean
e07d2a036a4816c63cef63418548ba2d54784635
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
555
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import tidy.at_least_one import tidy.tidy_attributes open tactic inductive Two : Type | _0 : Two | _1 : Two -- TODO ideally this wouldn't require a whole separate tactic, just an attribute on Two @[tidy] meta def induction_Two : tactic unit := do l ← local_context, at_least_one (l.reverse.map (λ h, do t ← infer_type h, match t with | `(Two) := induction h >> skip | _ := failed end))
dc0a391b96fd81c432c3d5bf9ddc6a07ba999908
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/intervals/group.lean
218d2dcc821febb5008482ed5fc0c7cf00375ed5
[ "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
8,073
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, Patrick Massot, Yury Kudryashov, Rémy Degenne -/ import data.set.intervals.basic import data.set.pairwise.basic import algebra.order.group.abs import algebra.group_power.lemmas /-! ### Lemmas about arithmetic operations and intervals. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} namespace set section ordered_comm_group variables [ordered_comm_group α] {a b c d : α} /-! `inv_mem_Ixx_iff`, `sub_mem_Ixx_iff` -/ @[to_additive] lemma inv_mem_Icc_iff : a⁻¹ ∈ set.Icc c d ↔ a ∈ set.Icc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_le' le_inv' @[to_additive] lemma inv_mem_Ico_iff : a⁻¹ ∈ set.Ico c d ↔ a ∈ set.Ioc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_lt' le_inv' @[to_additive] lemma inv_mem_Ioc_iff : a⁻¹ ∈ set.Ioc c d ↔ a ∈ set.Ico (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_le' lt_inv' @[to_additive] lemma inv_mem_Ioo_iff : a⁻¹ ∈ set.Ioo c d ↔ a ∈ set.Ioo (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_lt' lt_inv' end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group α] {a b c d : α} /-! `add_mem_Ixx_iff_left` -/ lemma add_mem_Icc_iff_left : a + b ∈ set.Icc c d ↔ a ∈ set.Icc (c - b) (d - b) := (and_congr sub_le_iff_le_add le_sub_iff_add_le).symm lemma add_mem_Ico_iff_left : a + b ∈ set.Ico c d ↔ a ∈ set.Ico (c - b) (d - b) := (and_congr sub_le_iff_le_add lt_sub_iff_add_lt).symm lemma add_mem_Ioc_iff_left : a + b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c - b) (d - b) := (and_congr sub_lt_iff_lt_add le_sub_iff_add_le).symm lemma add_mem_Ioo_iff_left : a + b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c - b) (d - b) := (and_congr sub_lt_iff_lt_add lt_sub_iff_add_lt).symm /-! `add_mem_Ixx_iff_right` -/ lemma add_mem_Icc_iff_right : a + b ∈ set.Icc c d ↔ b ∈ set.Icc (c - a) (d - a) := (and_congr sub_le_iff_le_add' le_sub_iff_add_le').symm lemma add_mem_Ico_iff_right : a + b ∈ set.Ico c d ↔ b ∈ set.Ico (c - a) (d - a) := (and_congr sub_le_iff_le_add' lt_sub_iff_add_lt').symm lemma add_mem_Ioc_iff_right : a + b ∈ set.Ioc c d ↔ b ∈ set.Ioc (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' le_sub_iff_add_le').symm lemma add_mem_Ioo_iff_right : a + b ∈ set.Ioo c d ↔ b ∈ set.Ioo (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' lt_sub_iff_add_lt').symm /-! `sub_mem_Ixx_iff_left` -/ lemma sub_mem_Icc_iff_left : a - b ∈ set.Icc c d ↔ a ∈ set.Icc (c + b) (d + b) := and_congr le_sub_iff_add_le sub_le_iff_le_add lemma sub_mem_Ico_iff_left : a - b ∈ set.Ico c d ↔ a ∈ set.Ico (c + b) (d + b) := and_congr le_sub_iff_add_le sub_lt_iff_lt_add lemma sub_mem_Ioc_iff_left : a - b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c + b) (d + b) := and_congr lt_sub_iff_add_lt sub_le_iff_le_add lemma sub_mem_Ioo_iff_left : a - b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c + b) (d + b) := and_congr lt_sub_iff_add_lt sub_lt_iff_lt_add /-! `sub_mem_Ixx_iff_right` -/ lemma sub_mem_Icc_iff_right : a - b ∈ set.Icc c d ↔ b ∈ set.Icc (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_le_comm le_sub_comm lemma sub_mem_Ico_iff_right : a - b ∈ set.Ico c d ↔ b ∈ set.Ioc (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_lt_comm le_sub_comm lemma sub_mem_Ioc_iff_right : a - b ∈ set.Ioc c d ↔ b ∈ set.Ico (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_le_comm lt_sub_comm lemma sub_mem_Ioo_iff_right : a - b ∈ set.Ioo c d ↔ b ∈ set.Ioo (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_lt_comm lt_sub_comm -- I think that symmetric intervals deserve attention and API: they arise all the time, -- for instance when considering metric balls in `ℝ`. lemma mem_Icc_iff_abs_le {R : Type*} [linear_ordered_add_comm_group R] {x y z : R} : |x - y| ≤ z ↔ y ∈ Icc (x - z) (x + z) := abs_le.trans $ (and_comm _ _).trans $ and_congr sub_le_comm neg_le_sub_iff_le_add end ordered_add_comm_group section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp [*, not_le.2 h'] }, { use max x (x + dy), simp [*, le_refl] } end end linear_ordered_add_comm_group /-! ### Lemmas about disjointness of translates of intervals -/ section pairwise_disjoint section ordered_comm_group variables [ordered_comm_group α] (a b : α) @[to_additive] lemma pairwise_disjoint_Ioc_mul_zpow : pairwise (disjoint on λ n : ℤ, Ioc (a * b ^ n) (a * b ^ (n + 1))) := begin simp_rw [function.on_fun, set.disjoint_iff], intros m n hmn x hx, apply hmn, have hb : 1 < b, { have : a * b ^ m < a * b ^ (m + 1), from hx.1.1.trans_le hx.1.2, rwa [mul_lt_mul_iff_left, ←mul_one (b ^ m), zpow_add_one, mul_lt_mul_iff_left] at this }, have i1 := hx.1.1.trans_le hx.2.2, have i2 := hx.2.1.trans_le hx.1.2, rw [mul_lt_mul_iff_left, zpow_lt_zpow_iff hb, int.lt_add_one_iff] at i1 i2, exact le_antisymm i1 i2 end @[to_additive] lemma pairwise_disjoint_Ico_mul_zpow : pairwise (disjoint on λ n : ℤ, Ico (a * b ^ n) (a * b ^ (n + 1))) := begin simp_rw [function.on_fun, set.disjoint_iff], intros m n hmn x hx, apply hmn, have hb : 1 < b, { have : a * b ^ m < a * b ^ (m + 1), from hx.1.1.trans_lt hx.1.2, rwa [mul_lt_mul_iff_left, ←mul_one (b ^ m), zpow_add_one, mul_lt_mul_iff_left] at this }, have i1 := hx.1.1.trans_lt hx.2.2, have i2 := hx.2.1.trans_lt hx.1.2, rw [mul_lt_mul_iff_left, zpow_lt_zpow_iff hb, int.lt_add_one_iff] at i1 i2, exact le_antisymm i1 i2, end @[to_additive] lemma pairwise_disjoint_Ioo_mul_zpow : pairwise (disjoint on λ n : ℤ, Ioo (a * b ^ n) (a * b ^ (n + 1))) := λ m n hmn, (pairwise_disjoint_Ioc_mul_zpow a b hmn).mono Ioo_subset_Ioc_self Ioo_subset_Ioc_self @[to_additive] lemma pairwise_disjoint_Ioc_zpow : pairwise (disjoint on λ n : ℤ, Ioc (b ^ n) (b ^ (n + 1))) := by simpa only [one_mul] using pairwise_disjoint_Ioc_mul_zpow 1 b @[to_additive] lemma pairwise_disjoint_Ico_zpow : pairwise (disjoint on λ n : ℤ, Ico (b ^ n) (b ^ (n + 1))) := by simpa only [one_mul] using pairwise_disjoint_Ico_mul_zpow 1 b @[to_additive] lemma pairwise_disjoint_Ioo_zpow : pairwise (disjoint on λ n : ℤ, Ioo (b ^ n) (b ^ (n + 1))) := by simpa only [one_mul] using pairwise_disjoint_Ioo_mul_zpow 1 b end ordered_comm_group section ordered_ring variables [ordered_ring α] (a : α) lemma pairwise_disjoint_Ioc_add_int_cast : pairwise (disjoint on λ n : ℤ, Ioc (a + n) (a + n + 1)) := by simpa only [zsmul_one, int.cast_add, int.cast_one, ←add_assoc] using pairwise_disjoint_Ioc_add_zsmul a (1 : α) lemma pairwise_disjoint_Ico_add_int_cast : pairwise (disjoint on λ n : ℤ, Ico (a + n) (a + n + 1)) := by simpa only [zsmul_one, int.cast_add, int.cast_one, ←add_assoc] using pairwise_disjoint_Ico_add_zsmul a (1 : α) lemma pairwise_disjoint_Ioo_add_int_cast : pairwise (disjoint on λ n : ℤ, Ioo (a + n) (a + n + 1)) := by simpa only [zsmul_one, int.cast_add, int.cast_one, ←add_assoc] using pairwise_disjoint_Ioo_add_zsmul a (1 : α) variables (α) lemma pairwise_disjoint_Ico_int_cast : pairwise (disjoint on λ n : ℤ, Ico (n : α) (n + 1)) := by simpa only [zero_add] using pairwise_disjoint_Ico_add_int_cast (0 : α) lemma pairwise_disjoint_Ioo_int_cast : pairwise (disjoint on λ n : ℤ, Ioo (n : α) (n + 1)) := by simpa only [zero_add] using pairwise_disjoint_Ioo_add_int_cast (0 : α) lemma pairwise_disjoint_Ioc_int_cast : pairwise (disjoint on λ n : ℤ, Ioc (n : α) (n + 1)) := by simpa only [zero_add] using pairwise_disjoint_Ioc_add_int_cast (0 : α) end ordered_ring end pairwise_disjoint end set
88efde241755a19673c88dcc7e4b693537482579
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/sheaves/sheaf_condition/sites.lean
7a6670ad156743b7668004761a6be1d62af2f007
[ "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,342
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer -/ import category_theory.sites.spaces import topology.sheaves.sheaf import category_theory.sites.dense_subsite /-! # The sheaf condition in terms of sites. The theory of sheaves on sites is developed independently from sheaves on spaces in `category_theory/sites`. In this file, we connect the two theories: We show that for a topological space `X`, a presheaf `F : (opens X)ᵒᵖ ⥤ C` is a sheaf on the site `opens X` if and only if it is a sheaf on `X` in the usual sense. Recall that a presheaf `F : (opens X)ᵒᵖ ⥤ C` is called a *sheaf* on the space `X`, if for every family of opens `U : ι → opens X`, the object `F.obj (op (supr U))` is the limit of some fork diagram. On the other hand, `F` is called a *sheaf* on the site `opens X`, if for every open set `U : opens X` and every presieve `R : presieve U`, the object `F.obj (op U)` is the limit of a very similar fork diagram. In this file, we will construct the two functions `covering_of_presieve` and `presieve_of_covering`, which translate between the two concepts. We then prove a bunch of naturality lemmas relating the two fork diagrams to each other. ## Main statements * `is_sheaf_sites_iff_is_sheaf_spaces`. A presheaf `F : (opens X)ᵒᵖ ⥤ C` is a sheaf on the site `opens X` if and only if it is a sheaf on the space `X`. * `Sheaf_sites_eq_sheaf_spaces`. The type of sheaves on the site `opens X` is *equal* to the type of sheaves on the space `X`. -/ noncomputable theory universes u v w namespace Top.presheaf open category_theory topological_space Top category_theory.limits opposite open Top.presheaf.sheaf_condition_equalizer_products variables {C : Type u} [category.{v} C] [has_products C] variables {X : Top.{v}} (F : presheaf C X) /-- Given a presieve `R` on `U`, we obtain a covering family of open sets in `X`, by taking as index type the type of dependent pairs `(V, f)`, where `f : V ⟶ U` is in `R`. -/ def covering_of_presieve (U : opens X) (R : presieve U) : (Σ V, {f : V ⟶ U // R f}) → opens X := λ f, f.1 @[simp] lemma covering_of_presieve_apply (U : opens X) (R : presieve U) (f : Σ V, {f : V ⟶ U // R f}) : covering_of_presieve U R f = f.1 := rfl namespace covering_of_presieve variables (U : opens X) (R : presieve U) /-! In this section, we will relate two different fork diagrams to each other. The first one is the defining fork diagram for the sheaf condition in terms of sites, applied to the presieve `R`. It will henceforth be called the _sites diagram_. Its objects are called `presheaf.first_obj` and `presheaf.second_obj` and its morphisms are `presheaf.first_map` and `presheaf.second_obj`. The fork map into this diagram is called `presheaf.fork_map`. The second one is the defining fork diagram for the sheaf condition in terms of spaces, applied to the family of opens `covering_of_presieve U R`. It will henceforth be called the _spaces diagram_. Its objects are called `pi_opens` and `pi_inters` and its morphisms are `left_res` and `right_res`. The fork map into this diagram is called `res`. -/ /-- If `R` is a presieve in the grothendieck topology on `opens X`, the covering family associated to `R` really is _covering_, i.e. the union of all open sets equals `U`. -/ lemma supr_eq_of_mem_grothendieck (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : supr (covering_of_presieve U R) = U := begin apply le_antisymm, { refine supr_le _, intro f, exact f.2.1.le, }, intros x hxU, rw [opens.mem_coe, opens.mem_supr], obtain ⟨V, iVU, ⟨W, iVW, iWU, hiWU, -⟩, hxV⟩ := hR x hxU, exact ⟨⟨W, ⟨iWU, hiWU⟩⟩, iVW.le hxV⟩, end /-- The first object in the sites diagram is isomorphic to the first object in the spaces diagram. Actually, they are even definitionally equal, but it is convenient to give this isomorphism a name. -/ def first_obj_iso_pi_opens : presheaf.first_obj R F ≅ pi_opens F (covering_of_presieve U R) := eq_to_iso rfl /-- The isomorphism `first_obj_iso_pi_opens` is compatible with canonical projections out of the product. -/ lemma first_obj_iso_pi_opens_π (f : Σ V, {f : V ⟶ U // R f}) : (first_obj_iso_pi_opens F U R).hom ≫ pi.π _ f = pi.π _ f := category.id_comp _ /-- The second object in the sites diagram is isomorphic to the second object in the spaces diagram. -/ def second_obj_iso_pi_inters : presheaf.second_obj R F ≅ pi_inters F (covering_of_presieve U R) := has_limit.iso_of_nat_iso $ discrete.nat_iso $ λ i, F.map_iso (eq_to_iso (complete_lattice.pullback_eq_inf _ _).symm).op /-- The isomorphism `second_obj_iso_pi_inters` is compatible with canonical projections out of the product. Here, we have to insert an `eq_to_hom` arrow to pass from `F.obj (op (pullback f.2.1 g.2.1))` to `F.obj (op (f.1 ⊓ g.1))`. -/ lemma second_obj_iso_pi_inters_π (f g : Σ V, {f : V ⟶ U // R f}) : (second_obj_iso_pi_inters F U R).hom ≫ pi.π _ (f, g) = pi.π _ (f, g) ≫ F.map (eq_to_hom (complete_lattice.pullback_eq_inf f.2.1 g.2.1).symm).op := begin dunfold second_obj_iso_pi_inters, rw has_limit.iso_of_nat_iso_hom_π, refl, end /-- Composing the fork map of the sites diagram with the isomorphism `first_obj_iso_pi_opens` is the same as the fork map of the spaces diagram (modulo an `eq_to_hom` arrow). -/ lemma fork_map_comp_first_obj_iso_pi_opens_eq (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : presheaf.fork_map R F ≫ (first_obj_iso_pi_opens F U R).hom = F.map (eq_to_hom (supr_eq_of_mem_grothendieck U R hR)).op ≫ res F (covering_of_presieve U R) := begin ext f, rw [category.assoc, category.assoc], rw first_obj_iso_pi_opens_π, dunfold presheaf.fork_map res, rw [limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app, ← F.map_comp], congr, end /-- First naturality condition. Under the isomorphisms `first_obj_iso_pi_opens` and `second_obj_iso_pi_inters`, the map `presheaf.first_map` corresponds to `left_res`. -/ lemma first_obj_iso_comp_left_res_eq : presheaf.first_map R F ≫ (second_obj_iso_pi_inters F U R).hom = (first_obj_iso_pi_opens F U R).hom ≫ left_res F (covering_of_presieve U R) := begin ext ⟨f, g⟩, rw [category.assoc, category.assoc, second_obj_iso_pi_inters_π], dunfold left_res presheaf.first_map, rw [limit.lift_π, fan.mk_π_app, limit.lift_π_assoc, fan.mk_π_app, ← category.assoc], erw [first_obj_iso_pi_opens_π, category.assoc, ← F.map_comp], refl, end /-- Second naturality condition. Under the isomorphisms `first_obj_iso_pi_opens` and `second_obj_iso_pi_inters`, the map `presheaf.second_map` corresponds to `right_res`. -/ lemma first_obj_iso_comp_right_res_eq : presheaf.second_map R F ≫ (second_obj_iso_pi_inters F U R).hom = (first_obj_iso_pi_opens F U R).hom ≫ right_res F (covering_of_presieve U R) := begin ext ⟨f, g⟩, dunfold right_res presheaf.second_map, rw [category.assoc, category.assoc, second_obj_iso_pi_inters_π, limit.lift_π, fan.mk_π_app, limit.lift_π_assoc, fan.mk_π_app, ← category.assoc, first_obj_iso_pi_opens_π, category.assoc, ← F.map_comp], refl, end /-- The natural isomorphism between the sites diagram and the spaces diagram. -/ @[simps] def diagram_nat_iso : parallel_pair (presheaf.first_map R F) (presheaf.second_map R F) ≅ diagram F (covering_of_presieve U R) := nat_iso.of_components (λ i, walking_parallel_pair.cases_on i (first_obj_iso_pi_opens F U R) (second_obj_iso_pi_inters F U R)) $ begin intros i j f, cases i, { cases j, { cases f, simp }, { cases f, { exact first_obj_iso_comp_left_res_eq F U R, }, { exact first_obj_iso_comp_right_res_eq F U R, } } }, { cases j, { cases f, }, { cases f, simp } }, end /-- Postcomposing the given fork of the _sites_ diagram with the natural isomorphism between the diagrams gives us a fork of the _spaces_ diagram. We construct a morphism from this fork to the given fork of the _spaces_ diagram. This is shown to be an isomorphism below. -/ @[simps] def postcompose_diagram_fork_hom (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : (cones.postcompose (diagram_nat_iso F U R).hom).obj (fork.of_ι _ (presheaf.w R F)) ⟶ fork F (covering_of_presieve U R) := fork.mk_hom (F.map (eq_to_hom (supr_eq_of_mem_grothendieck U R hR)).op) (fork_map_comp_first_obj_iso_pi_opens_eq F U R hR).symm instance is_iso_postcompose_diagram_fork_hom_hom (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : is_iso (postcompose_diagram_fork_hom F U R hR).hom := begin rw postcompose_diagram_fork_hom_hom, apply eq_to_hom.is_iso, end instance is_iso_postcompose_diagram_fork_hom (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : is_iso (postcompose_diagram_fork_hom F U R hR) := cones.cone_iso_of_hom_iso _ /-- See `postcompose_diagram_fork_hom`. -/ def postcompose_diagram_fork_iso (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : (cones.postcompose (diagram_nat_iso F U R).hom).obj (fork.of_ι _ (presheaf.w R F)) ≅ fork F (covering_of_presieve U R) := as_iso (postcompose_diagram_fork_hom F U R hR) end covering_of_presieve lemma is_sheaf_sites_of_is_sheaf_spaces (Fsh : F.is_sheaf) : presheaf.is_sheaf (opens.grothendieck_topology X) F := begin rw presheaf.is_sheaf_iff_is_sheaf', intros U R hR, refine ⟨_⟩, apply (is_limit.of_cone_equiv (cones.postcompose_equivalence (covering_of_presieve.diagram_nat_iso F U R : _))).to_fun, apply (is_limit.equiv_iso_limit (covering_of_presieve.postcompose_diagram_fork_iso F U R hR)).inv_fun, exact (Fsh (covering_of_presieve U R)).some, end /-- Given a family of opens `U : ι → opens X`, we obtain a presieve on `supr U` by declaring that a morphism `f : V ⟶ supr U` is a member of the presieve if and only if there exists an index `i : ι` such that `V = U i`. -/ def presieve_of_covering {ι : Type v} (U : ι → opens X) : presieve (supr U) := λ V f, ∃ i, V = U i namespace presieve_of_covering /-! In this section, we will relate two different fork diagrams to each other. The first one is the defining fork diagram for the sheaf condition in terms of spaces, applied to the family of opens `U`. It will henceforth be called the _spaces diagram_. Its objects are called `pi_opens` and `pi_inters` and its morphisms are `left_res` and `right_res`. The fork map into this diagram is called `res`. The second one is the defining fork diagram for the sheaf condition in terms of sites, applied to the presieve `presieve_of_covering U`. It will henceforth be called the _sites diagram_. Its objects are called `presheaf.first_obj` and `presheaf.second_obj` and its morphisms are `presheaf.first_map` and `presheaf.second_obj`. The fork map into this diagram is called `presheaf.fork_map`. -/ variables {ι : Type v} (U : ι → opens X) /-- The sieve generated by `presieve_of_covering U` is a member of the grothendieck topology. -/ lemma mem_grothendieck_topology : sieve.generate (presieve_of_covering U) ∈ opens.grothendieck_topology X (supr U) := begin intros x hx, obtain ⟨i, hxi⟩ := opens.mem_supr.mp hx, exact ⟨U i, opens.le_supr U i, ⟨U i, 𝟙 _, opens.le_supr U i, ⟨i, rfl⟩, category.id_comp _⟩, hxi⟩, end /-- An index `i : ι` can be turned into a dependent pair `(V, f)`, where `V` is an open set and `f : V ⟶ supr U` is a member of `presieve_of_covering U f`. -/ def hom_of_index (i : ι) : Σ V, {f : V ⟶ supr U // presieve_of_covering U f} := ⟨U i, opens.le_supr U i, i, rfl⟩ /-- By using the axiom of choice, a dependent pair `(V, f)` where `f : V ⟶ supr U` is a member of `presieve_of_covering U f` can be turned into an index `i : ι`, such that `V = U i`. -/ def index_of_hom (f : Σ V, {f : V ⟶ supr U // presieve_of_covering U f}) : ι := f.2.2.some lemma index_of_hom_spec (f : Σ V, {f : V ⟶ supr U // presieve_of_covering U f}) : f.1 = U (index_of_hom U f) := f.2.2.some_spec /-- The canonical morphism from the first object in the sites diagram to the first object in the spaces diagram. Note that this is *not* an isomorphism, as the product `pi_opens F U` may contain duplicate factors, i.e. `U : ι → opens X` may not be injective. -/ def first_obj_to_pi_opens : presheaf.first_obj (presieve_of_covering U) F ⟶ pi_opens F U := pi.lift (λ i, pi.π _ (hom_of_index U i)) /-- The canonical morphism from the first object in the spaces diagram to the first object in the sites diagram. Note that this is *not* an isomorphism, as the product `pi_opens F U` may contain duplicate factors, i.e. `U : ι → opens X` may not be injective. -/ def pi_opens_to_first_obj : pi_opens F U ⟶ presheaf.first_obj.{v v u} (presieve_of_covering U) F := pi.lift (λ f, pi.π _ (index_of_hom U f) ≫ F.map (eq_to_hom (index_of_hom_spec U f)).op) /-- Even though `first_obj_to_pi_opens` and `pi_opens_to_first_obj` are not inverse to each other, applying them both after a fork map `s.ι` does nothing. The intuition here is that a compatible family `s : Π i : ι, F.obj (op (U i))` does not care about duplicate open sets: If `U i = U j` the compatible family coincides on the intersection `U i ⊓ U j = U i = U j`, hence `s i = s j` (module an `eq_to_hom` arrow). -/ lemma fork_ι_comp_pi_opens_to_first_obj_to_pi_opens_eq (s : limits.fork (left_res F U) (right_res F U)) : s.ι ≫ pi_opens_to_first_obj F U ≫ first_obj_to_pi_opens F U = s.ι := begin ext j, dunfold first_obj_to_pi_opens pi_opens_to_first_obj, rw [category.assoc, category.assoc, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app], -- The issue here is that `index_of_hom U (hom_of_index U j)` need not be equal to `j`. -- But `U j = U (index_of_hom U (hom_of_index U j))` and hence we obtain the following -- `eq_to_hom` arrow: have i_eq : U j ⟶ U j ⊓ U (index_of_hom U (hom_of_index U j)), { apply eq_to_hom, rw ← index_of_hom_spec U, exact inf_idem.symm, }, -- Since `s` is a fork, we know that `s.ι ≫ left_res F U = s.ι ≫ right_res F U`. -- We compose both sides of this equality with the canonical projection at the index pair -- `(j, index_of_hom U (hom_of_index U j)` and the restriction along `i_eq`. have := congr_arg (λ f, f ≫ pi.π (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) (j, index_of_hom U (hom_of_index U j)) ≫ F.map i_eq.op) s.condition, dsimp at this, rw [category.assoc, category.assoc] at this, symmetry, -- We claim that this is equality is our goal convert this using 2, { dunfold left_res, rw [limit.lift_π_assoc, fan.mk_π_app, category.assoc, ← F.map_comp], erw F.map_id, rw category.comp_id }, { dunfold right_res, rw [limit.lift_π_assoc, fan.mk_π_app, category.assoc, ← F.map_comp], congr, } end /-- The canonical morphism from the second object of the spaces diagram to the second object of the sites diagram. -/ def pi_inters_to_second_obj : pi_inters F U ⟶ presheaf.second_obj.{v v u} (presieve_of_covering U) F := pi.lift (λ f, pi.π _ (index_of_hom U f.fst, index_of_hom U f.snd) ≫ F.map (eq_to_hom (by rw [complete_lattice.pullback_eq_inf, ← index_of_hom_spec U, ← index_of_hom_spec U])).op) lemma pi_opens_to_first_obj_comp_fist_map_eq : pi_opens_to_first_obj F U ≫ presheaf.first_map (presieve_of_covering U) F = left_res F U ≫ pi_inters_to_second_obj F U := begin ext ⟨f, g⟩, dunfold pi_opens_to_first_obj presheaf.first_map left_res pi_inters_to_second_obj, rw [category.assoc, category.assoc, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app, ← category.assoc, ← category.assoc, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app, category.assoc, category.assoc, ← F.map_comp, ← F.map_comp], refl, end lemma pi_opens_to_first_obj_comp_second_map_eq : pi_opens_to_first_obj F U ≫ presheaf.second_map (presieve_of_covering U) F = right_res F U ≫ pi_inters_to_second_obj F U := begin ext ⟨f, g⟩, dunfold pi_opens_to_first_obj presheaf.second_map right_res pi_inters_to_second_obj, rw [category.assoc, category.assoc, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app, ← category.assoc, ← category.assoc, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app, category.assoc, category.assoc, ← F.map_comp, ← F.map_comp], refl, end lemma fork_map_comp_first_map_to_pi_opens_eq : presheaf.fork_map (presieve_of_covering U) F ≫ first_obj_to_pi_opens F U = res F U := begin ext i, dsimp [presheaf.fork_map, first_obj_to_pi_opens, res], rw [category.assoc, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app], refl, end lemma res_comp_pi_opens_to_first_obj_eq : res F U ≫ pi_opens_to_first_obj F U = presheaf.fork_map (presieve_of_covering U) F := begin ext f, dunfold res pi_opens_to_first_obj presheaf.fork_map, rw [category.assoc, limit.lift_π, fan.mk_π_app, limit.lift_π, fan.mk_π_app, ← category.assoc, limit.lift_π, fan.mk_π_app, ← F.map_comp], congr, end end presieve_of_covering open presieve_of_covering lemma is_sheaf_spaces_of_is_sheaf_sites (Fsh : presheaf.is_sheaf (opens.grothendieck_topology X) F) : F.is_sheaf := begin intros ι U, rw presheaf.is_sheaf_iff_is_sheaf' at Fsh, -- We know that the sites diagram for `presieve_of_covering U` is a limit fork obtain ⟨h_limit⟩ := Fsh (supr U) (presieve_of_covering U) (presieve_of_covering.mem_grothendieck_topology U), refine ⟨fork.is_limit.mk' _ _⟩, -- Here, we are given an arbitrary fork of the spaces diagram and need to show that it factors -- uniquely through our limit fork. intro s, -- Composing `s.ι` with `pi_opens_to_first_obj F U` gives a fork of the sites diagram, which -- must factor through `presheaf.fork_map`. obtain ⟨l, hl⟩ := fork.is_limit.lift' h_limit (s.ι ≫ pi_opens_to_first_obj F U) _, swap, { rw [category.assoc, category.assoc, pi_opens_to_first_obj_comp_fist_map_eq, pi_opens_to_first_obj_comp_second_map_eq, ← category.assoc, ← category.assoc, s.condition] }, -- We claim that `l` also gives a factorization of `s.ι` refine ⟨l, _, _⟩, { rw [← fork_ι_comp_pi_opens_to_first_obj_to_pi_opens_eq F U s, ← category.assoc, ← hl, category.assoc, fork.ι_of_ι, fork_map_comp_first_map_to_pi_opens_eq], refl }, { intros m hm, apply fork.is_limit.hom_ext h_limit, rw [hl, fork.ι_of_ι], simp_rw ← res_comp_pi_opens_to_first_obj_eq, erw [← category.assoc, hm], }, end lemma is_sheaf_sites_iff_is_sheaf_spaces : presheaf.is_sheaf (opens.grothendieck_topology X) F ↔ F.is_sheaf := iff.intro (is_sheaf_spaces_of_is_sheaf_sites F) (is_sheaf_sites_of_is_sheaf_spaces F) variables (C X) /-- Turn a sheaf on the site `opens X` into a sheaf on the space `X`. -/ @[simps] def Sheaf_sites_to_sheaf_spaces : Sheaf (opens.grothendieck_topology X) C ⥤ sheaf C X := { obj := λ F, ⟨F.1, is_sheaf_spaces_of_is_sheaf_sites F.1 F.2⟩, map := λ F G f, f.val } /-- Turn a sheaf on the space `X` into a sheaf on the site `opens X`. -/ @[simps] def Sheaf_spaces_to_sheaf_sites : sheaf C X ⥤ Sheaf (opens.grothendieck_topology X) C := { obj := λ F, ⟨F.1, is_sheaf_sites_of_is_sheaf_spaces F.1 F.2⟩, map := λ F G f, ⟨f⟩ } /-- The equivalence of categories between sheaves on the site `opens X` and sheaves on the space `X`. -/ @[simps] def Sheaf_spaces_equiv_sheaf_sites : Sheaf (opens.grothendieck_topology X) C ≌ sheaf C X := { functor := Sheaf_sites_to_sheaf_spaces C X, inverse := Sheaf_spaces_to_sheaf_sites C X, unit_iso := nat_iso.of_components (λ t, ⟨⟨𝟙 _⟩, ⟨𝟙 _⟩, by { ext1, simp }, by { ext1, simp }⟩) $ by { intros, ext1, dsimp, simp }, counit_iso := nat_iso.of_components (λ t, ⟨𝟙 _, 𝟙 _, by { ext, simp }, by { ext, simp }⟩) $ by { intros, ext, dsimp, simp } } /-- The two forgetful functors are isomorphic via `Sheaf_spaces_equiv_sheaf_sites`. -/ def Sheaf_spaces_equiv_sheaf_sites_functor_forget : (Sheaf_spaces_equiv_sheaf_sites C X).functor ⋙ sheaf.forget C X ≅ Sheaf_to_presheaf _ _ := nat_iso.of_components (λ F, (iso.refl F.1)) (λ F G f, by { erw [category.comp_id, category.id_comp], refl }) /-- The two forgetful functors are isomorphic via `Sheaf_spaces_equiv_sheaf_sites`. -/ def Sheaf_spaces_equiv_sheaf_sites_inverse_forget : (Sheaf_spaces_equiv_sheaf_sites C X).inverse ⋙ Sheaf_to_presheaf _ _ ≅ sheaf.forget C X := nat_iso.of_components (λ F, (iso.refl F.1)) (λ F G f, by { erw [category.comp_id, category.id_comp], refl }) end Top.presheaf namespace Top.opens open category_theory topological_space variables {X : Top} {ι : Type*} lemma cover_dense_iff_is_basis [category ι] (B : ι ⥤ opens X) : cover_dense (opens.grothendieck_topology X) B ↔ opens.is_basis (set.range B.obj) := begin rw opens.is_basis_iff_nbhd, split, intros hd U x hx, rcases hd.1 U x hx with ⟨V,f,⟨i,f₁,f₂,hc⟩,hV⟩, exact ⟨B.obj i, ⟨i,rfl⟩, f₁.le hV, f₂.le⟩, intro hb, split, intros U x hx, rcases hb hx with ⟨_,⟨i,rfl⟩,hx,hi⟩, exact ⟨B.obj i, ⟨⟨hi⟩⟩, ⟨⟨i, 𝟙 _, ⟨⟨hi⟩⟩, rfl⟩⟩, hx⟩, end lemma cover_dense_induced_functor {B : ι → opens X} (h : opens.is_basis (set.range B)) : cover_dense (opens.grothendieck_topology X) (induced_functor B) := (cover_dense_iff_is_basis _).2 h end Top.opens namespace Top.sheaf open category_theory topological_space Top opposite variables {C : Type u} [category.{v} C] [limits.has_products C] variables {X : Top.{v}} {ι : Type*} {B : ι → opens X} variables (F : presheaf C X) (F' : sheaf C X) (h : opens.is_basis (set.range B)) /-- The empty component of a sheaf is terminal -/ def is_terminal_of_empty (F : sheaf C X) : limits.is_terminal (F.val.obj (op ∅)) := ((presheaf.Sheaf_spaces_to_sheaf_sites C X).obj F).is_terminal_of_bot_cover ∅ (by tidy) /-- A variant of `is_terminal_of_empty` that is easier to `apply`. -/ def is_terminal_of_eq_empty (F : X.sheaf C) {U : opens X} (h : U = ∅) : limits.is_terminal (F.val.obj (op U)) := by convert F.is_terminal_of_empty /-- If a family `B` of open sets forms a basis of the topology on `X`, and if `F'` is a sheaf on `X`, then a homomorphism between a presheaf `F` on `X` and `F'` is equivalent to a homomorphism between their restrictions to the indexing type `ι` of `B`, with the induced category structure on `ι`. -/ def restrict_hom_equiv_hom : ((induced_functor B).op ⋙ F ⟶ (induced_functor B).op ⋙ F'.1) ≃ (F ⟶ F'.1) := @cover_dense.restrict_hom_equiv_hom _ _ _ _ _ _ _ _ (opens.cover_dense_induced_functor h) _ F ((presheaf.Sheaf_spaces_to_sheaf_sites C X).obj F') @[simp] lemma extend_hom_app (α : ((induced_functor B).op ⋙ F ⟶ (induced_functor B).op ⋙ F'.1)) (i : ι) : (restrict_hom_equiv_hom F F' h α).app (op (B i)) = α.app (op i) := by { nth_rewrite 1 ← (restrict_hom_equiv_hom F F' h).left_inv α, refl } include h lemma hom_ext {α β : F ⟶ F'.1} (he : ∀ i, α.app (op (B i)) = β.app (op (B i))) : α = β := by { apply (restrict_hom_equiv_hom F F' h).symm.injective, ext i, exact he i.unop } end Top.sheaf
99925861745d92a21dd84d5f4ff7303e6456c2f3
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/module/submodule/basic.lean
cff1388b1ad80c0d09f4cf7724d1b1e3d4a575d0
[ "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
16,171
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.module.linear_map import algebra.module.equiv import group_theory.group_action.sub_mul_action /-! # Submodules of a module In this file we define * `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Tags submodule, subspace, linear map -/ open function open_locale big_operators universes u'' u' u v w variables {G : Type u''} {S : Type u'} {R : Type u} {M : Type v} {ι : Type w} set_option old_structure_cmd true /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] extends add_submonoid M, sub_mul_action R M : Type v. /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid /-- Reinterpret a `submodule` as an `sub_mul_action`. -/ add_decl_doc submodule.to_sub_mul_action namespace submodule variables [semiring R] [add_comm_monoid M] [module R M] instance : set_like (submodule R M) M := { coe := submodule.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : add_submonoid_class (submodule R M) M := { zero_mem := zero_mem', add_mem := add_mem' } @[simp] theorem mem_to_add_submonoid (p : submodule R M) (x : M) : x ∈ p.to_add_submonoid ↔ x ∈ p := iff.rfl variables {p q : submodule R M} @[simp] lemma mem_mk {S : set M} {x : M} (h₁ h₂ h₃) : x ∈ (⟨S, h₁, h₂, h₃⟩ : submodule R M) ↔ x ∈ S := iff.rfl @[simp] lemma coe_set_mk (S : set M) (h₁ h₂ h₃) : ((⟨S, h₁, h₂, h₃⟩ : submodule R M) : set M) = S := rfl @[simp] lemma mk_le_mk {S S' : set M} (h₁ h₂ h₃ h₁' h₂' h₃') : (⟨S, h₁, h₂, h₃⟩ : submodule R M) ≤ (⟨S', h₁', h₂', h₃'⟩ : submodule R M) ↔ S ⊆ S' := iff.rfl @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : submodule R M) (s : set M) (hs : s = ↑p) : submodule R M := { carrier := s, zero_mem' := hs.symm ▸ p.zero_mem', add_mem' := hs.symm ▸ p.add_mem', smul_mem' := hs.symm ▸ p.smul_mem' } @[simp] lemma coe_copy (S : submodule R M) (s : set M) (hs : s = ↑S) : (S.copy s hs : set M) = s := rfl lemma copy_eq (S : submodule R M) (s : set M) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : submodule R M → add_submonoid M) := λ _ _, id lemma to_add_submonoid_le : p.to_add_submonoid ≤ q.to_add_submonoid ↔ p ≤ q := iff.rfl @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : submodule R M → add_submonoid M) := to_add_submonoid_strict_mono.monotone @[simp] theorem coe_to_add_submonoid (p : submodule R M) : (p.to_add_submonoid : set M) = p := rfl theorem to_sub_mul_action_injective : injective (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q := to_sub_mul_action_injective.eq_iff @[mono] lemma to_sub_mul_action_strict_mono : strict_mono (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ _ _, id @[mono] lemma to_sub_mul_action_mono : monotone (to_sub_mul_action : submodule R M → sub_mul_action R M) := to_sub_mul_action_strict_mono.monotone @[simp] theorem coe_to_sub_mul_action (p : submodule R M) : (p.to_sub_mul_action : set M) = p := rfl end submodule namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {module_M : module R M} variables {p q : submodule R M} variables {r : R} {x y : M} variables (p) @[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[simp] protected lemma zero_mem : (0 : M) ∈ p := zero_mem _ protected lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := add_mem h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma smul_of_tower_mem [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] (r : S) (h : x ∈ p) : r • x ∈ p := p.to_sub_mul_action.smul_of_tower_mem r h protected lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := sum_mem (λ i hi, smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' [group G] [mul_action G M] [has_scalar G R] [is_scalar_tower G R M] (g : G) : g • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff' g instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] : has_scalar S p := ⟨λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩ instance [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] : is_scalar_tower S R p := p.to_sub_mul_action.is_scalar_tower instance [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] [has_scalar Sᵐᵒᵖ R] [has_scalar Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] : is_central_scalar S p := p.to_sub_mul_action.is_central_scalar protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := (set_like.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0) @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_smul_of_tower [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] (r : S) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance module' [semiring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] : module S p := by refine {smul := (•), ..p.to_sub_mul_action.mul_action', ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } instance : module R p := p.module' instance no_zero_smul_divisors [no_zero_smul_divisors R M] : no_zero_smul_divisors R p := ⟨λ c x h, have c = 0 ∨ (x : M) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] theorem subtype_apply (x : p) : p.subtype x = x := rfl @[simp] lemma coe_subtype : ((submodule.subtype p) : p → M) = coe := rfl lemma injective_subtype : injective p.subtype := subtype.coe_injective /-- Note the `add_submonoid` version of this lemma is called `add_submonoid.coe_finset_sum`. -/ @[simp] lemma coe_sum (x : ι → p) (s : finset ι) : ↑(∑ i in s, x i) = ∑ i in s, (x i : M) := p.subtype.map_sum section restrict_scalars variables (S) [semiring S] [module S M] [module R M] [has_scalar S R] [is_scalar_tower S R M] /-- `V.restrict_scalars S` is the `S`-submodule of the `S`-module given by restriction of scalars, corresponding to `V`, an `R`-submodule of the original `R`-module. -/ def restrict_scalars (V : submodule R M) : submodule S M := { carrier := V, zero_mem' := V.zero_mem, smul_mem' := λ c m h, V.smul_of_tower_mem c h, add_mem' := λ x y hx hy, V.add_mem hx hy } @[simp] lemma coe_restrict_scalars (V : submodule R M) : (V.restrict_scalars S : set M) = V := rfl @[simp] lemma restrict_scalars_mem (V : submodule R M) (m : M) : m ∈ V.restrict_scalars S ↔ m ∈ V := iff.refl _ @[simp] lemma restrict_scalars_self (V : submodule R M) : V.restrict_scalars R = V := set_like.coe_injective rfl variables (R S M) lemma restrict_scalars_injective : function.injective (restrict_scalars S : submodule R M → submodule S M) := λ V₁ V₂ h, ext $ set.ext_iff.1 (set_like.ext'_iff.1 h : _) @[simp] lemma restrict_scalars_inj {V₁ V₂ : submodule R M} : restrict_scalars S V₁ = restrict_scalars S V₂ ↔ V₁ = V₂ := (restrict_scalars_injective S _ _).eq_iff /-- Even though `p.restrict_scalars S` has type `submodule S M`, it is still an `R`-module. -/ instance restrict_scalars.orig_module (p : submodule R M) : module R (p.restrict_scalars S) := (by apply_instance : module R p) instance (p : submodule R M) : is_scalar_tower S R (p.restrict_scalars S) := { smul_assoc := λ r s x, subtype.ext $ smul_assoc r s (x : M) } /-- `restrict_scalars S` is an embedding of the lattice of `R`-submodules into the lattice of `S`-submodules. -/ @[simps] def restrict_scalars_embedding : submodule R M ↪o submodule S M := { to_fun := restrict_scalars S, inj' := restrict_scalars_injective S R M, map_rel_iff' := λ p q, by simp [set_like.le_def] } /-- Turning `p : submodule R M` into an `S`-submodule gives the same module structure as turning it into a type and adding a module structure. -/ @[simps {simp_rhs := tt}] def restrict_scalars_equiv (p : submodule R M) : p.restrict_scalars S ≃ₗ[R] p := { to_fun := id, inv_fun := id, map_smul' := λ c x, rfl, .. add_equiv.refl p } end restrict_scalars end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {module_M : module R M} variables (p p' : submodule R M) variables {r : R} {x y : M} instance [module R M] : add_subgroup_class (submodule R M) M := { neg_mem := λ p x, p.to_sub_mul_action.neg_mem, .. submodule.add_submonoid_class } protected lemma neg_mem (hx : x ∈ p) : -x ∈ p := neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl @[simp] lemma mem_to_add_subgroup : x ∈ p.to_add_subgroup ↔ x ∈ p := iff.rfl include module_M theorem to_add_subgroup_injective : injective (to_add_subgroup : submodule R M → add_subgroup M) | p q h := set_like.ext (set_like.ext_iff.1 h : _) @[simp] theorem to_add_subgroup_eq : p.to_add_subgroup = p'.to_add_subgroup ↔ p = p' := to_add_subgroup_injective.eq_iff @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : submodule R M → add_subgroup M) := λ _ _, id lemma to_add_subgroup_le : p.to_add_subgroup ≤ p'.to_add_subgroup ↔ p ≤ p' := iff.rfl @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : submodule R M → add_subgroup M) := to_add_subgroup_strict_mono.monotone omit module_M protected lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := sub_mem protected lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := neg_mem_iff protected lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := add_mem_cancel_right protected lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := add_mem_cancel_left protected lemma coe_neg (x : p) : ((-x : p) : M) = -x := add_subgroup_class.coe_neg _ protected lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := add_subgroup_class.coe_sub _ _ lemma sub_mem_iff_left (hy : y ∈ p) : (x - y) ∈ p ↔ x ∈ p := by rw [sub_eq_add_neg, p.add_mem_iff_left (p.neg_mem hy)] lemma sub_mem_iff_right (hx : x ∈ p) : (x - y) ∈ p ↔ y ∈ p := by rw [sub_eq_add_neg, p.add_mem_iff_right hx, p.neg_mem_iff] instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } end add_comm_group section is_domain variables [ring R] [is_domain R] variables [add_comm_group M] [module R M] {b : ι → M} lemma not_mem_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ∉ N := by { intro hx, simpa using ortho (-1) x hx } lemma ne_zero_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ≠ 0 := mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho) end is_domain section ordered_monoid variables [semiring R] /-- A submodule of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`. -/ instance to_ordered_add_comm_monoid {M} [ordered_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_add_comm_monoid S := subtype.coe_injective.ordered_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`. -/ instance to_linear_ordered_add_comm_monoid {M} [linear_ordered_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_add_comm_monoid S := subtype.coe_injective.linear_ordered_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`. -/ instance to_ordered_cancel_add_comm_monoid {M} [ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_cancel_add_comm_monoid S := subtype.coe_injective.ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`. -/ instance to_linear_ordered_cancel_add_comm_monoid {M} [linear_ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_cancel_add_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) end ordered_monoid section ordered_group variables [ring R] /-- A submodule of an `ordered_add_comm_group` is an `ordered_add_comm_group`. -/ instance to_ordered_add_comm_group {M} [ordered_add_comm_group M] [module R M] (S : submodule R M) : ordered_add_comm_group S := subtype.coe_injective.ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`. -/ instance to_linear_ordered_add_comm_group {M} [linear_ordered_add_comm_group M] [module R M] (S : submodule R M) : linear_ordered_add_comm_group S := subtype.coe_injective.linear_ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end ordered_group end submodule namespace submodule variables [division_ring S] [semiring R] [add_comm_monoid M] [module R M] variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p : submodule R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff s0 end submodule /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [module R M] := submodule R M
db35c3da5ca24e89590f206b3e50e4333768afac
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/int/parity.lean
da98012fac4f87511c8a8f38863fd676507497b4
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
2,846
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The `even` predicate on the integers. -/ import .modeq data.nat.parity algebra.group_power namespace int @[simp] theorem mod_two_ne_one {n : int} : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem mod_two_ne_zero {n : int} : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] def even (n : int) : Prop := 2 ∣ n @[simp] theorem even_coe_nat (n : nat) : even n ↔ nat.even n := have ∀ m, 2 * to_nat m = to_nat (2 * m), from λ m, by cases m; refl, ⟨λ ⟨m, hm⟩, ⟨to_nat m, by rw [this, ←to_nat_coe_nat n, hm]⟩, λ ⟨m, hm⟩, ⟨m, by simp [hm]⟩⟩ theorem even_iff {n : int} : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ instance : decidable_pred even := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm @[simp] theorem even_zero : even (0 : int) := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even (1 : int) := by rw even_iff; apply one_ne_zero @[simp] theorem even_bit0 (n : int) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add {m n : int} : even (m + n) ↔ (even m ↔ even n) := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂], { exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂ end @[simp] theorem not_even_bit1 (n : int) : ¬ even (bit1 n) := by simp [bit1] with parity_simps @[parity_simps] theorem even_sub {m n : int} : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←sub_add_cancel m n, even_add] }, by_cases h : even n; simp [h] end @[parity_simps] theorem even_mul {m n : int} : even (m * n) ↔ even m ∨ even n := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂], { exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂ end @[parity_simps] theorem even_pow {m : int} {n : nat} : even (m^n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, even_mul, pow_succ], tauto } -- Here are examples of how `parity_simps` can be used with `int`. example (m n : int) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even (25394535 : int) := by simp end int