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
6e413d448502b2859d9286e6c17d20d8dc5b8f7d
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/calculus/lagrange_multipliers.lean
311a1f93a418a9e55b4af0949c0aa7da7f56b53f
[ "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
6,756
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.inverse import linear_algebra.dual /-! # Lagrange multipliers In this file we formalize the [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) method of solving conditional extremum problems: if a function `Ο†` has a local extremum at `xβ‚€` on the set `f ⁻¹' {f xβ‚€}`, `f x = (fβ‚€ x, ..., fₙ₋₁ x)`, then the differentials of `fβ‚–` and `Ο†` are linearly dependent. First we formulate a geometric version of this theorem which does not rely on the target space being `ℝⁿ`, then restate it in terms of coordinates. ## TODO Formalize Karush-Kuhn-Tucker theorem ## Tags lagrange multiplier, local extremum -/ open filter set open_locale topological_space filter big_operators variables {E F : Type*} [normed_group E] [normed_space ℝ E] [complete_space E] [normed_group F] [normed_space ℝ F] [complete_space F] {f : E β†’ F} {Ο† : E β†’ ℝ} {xβ‚€ : E} {f' : E β†’L[ℝ] F} {Ο†' : E β†’L[ℝ] ℝ} /-- Lagrange multipliers theorem: if `Ο† : E β†’ ℝ` has a local extremum on the set `{x | f x = f xβ‚€}` at `xβ‚€`, both `f : E β†’ F` and `Ο†` are strictly differentiable at `xβ‚€`, and the codomain of `f` is a complete space, then the linear map `x ↦ (f' x, Ο†' x)` is not surjective. -/ lemma is_local_extr_on.range_ne_top_of_has_strict_fderiv_at (hextr : is_local_extr_on Ο† {x | f x = f xβ‚€} xβ‚€) (hf' : has_strict_fderiv_at f f' xβ‚€) (hΟ†' : has_strict_fderiv_at Ο† Ο†' xβ‚€) : (f'.prod Ο†').range β‰  ⊀ := begin intro htop, set fΟ† := Ξ» x, (f x, Ο† x), have A : map Ο† (𝓝[f ⁻¹' {f xβ‚€}] xβ‚€) = 𝓝 (Ο† xβ‚€), { change map (prod.snd ∘ fΟ†) (𝓝[fΟ† ⁻¹' {p | p.1 = f xβ‚€}] xβ‚€) = 𝓝 (Ο† xβ‚€), rw [← map_map, nhds_within, map_inf_principal_preimage, (hf'.prod hΟ†').map_nhds_eq_of_surj htop], exact map_snd_nhds_within _ }, exact hextr.not_nhds_le_map A.ge end /-- Lagrange multipliers theorem: if `Ο† : E β†’ ℝ` has a local extremum on the set `{x | f x = f xβ‚€}` at `xβ‚€`, both `f : E β†’ F` and `Ο†` are strictly differentiable at `xβ‚€`, and the codomain of `f` is a complete space, then there exist `Ξ› : dual ℝ F` and `Ξ›β‚€ : ℝ` such that `(Ξ›, Ξ›β‚€) β‰  0` and `Ξ› (f' x) + Ξ›β‚€ β€’ Ο†' x = 0` for all `x`. -/ lemma is_local_extr_on.exists_linear_map_of_has_strict_fderiv_at (hextr : is_local_extr_on Ο† {x | f x = f xβ‚€} xβ‚€) (hf' : has_strict_fderiv_at f f' xβ‚€) (hΟ†' : has_strict_fderiv_at Ο† Ο†' xβ‚€) : βˆƒ (Ξ› : module.dual ℝ F) (Ξ›β‚€ : ℝ), (Ξ›, Ξ›β‚€) β‰  0 ∧ βˆ€ x, Ξ› (f' x) + Ξ›β‚€ β€’ Ο†' x = 0 := begin rcases submodule.exists_le_ker_of_lt_top _ (lt_top_iff_ne_top.2 $ hextr.range_ne_top_of_has_strict_fderiv_at hf' hΟ†') with βŸ¨Ξ›', h0, hΞ›'⟩, set e : ((F β†’β‚—[ℝ] ℝ) Γ— ℝ) ≃ₗ[ℝ] (F Γ— ℝ β†’β‚—[ℝ] ℝ) := ((linear_equiv.refl ℝ (F β†’β‚—[ℝ] ℝ)).prod (linear_map.ring_lmap_equiv_self ℝ ℝ ℝ).symm).trans (linear_map.coprod_equiv ℝ), rcases e.surjective Ξ›' with βŸ¨βŸ¨Ξ›, Ξ›β‚€βŸ©, rfl⟩, refine βŸ¨Ξ›, Ξ›β‚€, e.map_ne_zero_iff.1 h0, Ξ» x, _⟩, convert linear_map.congr_fun (linear_map.range_le_ker_iff.1 hΞ›') x using 1, -- squeezed `simp [mul_comm]` to speed up elaboration simp only [linear_map.coprod_equiv_apply, linear_equiv.refl_apply, linear_map.ring_lmap_equiv_self_symm_apply, linear_map.comp_apply, continuous_linear_map.coe_coe, continuous_linear_map.prod_apply, linear_equiv.trans_apply, linear_equiv.prod_apply, linear_map.coprod_apply, linear_map.smul_right_apply, linear_map.one_apply, smul_eq_mul, mul_comm] end /-- Lagrange multipliers theorem. Let `f : ΞΉ β†’ E β†’ ℝ` be a finite family of functions. Suppose that `Ο† : E β†’ ℝ` has a local extremum on the set `{x | βˆ€ i, f i x = f i xβ‚€}` at `xβ‚€`. Suppose that all functions `f i` as well as `Ο†` are strictly differentiable at `xβ‚€`. Then the derivatives `f' i : E β†’ L[ℝ] ℝ` and `Ο†' : E β†’L[ℝ] ℝ` are linearly dependent: there exist `Ξ› : ΞΉ β†’ ℝ` and `Ξ›β‚€ : ℝ`, `(Ξ›, Ξ›β‚€) β‰  0`, such that `βˆ‘ i, Ξ› i β€’ f' i + Ξ›β‚€ β€’ Ο†' = 0`. See also `is_local_extr_on.linear_dependent_of_has_strict_fderiv_at` for a version that states `Β¬linear_independent ℝ _` instead of existence of `Ξ›` and `Ξ›β‚€`. -/ lemma is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at {ΞΉ : Type*} [fintype ΞΉ] {f : ΞΉ β†’ E β†’ ℝ} {f' : ΞΉ β†’ E β†’L[ℝ] ℝ} (hextr : is_local_extr_on Ο† {x | βˆ€ i, f i x = f i xβ‚€} xβ‚€) (hf' : βˆ€ i, has_strict_fderiv_at (f i) (f' i) xβ‚€) (hΟ†' : has_strict_fderiv_at Ο† Ο†' xβ‚€) : βˆƒ (Ξ› : ΞΉ β†’ ℝ) (Ξ›β‚€ : ℝ), (Ξ›, Ξ›β‚€) β‰  0 ∧ βˆ‘ i, Ξ› i β€’ f' i + Ξ›β‚€ β€’ Ο†' = 0 := begin letI := classical.dec_eq ΞΉ, replace hextr : is_local_extr_on Ο† {x | (Ξ» i, f i x) = (Ξ» i, f i xβ‚€)} xβ‚€, by simpa only [function.funext_iff] using hextr, rcases hextr.exists_linear_map_of_has_strict_fderiv_at (has_strict_fderiv_at_pi.2 (Ξ» i, hf' i)) hΟ†' with βŸ¨Ξ›, Ξ›β‚€, h0, hsum⟩, rcases (linear_equiv.pi_ring ℝ ℝ ΞΉ ℝ).symm.surjective Ξ› with βŸ¨Ξ›, rfl⟩, refine βŸ¨Ξ›, Ξ›β‚€, _, _⟩, { simpa only [ne.def, prod.ext_iff, linear_equiv.map_eq_zero_iff, prod.fst_zero] using h0 }, { ext x, simpa [mul_comm] using hsum x } end /-- Lagrange multipliers theorem. Let `f : ΞΉ β†’ E β†’ ℝ` be a finite family of functions. Suppose that `Ο† : E β†’ ℝ` has a local extremum on the set `{x | βˆ€ i, f i x = f i xβ‚€}` at `xβ‚€`. Suppose that all functions `f i` as well as `Ο†` are strictly differentiable at `xβ‚€`. Then the derivatives `f' i : E β†’ L[ℝ] ℝ` and `Ο†' : E β†’L[ℝ] ℝ` are linearly dependent. See also `is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at` for a version that that states existence of Lagrange multipliers `Ξ›` and `Ξ›β‚€` instead of using `Β¬linear_independent ℝ _` -/ lemma is_local_extr_on.linear_dependent_of_has_strict_fderiv_at {ΞΉ : Type*} [fintype ΞΉ] {f : ΞΉ β†’ E β†’ ℝ} {f' : ΞΉ β†’ E β†’L[ℝ] ℝ} (hextr : is_local_extr_on Ο† {x | βˆ€ i, f i x = f i xβ‚€} xβ‚€) (hf' : βˆ€ i, has_strict_fderiv_at (f i) (f' i) xβ‚€) (hΟ†' : has_strict_fderiv_at Ο† Ο†' xβ‚€) : Β¬linear_independent ℝ (Ξ» i, option.elim i Ο†' f' : option ΞΉ β†’ E β†’L[ℝ] ℝ) := begin rw [fintype.linear_independent_iff], push_neg, rcases hextr.exists_multipliers_of_has_strict_fderiv_at hf' hΟ†' with βŸ¨Ξ›, Ξ›β‚€, hΞ›, hΞ›f⟩, refine ⟨λ i, option.elim i Ξ›β‚€ Ξ›, _, _⟩, { simpa [add_comm] using hΞ›f }, { simpa [function.funext_iff, not_and_distrib, or_comm, option.exists] using hΞ› } end
3e93f7d2a02c284e906a25133989b397a6330953
9c2e8d73b5c5932ceb1333265f17febc6a2f0a39
/src/S4/full_language.lean
5b52f2ea428cca39fa9a709c3d55321b5f7e2323
[ "MIT" ]
permissive
minchaowu/ModalTab
2150392108dfdcaffc620ff280a8b55fe13c187f
9bb0bf17faf0554d907ef7bdd639648742889178
refs/heads/master
1,626,266,863,244
1,592,056,874,000
1,592,056,874,000
153,314,364
12
1
null
null
null
null
UTF-8
Lean
false
false
10,184
lean
import .semantics inductive fml | var (n : nat) | neg (Ο† : fml) | and (Ο† ψ : fml) | or (Ο† ψ : fml) | impl (Ο† ψ : fml) | box (Ο† : fml) | dia (Ο† : fml) open fml def fml.to_string : fml β†’ string | (var n) := "P" ++ n.repr | (neg Ο•) := "Β¬" ++ "(" ++ fml.to_string Ο• ++ ")" | (and Ο† ψ) := fml.to_string Ο† ++ "∧" ++ fml.to_string ψ | (or Ο† ψ) := fml.to_string Ο† ++ "∨" ++ fml.to_string ψ | (impl Ο† ψ) := fml.to_string Ο† ++ "β†’" ++ fml.to_string ψ | (box Ο†) := "β–‘" ++ "(" ++ fml.to_string Ο† ++ ")" | (dia Ο†) := "β—‡" ++ "(" ++ fml.to_string Ο† ++ ")" instance fml_repr : has_repr fml := ⟨fml.to_string⟩ instance dec_eq_fml : decidable_eq fml := by tactic.mk_dec_eq_instance @[simp] def fml_size : fml β†’ β„• | (var n) := 1 | (neg Ο†) := fml_size Ο† + 1 | (and Ο† ψ) := fml_size Ο† + fml_size ψ + 1 | (or Ο† ψ) := fml_size Ο† + fml_size ψ + 1 | (impl Ο† ψ) := fml_size Ο† + fml_size ψ + 2 | (box Ο†) := fml_size Ο† + 1 | (dia Ο†) := fml_size Ο† + 1 @[simp] def fml_force {states : Type} (k : S4 states) : states β†’ fml β†’ Prop | s (var n) := k.val n s | s (neg Ο†) := Β¬ fml_force s Ο† | s (and Ο† ψ) := fml_force s Ο† ∧ fml_force s ψ | s (or Ο† ψ) := fml_force s Ο† ∨ fml_force s ψ | s (impl Ο† ψ) := Β¬ fml_force s Ο† ∨ fml_force s ψ | s (box Ο†) := βˆ€ s', k.rel s s' β†’ fml_force s' Ο† | s (dia Ο†) := βˆƒ s', k.rel s s' ∧ fml_force s' Ο† @[simp] def fml.to_nnf : fml β†’ nnf | (var n) := nnf.var n | (neg (var n)) := nnf.neg n | (neg (neg Ο†)) := fml.to_nnf Ο† | (neg (and Ο† ψ)) := nnf.or (fml.to_nnf (neg Ο†)) (fml.to_nnf (neg ψ)) | (neg (or Ο† ψ)) := nnf.and (fml.to_nnf (neg Ο†)) (fml.to_nnf (neg ψ)) | (neg (impl Ο† ψ)) := nnf.and (fml.to_nnf Ο†) (fml.to_nnf (neg ψ)) | (neg (box Ο†)) := nnf.dia (fml.to_nnf (neg Ο†)) | (neg (dia Ο†)) := nnf.box (fml.to_nnf (neg Ο†)) | (and Ο† ψ) := nnf.and (fml.to_nnf Ο†) (fml.to_nnf ψ) | (or Ο† ψ) := nnf.or (fml.to_nnf Ο†) (fml.to_nnf ψ) | (impl Ο† ψ) := nnf.or (fml.to_nnf (neg Ο†)) (fml.to_nnf ψ) | (box Ο†) := nnf.box (fml.to_nnf Ο†) | (dia Ο†) := nnf.dia (fml.to_nnf Ο†) using_well_founded {rel_tac := Ξ» _ _, `[exact ⟨_, measure_wf fml_size⟩]} @[simp] def trans_size_left {st} (k : S4 st) : (Ξ£' (s) (Ο† : fml), fml_force k s Ο†) β†’ β„• := Ξ» h, fml_size h.snd.fst @[simp] def trans_size_right {st} (k : S4 st) : (Ξ£' (s : st) (Ο† : fml), force k s (fml.to_nnf Ο†)) β†’ β„• := Ξ» h, fml_size h.snd.fst theorem trans_left {st} (k : S4 st) : Ξ  s Ο†, fml_force k s Ο† β†’ force k s (fml.to_nnf Ο†) | s (var n) h := h | s (neg (var n)) h := h | s (neg (neg Ο†)) h := by dsimp at h; rw classical.not_not at h; exact trans_left _ _ h | s (neg (and Ο† ψ)) h := begin have := trans_left s (neg Ο†), dsimp at h, rw classical.not_and_distrib at h, cases h with l r, {simp [trans_left _ (neg Ο†) l]}, {simp [trans_left _ (neg ψ) r]} end | s (neg (or Ο† ψ)) h := begin dsimp at h, rw not_or_distrib at h, simp [and.intro (trans_left _ (neg Ο†) h.1) (trans_left _ (neg ψ) h.2)] end | s (neg (impl Ο† ψ)) h := begin dsimp at h, rw not_or_distrib at h, have : force k s (fml.to_nnf Ο†), { apply trans_left, have := h.1, rw classical.not_not at this, exact this }, simp [and.intro this (trans_left _ (neg ψ) h.2)] end | s (neg (box Ο†)) h := begin dsimp at h, rw classical.not_forall at h, cases h with w hw, rw classical.not_imp at hw, simp, split, split, {exact hw.1}, {apply trans_left, exact hw.2} end | s (neg (dia Ο†)) h := begin dsimp at h, simp, intros s' hs', rw not_exists at h, have := h s', rw not_and at this, have hnf := this hs', apply trans_left, exact hnf end | s (and Ο† ψ) h := by dsimp at h; simp [and.intro (trans_left _ _ h.1) (trans_left _ _ h.2)] | s (or Ο† ψ) h := begin dsimp at h, cases h, {exact or.inl (trans_left _ _ h)}, {exact or.inr (trans_left _ _ h)} end | s (impl Ο† ψ) h := begin dsimp at h, simp, cases h, {left, apply trans_left, exact h}, {right, apply trans_left, exact h} end | s (box Ο†) h := begin dsimp at h, simp, intros s' hs', exact trans_left _ _ (h s' hs') end | s (dia Ο†) h := begin dsimp at h, simp, cases h with w hw, split, split, {exact hw.1}, {exact trans_left _ _ hw.2} end using_well_founded {rel_tac := Ξ» _ _, `[exact ⟨_, measure_wf (trans_size_left k)⟩]} theorem trans_right {st} (k : S4 st) : Ξ  s Ο†, force k s (fml.to_nnf Ο†) β†’ fml_force k s Ο† | s (var n) h := h | s (neg (var n)) h := h | s (neg (neg Ο†)) h := by dsimp; simp at h; exact not_not_intro (trans_right _ _ h) | s (neg (and Ο† ψ)) h := begin dsimp, simp at h, apply not_and_of_not_or_not, cases h, {left, exact trans_right _ _ h}, {right, exact trans_right _ _ h} end | s (neg (or Ο† ψ)) h := begin dsimp, simp at h, apply not_or, {exact trans_right _ _ h.1}, {exact trans_right _ _ h.2} end | s (neg (impl Ο† ψ)) h := begin dsimp, simp at h, apply not_or, {exact not_not_intro (trans_right _ _ h.1)}, {exact trans_right _ _ h.2} end | s (neg (box Ο†)) h := begin dsimp, simp at h, apply not_forall_of_exists_not, cases h with w hw, split, {apply not_imp_of_and_not, split, exact hw.1, exact trans_right _ _ hw.2} end | s (neg (dia Ο†)) h := begin dsimp, simp at h, rw not_exists, intros s' hs', have := h s' hs'.1, have hn := trans_right _ _ this, have := hs'.2, contradiction end | s (and Ο† ψ) h := begin dsimp, simp at h, split, {exact trans_right _ _ h.1}, {exact trans_right _ _ h.2} end | s (or Ο† ψ) h := begin dsimp, simp at h, cases h, {left, exact trans_right _ _ h}, {right, exact trans_right _ _ h} end | s (impl Ο† ψ) h := begin dsimp, simp at h, cases h, {left, exact trans_right _ _ h}, {right, exact trans_right _ _ h} end | s (box Ο†) h := begin dsimp, simp at h, intros s' hs', exact trans_right _ _ (h s' hs') end | s (dia Ο†) h := begin dsimp, simp at h, cases h with w hw, split, split, {exact hw.1}, {exact trans_right _ _ hw.2} end using_well_founded {rel_tac := Ξ» _ _, `[exact ⟨_, measure_wf (trans_size_right k)⟩]} theorem trans_iff {st} (k : S4 st) (s Ο†) : fml_force k s Ο† ↔ force k s (fml.to_nnf Ο†) := ⟨trans_left k s Ο†, trans_right k s Ο†βŸ© def fml_sat {st} (k : S4 st) (s) (Ξ“ : list fml) : Prop := βˆ€ Ο† ∈ Ξ“, fml_force k s Ο† theorem fml_sat_of_empty {st} (k : S4 st) (s) : fml_sat k s [] := Ξ» Ο† h, absurd h $ list.not_mem_nil _ def fml_unsatisfiable (Ξ“ : list fml) : Prop := βˆ€ (st) (k : S4 st) s, Β¬ fml_sat k s Ξ“ theorem trans_sat_iff {st} (k : S4 st) (s) : Ξ  Ξ“, fml_sat k s Ξ“ ↔ sat k s (list.map fml.to_nnf Ξ“) | [] := by simp [sat_of_empty, fml_sat_of_empty] | (hd::tl) := begin split, { intro h, dsimp, intros Ο† hΟ†, cases hΟ†, { rw hΟ†, rw ←trans_iff, apply h, simp }, { have : fml_sat k s tl, { intros ψ hψ, apply h, simp [hψ] }, rw trans_sat_iff at this, exact this _ hΟ† } }, { intros h Ο† hΟ†, cases hΟ†, { rw hΟ†, rw trans_iff, apply h, simp }, { have : sat k s (list.map fml.to_nnf tl), { intros ψ hψ, apply h, simp [hψ] }, rw ←trans_sat_iff at this, exact this _ hΟ† } } end theorem trans_unsat_iff (Ξ“ : list fml) : fml_unsatisfiable Ξ“ ↔ unsatisfiable (list.map fml.to_nnf Ξ“) := begin split, {intros h _ _ _ _, apply h, rw trans_sat_iff, assumption}, {intros h _ _ _ _, apply h, rw ←trans_sat_iff, assumption} end
7d282496ecc42266e97a248bcc329aa8aed320bd
5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61
/floats.lean
13e71340d2ea813a5fe674ef1862684d8ab95a87
[]
no_license
mbrodersen/kremlin
f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec
d4665929ce9012e93a0b05fc7063b96256bab86f
refs/heads/master
1,624,057,268,130
1,496,957,084,000
1,496,957,084,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,815
lean
/- Formalization of floating-point numbers, using the Flocq library. -/ import .integers .lib .flocq .archi namespace floats open integers flocq word /- Boolean-valued comparisons -/ def cmp_of_comparison : comparison β†’ option ordering β†’ bool | Ceq (some ordering.eq) := tt | Ceq _ := ff | Cne (some ordering.eq) := ff | Cne _ := tt | Clt (some ordering.lt) := tt | Clt _ := ff | Cle (some ordering.lt) := tt | Cle (some ordering.eq) := tt | Cle _ := ff | Cgt (some ordering.gt) := tt | Cgt _ := ff | Cge (some ordering.gt) := tt | Cge (some ordering.eq) := tt | Cge _ := ff lemma cmp_of_comparison_swap (c x) : cmp_of_comparison (swap_comparison c) x = cmp_of_comparison c (ordering.swap <$> x) := sorry' lemma cmp_of_comparison_ne_eq (x) : cmp_of_comparison Cne x = bnot (cmp_of_comparison Ceq x) := sorry' lemma cmp_of_comparison_lt_not_eq (x) : cmp_of_comparison Clt x β†’ Β¬ cmp_of_comparison Ceq x := sorry' lemma cmp_of_comparison_le_lt_eq (x) : cmp_of_comparison Cle x = cmp_of_comparison Clt x || cmp_of_comparison Ceq x := sorry' lemma cmp_of_comparison_gt_not_eq (x) : cmp_of_comparison Cgt x β†’ Β¬ cmp_of_comparison Ceq x := sorry' lemma cmp_of_comparison_ge_gt_eq (x) : cmp_of_comparison Cge x = cmp_of_comparison Cgt x || cmp_of_comparison Ceq x := sorry' lemma cmp_of_comparison_lt_not_gt (x) : cmp_of_comparison Clt x β†’ Β¬ cmp_of_comparison Cgt x := sorry' def float : Type := sorry' /- the type of IEE754 double-precision FP numbers -/ def float32 : Type := sorry' /- the type of IEE754 single-precision FP numbers -/ /- * Double-precision FP numbers -/ namespace float /- ** NaN payload manipulations -/ /- The following definitions are not part of the IEEE754 standard but apply to all architectures supported by CompCert. -/ /- Transform a Nan payload to a quiet Nan payload. -/ def transform_quiet_pl (pl : nan_pl 53) : nan_pl 53 := word.or pl (word.repr (2^22)) lemma transform_quiet_pl_idempotent (pl) : transform_quiet_pl (transform_quiet_pl pl) = transform_quiet_pl pl := sorry' /- Nan payload operations for single <-> double conversions. -/ def expand_pl (pl : nan_pl 24) : nan_pl 53 := word.shl (ucoe pl) (repr 29) def of_single_pl (s : bool) (pl : nan_pl 24) : bool Γ— nan_pl 53 := (s, if archi.float_of_single_preserves_sNaN then expand_pl pl else transform_quiet_pl (expand_pl pl)) def reduce_pl (pl : nan_pl 53) : nan_pl 24 := ucoe (word.shr pl (repr 29)) def to_single_pl (s : bool) (pl : nan_pl 53) : bool Γ— nan_pl 24 := (s, reduce_pl (transform_quiet_pl pl)) /- NaN payload operations for opposite and absolute value. -/ def neg_pl (s : bool) (pl : nan_pl 53) := (bnot s, pl) def abs_pl (s : bool) (pl : nan_pl 53) := (ff, pl) /- The NaN payload operations for two-argument arithmetic operations are not part of the IEEE754 standard, but all architectures of Compcert share a similar NaN behavior, parameterized by: - a "default" payload which occurs when an operation generates a NaN from non-NaN arguments; - a choice function determining which of the payload arguments to choose, when an operation is given two NaN arguments. -/ def binop_pl (x y : binary64) : bool Γ— nan_pl 53 := sorry' /- ** Operations over double-precision floats -/ def zero : float := sorry' /- the float [+0.0] -/ instance : has_zero float := ⟨zero⟩ instance eq_dec : decidable_eq float := sorry' /- Arithmetic operations -/ protected def neg : float β†’ float := sorry' /- opposite (change sign) -/ def abs : float β†’ float := sorry' /- absolute value (set sign to [+]) -/ protected def add : float β†’ float β†’ float := sorry' /- addition -/ protected def sub : float β†’ float β†’ float := sorry' /- subtraction -/ protected def mul : float β†’ float β†’ float := sorry' /- multiplication -/ protected def div : float β†’ float β†’ float := sorry' /- division -/ def cmp (c:comparison) (f1 f2 : float) : bool := /- comparison -/ cmp_of_comparison c sorry' instance : has_add float := ⟨float.add⟩ instance : has_neg float := ⟨float.neg⟩ instance : has_sub float := ⟨float.sub⟩ instance : has_mul float := ⟨float.mul⟩ instance : has_div float := ⟨float.div⟩ /- Conversions -/ def of_single : float32 β†’ float := sorry' def to_single : float β†’ float32 := sorry' def to_int (f:float) : option int32 := /- conversion to signed 32-bit int -/ repr <$> sorry' def to_intu (f:float) : option int32 := /- conversion to unsigned 32-bit int -/ repr <$> sorry' def to_long (f:float) : option int64 := /- conversion to signed 64-bit int -/ repr <$> sorry' def to_longu (f:float) : option int64 := /- conversion to unsigned 64-bit int -/ repr <$> sorry' def of_int (n:int32) : float := /- conversion from signed 32-bit int -/ sorry' def of_intu (n:int32) : float:= /- conversion from unsigned 32-bit int -/ sorry' def of_long (n:int64) : float := /- conversion from signed 64-bit int -/ sorry' def of_longu (n:int64) : float:= /- conversion from unsigned 64-bit int -/ sorry' instance coe_int32_float : has_coe int32 float := ⟨of_int⟩ instance coe_int64_float : has_coe int64 float := ⟨of_long⟩ def from_parsed (base : pos_num) (intPart : pos_num) (expPart : β„€) : float := sorry' /- Conversions between floats and their concrete in-memory representation as a sequence of 64 bits. -/ def to_bits (f : float) : int64 := sorry' def of_bits (b : int64) : float := sorry' def from_words (hi lo : int32) : float := of_bits (int64.ofwords hi lo) def is_nan : float β†’ bool := sorry' /- ** Properties -/ /- Below are the only properties of floating-point arithmetic that we rely on in the compiler proof. -/ /- Commutativity properties of addition and multiplication. -/ theorem add_comm (x y) : Β¬ is_nan x ∨ Β¬ is_nan y β†’ x + y = y + x := sorry' theorem mul_comm (x y) : Β¬ is_nan x ∨ Β¬ is_nan y β†’ x * y = y * x := sorry' /- Multiplication by 2 is diagonal addition. -/ theorem mul2_add (f) : f + f = f * of_int 2 := sorry' /- Divisions that can be turned into multiplication by an inverse. -/ def exact_inverse : float β†’ option float := sorry' theorem div_mul_inverse (x y z) : exact_inverse y = some z β†’ x / y = x * z := sorry' /- Properties of comparisons. -/ lemma cmp_swap (c x y) : cmp (swap_comparison c) x y = cmp c y x := sorry' lemma cmp_ne_eq (x y) : cmp Cne x y = bnot (cmp Ceq x y) := sorry' lemma cmp_lt_not_eq (x y) : cmp Clt x y β†’ Β¬ cmp Ceq x y := sorry' lemma cmp_le_lt_eq (x y) : cmp Cle x y = cmp Clt x y || cmp Ceq x y := sorry' lemma cmp_gt_not_eq (x y) : cmp Cgt x y β†’ Β¬ cmp Ceq x y := sorry' lemma cmp_ge_gt_eq (x y) : cmp Cge x y = cmp Cgt x y || cmp Ceq x y := sorry' lemma cmp_lt_not_gt (x y) : cmp Clt x y β†’ Β¬ cmp Cgt x y := sorry' /- Properties of conversions to/from in-memory representation. The conversions are bijective (one-to-one). -/ theorem of_to_bits (f) : of_bits (to_bits f) = f := sorry' theorem to_of_bits (b) : to_bits (of_bits b) = b := sorry' /- Conversions between floats and unsigned ints can be defined in terms of conversions between floats and signed ints. (Most processors provide only the latter, forcing the compiler to emulate the former.) -/ def half32 : int32 := repr (@min_signed W32). /- [0x8000_0000] -/ theorem of_intu_of_int_1 (x) : word.ltu x half32 β†’ of_intu x = of_int x := sorry' theorem of_intu_of_int_2 (x) : Β¬ word.ltu x half32 β†’ of_intu x = of_int (x - half32) + of_intu half32 := sorry' theorem to_intu_to_int_1 (x n) : cmp Clt x (of_intu half32) β†’ to_intu x = some n β†’ to_int x = some n := sorry' theorem to_intu_to_int_2 (x n) : Β¬ cmp Clt x (of_intu half32) β†’ to_intu x = some n β†’ to_int (x - of_intu half32) = some (n - half32) := sorry' /- Conversions from ints to floats can be defined as bitwise manipulations over the in-memory representation. This is what the PowerPC port does. The trick is that [from_words 0x4330_0000 x] is the float [2^52 + of_intu x]. -/ def bit433 : int32 := repr 0x43300000 lemma split_bits_or (x) : split_bits 52 11 (unsigned (int64.ofwords bit433 x)) = (ff, unsigned x, 1075) := sorry' theorem of_intu_from_words (x) : of_intu x = from_words bit433 x - from_words bit433 0 := sorry' lemma half32_signed_unsigned (x) : (unsigned (x + half32) : β„€) = signed x + @half_modulus W32 := sorry' theorem of_int_from_words (x) : of_int x = from_words bit433 (x + half32) - from_words bit433 half32 := sorry' def bit453 : int32 := repr 0x45300000 lemma split_bits_or' (x) : split_bits 52 11 (unsigned (int64.ofwords bit453 x)) = (ff, unsigned x, 1107) := sorry' theorem of_longu_from_words (l) : of_longu l = from_words bit453 (int64.hiword l) - from_words bit453 (repr (2^20)) + from_words bit433 (int64.loword l) := sorry' theorem of_long_from_words (l) : of_long l = from_words bit453 (int64.hiword l + half32) - from_words bit453 (repr (2^20+2^31)) + from_words bit433 (int64.loword l) := sorry' /- Conversions from unsigned longs can be expressed in terms of conversions from signed longs. If the unsigned long is too big, a round-to-odd must be performed on it to avoid double rounding. -/ theorem of_longu_of_long_1 (x) : word.ltu x (repr (@half_modulus W64)) β†’ of_longu x = of_long x := sorry' theorem of_longu_of_long_2 (x) : Β¬ word.ltu x (repr (@half_modulus W64)) β†’ of_longu x = of_long (word.or (word.shru x 1) (word.and x 1)) * of_int (repr 2) := sorry' end float /- * Single-precision FP numbers -/ namespace float32 /- ** NaN payload manipulations -/ def transform_quiet_pl (pl : nan_pl 24) : nan_pl 24 := word.or pl (repr (2^22)) lemma transform_quiet_pl_idempotent (pl) : transform_quiet_pl (transform_quiet_pl pl) = transform_quiet_pl pl := sorry' def neg_pl (s:bool) (pl:nan_pl 24) := (bnot s, pl) def abs_pl (s:bool) (pl:nan_pl 24) := (ff, pl) def binop_pl (x y : binary32) : bool Γ— nan_pl 24 := sorry' /- ** Operations over single-precision floats -/ def zero : float32 := sorry' /- the float [+0.0] -/ instance : has_zero float32 := ⟨zero⟩ instance eq_dec : decidable_eq float32 := sorry' /- Arithmetic operations -/ protected def neg : float32 β†’ float32 := sorry' /- opposite (change sign) -/ def abs : float32 β†’ float32 := sorry' /- absolute value (set sign to [+]) -/ protected def add : float32 β†’ float32 β†’ float32 := sorry' /- addition -/ protected def sub : float32 β†’ float32 β†’ float32 := sorry' /- subtraction -/ protected def mul : float32 β†’ float32 β†’ float32 := sorry' /- multiplication -/ protected def div : float32 β†’ float32 β†’ float32 := sorry' /- division -/ def cmp (c:comparison) (f1 f2 : float32) : bool := /- comparison -/ cmp_of_comparison c sorry' instance : has_add float32 := ⟨float32.add⟩ instance : has_neg float32 := ⟨float32.neg⟩ instance : has_sub float32 := ⟨float32.sub⟩ instance : has_mul float32 := ⟨float32.mul⟩ instance : has_div float32 := ⟨float32.div⟩ /- Conversions -/ def of_double : float β†’ float32 := float.to_single def to_double : float32 β†’ float := float.of_single def to_int (f:float32) : option int32 := /- conversion to signed 32-bit int -/ repr <$> sorry' def to_intu (f:float32) : option int32 := /- conversion to unsigned 32-bit int -/ repr <$> sorry' def to_long (f:float32) : option int64 := /- conversion to signed 64-bit int -/ repr <$> sorry' def to_longu (f:float32) : option int64 := /- conversion to unsigned 64-bit int -/ repr <$> sorry' def of_int (n:int32) : float32 := /- conversion from signed 32-bit int to single-precision float -/ sorry' def of_intu (n:int32) : float32 := /- conversion from unsigned 32-bit int to single-precision float -/ sorry' def of_long (n:int64) : float32 := /- conversion from signed 64-bit int to single-precision float -/ sorry' def of_longu (n:int64) : float32 := /- conversion from unsigned 64-bit int to single-precision float -/ sorry' def from_parsed (base : pos_num) (intPart : pos_num) (expPart : β„€) : float32 := sorry' /- Conversions between floats and their concrete in-memory representation as a sequence of 32 bits. -/ def to_bits (f : float32) : int32 := sorry' def of_bits (b : int32) : float32 := sorry' def is_nan : float32 β†’ bool := sorry' /- ** Properties -/ /- Commutativity properties of addition and multiplication. -/ theorem add_comm (x y) : Β¬ is_nan x ∨ Β¬ is_nan y β†’ x + y = y + x := sorry' theorem mul_comm (x y) : Β¬ is_nan x ∨ Β¬ is_nan y β†’ x * y = y * x := sorry' /- Multiplication by 2 is diagonal addition. -/ theorem mul2_add (f) : f + f = f * of_int 2 := sorry' /- Divisions that can be turned into multiplication by an inverse. -/ def exact_inverse : float32 β†’ option float32 := sorry' theorem div_mul_inverse (x y z) : exact_inverse y = some z β†’ x / y = x * z := sorry' /- Properties of comparisons. -/ lemma cmp_swap (c x y) : cmp (swap_comparison c) x y = cmp c y x := sorry' lemma cmp_ne_eq (x y) : cmp Cne x y = bnot (cmp Ceq x y) := sorry' lemma cmp_lt_not_eq (x y) : cmp Clt x y β†’ Β¬ cmp Ceq x y := sorry' lemma cmp_le_lt_eq (x y) : cmp Cle x y = cmp Clt x y || cmp Ceq x y := sorry' lemma cmp_gt_not_eq (x y) : cmp Cgt x y β†’ Β¬ cmp Ceq x y := sorry' lemma cmp_ge_gt_eq (x y) : cmp Cge x y = cmp Cgt x y || cmp Ceq x y := sorry' lemma cmp_lt_not_gt (x y) : cmp Clt x y β†’ Β¬ cmp Cgt x y := sorry' theorem cmp_double (f1 f2 c) : cmp c f1 f2 = float.cmp c (to_double f1) (to_double f2) := sorry' /- Properties of conversions to/from in-memory representation. The conversions are bijective (one-to-one). -/ theorem of_to_bits (f) : of_bits (to_bits f) = f := sorry' theorem to_of_bits (b) : to_bits (of_bits b) = b := sorry' /- Conversions from 32-bit integers to single-precision floats can be decomposed into a conversion to a double-precision float, followed by a [Float32.of_double] conversion. No double rounding occurs. -/ theorem of_int_double (n) : of_int n = of_double (float.of_int n) := sorry' theorem of_intu_double (n) : of_intu n = of_double (float.of_intu n) := sorry' /- Conversion of single-precision floats to integers can be decomposed into a [Float32.to_double] extension, followed by a double-precision-to-int conversion. -/ theorem to_int_double (f n) : to_int f = some n β†’ float.to_int (to_double f) = some n := sorry' theorem to_intu_double (f n) : to_intu f = some n β†’ float.to_intu (to_double f) = some n := sorry' theorem to_long_double (f n) : to_long f = some n β†’ float.to_long (to_double f) = some n := sorry' theorem to_longu_double (f n) : to_longu f = some n β†’ float.to_longu (to_double f) = some n := sorry' /- Conversions from 64-bit integers to single-precision floats can be expressed as conversion to a double-precision float followed by a [Float32.of_double] conversion. To avoid double rounding when the integer is large (above [2^53]), a round to odd must be performed on the integer before conversion to double-precision float. -/ lemma int_round_odd_plus (p n) : int_round_odd n p = int.land (int.lor n (int.land n (2^p-1) + (2^p-1))) (-(2^p)) := sorry' theorem of_longu_double_1 (n) : unsigned n ≀ 2^53 β†’ of_longu n = of_double (float.of_longu n) := sorry' theorem of_longu_double_2 (n) : 2^36 ≀ unsigned n β†’ of_longu n = of_double (float.of_longu $ word.and (word.or n (word.and n (repr 2047) + repr 2047)) (repr (-2048))) := sorry' theorem of_long_double_1 (n) : (signed n).nat_abs ≀ 2^53 β†’ of_long n = of_double (float.of_long n) := sorry' theorem of_long_double_2 (n) : 2^36 ≀ (signed n).nat_abs β†’ of_long n = of_double (float.of_long $ word.and (word.or n (word.and n (repr 2047) + repr 2047)) (repr (-2048))) := sorry' end float32 end floats
ef314ca9da6fbfb6906bdca78a0f7bad42e8da8e
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/rs.lean
640534001f9ecc0d0557bf48de27c8df6a2f9730
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
378
lean
rewrite_set S variable bracket : Type β†’ Bool axiom bracket_eq (a : Bool) : bracket a = a add_rewrite bracket_eq : S add_rewrite and_truer and_comm not_true not_neq not_and exists_or_distribute exists_and_distributel : S add_rewrite exists_rem eq_id forall_rem : S add_rewrite Nat::add_zeror Nat::add_comm Nat::add_assoc Nat::mul_comm not_true not_false : S print rewrite_set S
fa51739235f45901a456468a2b4c22aa7fdc2643
94e33a31faa76775069b071adea97e86e218a8ee
/src/combinatorics/composition.lean
d7dcb7f1871a34082fd98353be16103327be2c1e
[ "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
36,432
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 data.finset.sort import algebra.big_operators.order import algebra.big_operators.fin /-! # Compositions A composition of a natural number `n` is a decomposition `n = iβ‚€ + ... + i_{k-1}` of `n` into a sum of positive integers. Combinatorially, it corresponds to a decomposition of `{0, ..., n-1}` into non-empty blocks of consecutive integers, where the `iβ±Ό` are the lengths of the blocks. This notion is closely related to that of a partition of `n`, but in a composition of `n` the order of the `iβ±Ό`s matters. We implement two different structures covering these two viewpoints on compositions. The first one, made of a list of positive integers summing to `n`, is the main one and is called `composition n`. The second one is useful for combinatorial arguments (for instance to show that the number of compositions of `n` is `2^(n-1)`). It is given by a subset of `{0, ..., n}` containing `0` and `n`, where the elements of the subset (other than `n`) correspond to the leftmost points of each block. The main API is built on `composition n`, and we provide an equivalence between the two types. ## Main functions * `c : composition n` is a structure, made of a list of integers which are all positive and add up to `n`. * `composition_card` states that the cardinality of `composition n` is exactly `2^(n-1)`, which is proved by constructing an equiv with `composition_as_set n` (see below), which is itself in bijection with the subsets of `fin (n-1)` (this holds even for `n = 0`, where `-` is nat subtraction). Let `c : composition n` be a composition of `n`. Then * `c.blocks` is the list of blocks in `c`. * `c.length` is the number of blocks in the composition. * `c.blocks_fun : fin c.length β†’ β„•` is the realization of `c.blocks` as a function on `fin c.length`. This is the main object when using compositions to understand the composition of analytic functions. * `c.size_up_to : β„• β†’ β„•` is the sum of the size of the blocks up to `i`.; * `c.embedding i : fin (c.blocks_fun i) β†’ fin n` is the increasing embedding of the `i`-th block in `fin n`; * `c.index j`, for `j : fin n`, is the index of the block containing `j`. * `composition.ones n` is the composition of `n` made of ones, i.e., `[1, ..., 1]`. * `composition.single n (hn : 0 < n)` is the composition of `n` made of a single block of size `n`. Compositions can also be used to split lists. Let `l` be a list of length `n` and `c` a composition of `n`. * `l.split_wrt_composition c` is a list of lists, made of the slices of `l` corresponding to the blocks of `c`. * `join_split_wrt_composition` states that splitting a list and then joining it gives back the original list. * `split_wrt_composition_join` states that joining a list of lists, and then splitting it back according to the right composition, gives back the original list of lists. We turn to the second viewpoint on compositions, that we realize as a finset of `fin (n+1)`. `c : composition_as_set n` is a structure made of a finset of `fin (n+1)` called `c.boundaries` and proofs that it contains `0` and `n`. (Taking a finset of `fin n` containing `0` would not make sense in the edge case `n = 0`, while the previous description works in all cases). The elements of this set (other than `n`) correspond to leftmost points of blocks. Thus, there is an equiv between `composition n` and `composition_as_set n`. We only construct basic API on `composition_as_set` (notably `c.length` and `c.blocks`) to be able to construct this equiv, called `composition_equiv n`. Since there is a straightforward equiv between `composition_as_set n` and finsets of `{1, ..., n-1}` (obtained by removing `0` and `n` from a `composition_as_set` and called `composition_as_set_equiv n`), we deduce that `composition_as_set n` and `composition n` are both fintypes of cardinality `2^(n - 1)` (see `composition_as_set_card` and `composition_card`). ## Implementation details The main motivation for this structure and its API is in the construction of the composition of formal multilinear series, and the proof that the composition of analytic functions is analytic. The representation of a composition as a list is very handy as lists are very flexible and already have a well-developed API. ## Tags Composition, partition ## References <https://en.wikipedia.org/wiki/Composition_(combinatorics)> -/ open list open_locale big_operators variable {n : β„•} /-- A composition of `n` is a list of positive integers summing to `n`. -/ @[ext] structure composition (n : β„•) := (blocks : list β„•) (blocks_pos : βˆ€ {i}, i ∈ blocks β†’ 0 < i) (blocks_sum : blocks.sum = n) /-- Combinatorial viewpoint on a composition of `n`, by seeing it as non-empty blocks of consecutive integers in `{0, ..., n-1}`. We register every block by its left end-point, yielding a finset containing `0`. As this does not make sense for `n = 0`, we add `n` to this finset, and get a finset of `{0, ..., n}` containing `0` and `n`. This is the data in the structure `composition_as_set n`. -/ @[ext] structure composition_as_set (n : β„•) := (boundaries : finset (fin n.succ)) (zero_mem : (0 : fin n.succ) ∈ boundaries) (last_mem : fin.last n ∈ boundaries) instance {n : β„•} : inhabited (composition_as_set n) := ⟨⟨finset.univ, finset.mem_univ _, finset.mem_univ _⟩⟩ /-! ### Compositions A composition of an integer `n` is a decomposition `n = iβ‚€ + ... + i_{k-1}` of `n` into a sum of positive integers. -/ namespace composition variables (c : composition n) instance (n : β„•) : has_to_string (composition n) := ⟨λ c, to_string c.blocks⟩ /-- The length of a composition, i.e., the number of blocks in the composition. -/ @[reducible] def length : β„• := c.blocks.length lemma blocks_length : c.blocks.length = c.length := rfl /-- The blocks of a composition, seen as a function on `fin c.length`. When composing analytic functions using compositions, this is the main player. -/ def blocks_fun : fin c.length β†’ β„• := Ξ» i, nth_le c.blocks i i.2 lemma of_fn_blocks_fun : of_fn c.blocks_fun = c.blocks := of_fn_nth_le _ lemma sum_blocks_fun : βˆ‘ i, c.blocks_fun i = n := by conv_rhs { rw [← c.blocks_sum, ← of_fn_blocks_fun, sum_of_fn] } lemma blocks_fun_mem_blocks (i : fin c.length) : c.blocks_fun i ∈ c.blocks := nth_le_mem _ _ _ @[simp] lemma one_le_blocks {i : β„•} (h : i ∈ c.blocks) : 1 ≀ i := c.blocks_pos h @[simp] lemma one_le_blocks' {i : β„•} (h : i < c.length) : 1 ≀ nth_le c.blocks i h:= c.one_le_blocks (nth_le_mem (blocks c) i h) @[simp] lemma blocks_pos' (i : β„•) (h : i < c.length) : 0 < nth_le c.blocks i h:= c.one_le_blocks' h lemma one_le_blocks_fun (i : fin c.length) : 1 ≀ c.blocks_fun i := c.one_le_blocks (c.blocks_fun_mem_blocks i) lemma length_le : c.length ≀ n := begin conv_rhs { rw ← c.blocks_sum }, exact length_le_sum_of_one_le _ (Ξ» i hi, c.one_le_blocks hi) end lemma length_pos_of_pos (h : 0 < n) : 0 < c.length := begin apply length_pos_of_sum_pos, convert h, exact c.blocks_sum end /-- The sum of the sizes of the blocks in a composition up to `i`. -/ def size_up_to (i : β„•) : β„• := (c.blocks.take i).sum @[simp] lemma size_up_to_zero : c.size_up_to 0 = 0 := by simp [size_up_to] lemma size_up_to_of_length_le (i : β„•) (h : c.length ≀ i) : c.size_up_to i = n := begin dsimp [size_up_to], convert c.blocks_sum, exact take_all_of_le h end @[simp] lemma size_up_to_length : c.size_up_to c.length = n := c.size_up_to_of_length_le c.length le_rfl lemma size_up_to_le (i : β„•) : c.size_up_to i ≀ n := begin conv_rhs { rw [← c.blocks_sum, ← sum_take_add_sum_drop _ i] }, exact nat.le_add_right _ _ end lemma size_up_to_succ {i : β„•} (h : i < c.length) : c.size_up_to (i+1) = c.size_up_to i + c.blocks.nth_le i h := by { simp only [size_up_to], rw sum_take_succ _ _ h } lemma size_up_to_succ' (i : fin c.length) : c.size_up_to ((i : β„•) + 1) = c.size_up_to i + c.blocks_fun i := c.size_up_to_succ i.2 lemma size_up_to_strict_mono {i : β„•} (h : i < c.length) : c.size_up_to i < c.size_up_to (i+1) := by { rw c.size_up_to_succ h, simp } lemma monotone_size_up_to : monotone c.size_up_to := monotone_sum_take _ /-- The `i`-th boundary of a composition, i.e., the leftmost point of the `i`-th block. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundary : fin (c.length + 1) β†ͺo fin (n+1) := order_embedding.of_strict_mono (Ξ» i, ⟨c.size_up_to i, nat.lt_succ_of_le (c.size_up_to_le i)⟩) $ fin.strict_mono_iff_lt_succ.2 $ Ξ» ⟨i, hi⟩, c.size_up_to_strict_mono hi @[simp] lemma boundary_zero : c.boundary 0 = 0 := by simp [boundary, fin.ext_iff] @[simp] lemma boundary_last : c.boundary (fin.last c.length) = fin.last n := by simp [boundary, fin.ext_iff] /-- The boundaries of a composition, i.e., the leftmost point of all the blocks. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundaries : finset (fin (n+1)) := finset.univ.map c.boundary.to_embedding lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := by simp [boundaries] /-- To `c : composition n`, one can associate a `composition_as_set n` by registering the leftmost point of each block, and adding a virtual point at the right of the last block. -/ def to_composition_as_set : composition_as_set n := { boundaries := c.boundaries, zero_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_map], exact ⟨0, rfl⟩, end, last_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_map], exact ⟨fin.last c.length, c.boundary_last⟩, end } /-- The canonical increasing bijection between `fin (c.length + 1)` and `c.boundaries` is exactly `c.boundary`. -/ lemma order_emb_of_fin_boundaries : c.boundaries.order_emb_of_fin c.card_boundaries_eq_succ_length = c.boundary := begin refine (finset.order_emb_of_fin_unique' _ _).symm, exact Ξ» i, (finset.mem_map' _).2 (finset.mem_univ _) end /-- Embedding the `i`-th block of a composition (identified with `fin (c.blocks_fun i)`) into `fin n` at the relevant position. -/ def embedding (i : fin c.length) : fin (c.blocks_fun i) β†ͺo fin n := (fin.nat_add $ c.size_up_to i).trans $ fin.cast_le $ calc c.size_up_to i + c.blocks_fun i = c.size_up_to (i + 1) : (c.size_up_to_succ _).symm ... ≀ c.size_up_to c.length : monotone_sum_take _ i.2 ... = n : c.size_up_to_length @[simp] lemma coe_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) : (c.embedding i j : β„•) = c.size_up_to i + j := rfl /-- `index_exists` asserts there is some `i` with `j < c.size_up_to (i+1)`. In the next definition `index` we use `nat.find` to produce the minimal such index. -/ lemma index_exists {j : β„•} (h : j < n) : βˆƒ i : β„•, j < c.size_up_to i.succ ∧ i < c.length := begin have n_pos : 0 < n := lt_of_le_of_lt (zero_le j) h, have : 0 < c.blocks.sum, by rwa [← c.blocks_sum] at n_pos, have length_pos : 0 < c.blocks.length := length_pos_of_sum_pos (blocks c) this, refine ⟨c.length.pred, _, nat.pred_lt (ne_of_gt length_pos)⟩, have : c.length.pred.succ = c.length := nat.succ_pred_eq_of_pos length_pos, simp [this, h] end /-- `c.index j` is the index of the block in the composition `c` containing `j`. -/ def index (j : fin n) : fin c.length := ⟨nat.find (c.index_exists j.2), (nat.find_spec (c.index_exists j.2)).2⟩ lemma lt_size_up_to_index_succ (j : fin n) : (j : β„•) < c.size_up_to (c.index j).succ := (nat.find_spec (c.index_exists j.2)).1 lemma size_up_to_index_le (j : fin n) : c.size_up_to (c.index j) ≀ j := begin by_contradiction H, set i := c.index j with hi, push_neg at H, have i_pos : (0 : β„•) < i, { by_contra' i_pos, revert H, simp [nonpos_iff_eq_zero.1 i_pos, c.size_up_to_zero] }, let i₁ := (i : β„•).pred, have i₁_lt_i : i₁ < i := nat.pred_lt (ne_of_gt i_pos), have i₁_succ : i₁.succ = i := nat.succ_pred_eq_of_pos i_pos, have := nat.find_min (c.index_exists j.2) i₁_lt_i, simp [lt_trans i₁_lt_i (c.index j).2, i₁_succ] at this, exact nat.lt_le_antisymm H this end /-- Mapping an element `j` of `fin n` to the element in the block containing it, identified with `fin (c.blocks_fun (c.index j))` through the canonical increasing bijection. -/ def inv_embedding (j : fin n) : fin (c.blocks_fun (c.index j)) := ⟨j - c.size_up_to (c.index j), begin rw [tsub_lt_iff_right, add_comm, ← size_up_to_succ'], { exact lt_size_up_to_index_succ _ _ }, { exact size_up_to_index_le _ _ } end⟩ @[simp] lemma coe_inv_embedding (j : fin n) : (c.inv_embedding j : β„•) = j - c.size_up_to (c.index j) := rfl lemma embedding_comp_inv (j : fin n) : c.embedding (c.index j) (c.inv_embedding j) = j := begin rw fin.ext_iff, apply add_tsub_cancel_of_le (c.size_up_to_index_le j), end lemma mem_range_embedding_iff {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ c.size_up_to i ≀ j ∧ (j : β„•) < c.size_up_to (i : β„•).succ := begin split, { assume h, rcases set.mem_range.2 h with ⟨k, hk⟩, rw fin.ext_iff at hk, change c.size_up_to i + k = (j : β„•) at hk, rw ← hk, simp [size_up_to_succ', k.is_lt] }, { assume h, apply set.mem_range.2, refine ⟨⟨j - c.size_up_to i, _⟩, _⟩, { rw [tsub_lt_iff_left, ← size_up_to_succ'], { exact h.2 }, { exact h.1 } }, { rw fin.ext_iff, exact add_tsub_cancel_of_le h.1 } } end /-- The embeddings of different blocks of a composition are disjoint. -/ lemma disjoint_range {i₁ iβ‚‚ : fin c.length} (h : i₁ β‰  iβ‚‚) : disjoint (set.range (c.embedding i₁)) (set.range (c.embedding iβ‚‚)) := begin classical, wlog h' : i₁ ≀ iβ‚‚ using i₁ iβ‚‚, swap, exact (this h.symm).symm, by_contradiction d, obtain ⟨x, hx₁, hxβ‚‚βŸ© : βˆƒ x : fin n, (x ∈ set.range (c.embedding i₁) ∧ x ∈ set.range (c.embedding iβ‚‚)) := set.not_disjoint_iff.1 d, have : i₁ < iβ‚‚ := lt_of_le_of_ne h' h, have A : (i₁ : β„•).succ ≀ iβ‚‚ := nat.succ_le_of_lt this, apply lt_irrefl (x : β„•), calc (x : β„•) < c.size_up_to (i₁ : β„•).succ : (c.mem_range_embedding_iff.1 hx₁).2 ... ≀ c.size_up_to (iβ‚‚ : β„•) : monotone_sum_take _ A ... ≀ x : (c.mem_range_embedding_iff.1 hxβ‚‚).1 end lemma mem_range_embedding (j : fin n) : j ∈ set.range (c.embedding (c.index j)) := begin have : c.embedding (c.index j) (c.inv_embedding j) ∈ set.range (c.embedding (c.index j)) := set.mem_range_self _, rwa c.embedding_comp_inv j at this end lemma mem_range_embedding_iff' {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ i = c.index j := begin split, { rw ← not_imp_not, assume h, exact set.disjoint_right.1 (c.disjoint_range h) (c.mem_range_embedding j) }, { assume h, rw h, exact c.mem_range_embedding j } end lemma index_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) : c.index (c.embedding i j) = i := begin symmetry, rw ← mem_range_embedding_iff', apply set.mem_range_self end lemma inv_embedding_comp (i : fin c.length) (j : fin (c.blocks_fun i)) : (c.inv_embedding (c.embedding i j) : β„•) = j := by simp_rw [coe_inv_embedding, index_embedding, coe_embedding, add_tsub_cancel_left] /-- Equivalence between the disjoint union of the blocks (each of them seen as `fin (c.blocks_fun i)`) with `fin n`. -/ def blocks_fin_equiv : (Ξ£ i : fin c.length, fin (c.blocks_fun i)) ≃ fin n := { to_fun := Ξ» x, c.embedding x.1 x.2, inv_fun := Ξ» j, ⟨c.index j, c.inv_embedding j⟩, left_inv := Ξ» x, begin rcases x with ⟨i, y⟩, dsimp, congr, { exact c.index_embedding _ _ }, rw fin.heq_ext_iff, { exact c.inv_embedding_comp _ _ }, { rw c.index_embedding } end, right_inv := Ξ» j, c.embedding_comp_inv j } lemma blocks_fun_congr {n₁ nβ‚‚ : β„•} (c₁ : composition n₁) (cβ‚‚ : composition nβ‚‚) (i₁ : fin c₁.length) (iβ‚‚ : fin cβ‚‚.length) (hn : n₁ = nβ‚‚) (hc : c₁.blocks = cβ‚‚.blocks) (hi : (i₁ : β„•) = iβ‚‚) : c₁.blocks_fun i₁ = cβ‚‚.blocks_fun iβ‚‚ := by { cases hn, rw ← composition.ext_iff at hc, cases hc, congr, rwa fin.ext_iff } /-- Two compositions (possibly of different integers) coincide if and only if they have the same sequence of blocks. -/ lemma sigma_eq_iff_blocks_eq {c : Ξ£ n, composition n} {c' : Ξ£ n, composition n} : c = c' ↔ c.2.blocks = c'.2.blocks := begin refine ⟨λ H, by rw H, Ξ» H, _⟩, rcases c with ⟨n, c⟩, rcases c' with ⟨n', c'⟩, have : n = n', by { rw [← c.blocks_sum, ← c'.blocks_sum, H] }, induction this, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext1, exact H end /-! ### The composition `composition.ones` -/ /-- The composition made of blocks all of size `1`. -/ def ones (n : β„•) : composition n := ⟨repeat (1 : β„•) n, Ξ» i hi, by simp [list.eq_of_mem_repeat hi], by simp⟩ instance {n : β„•} : inhabited (composition n) := ⟨composition.ones n⟩ @[simp] lemma ones_length (n : β„•) : (ones n).length = n := list.length_repeat 1 n @[simp] lemma ones_blocks (n : β„•) : (ones n).blocks = repeat (1 : β„•) n := rfl @[simp] lemma ones_blocks_fun (n : β„•) (i : fin (ones n).length) : (ones n).blocks_fun i = 1 := by simp [blocks_fun, ones, blocks, i.2] @[simp] lemma ones_size_up_to (n : β„•) (i : β„•) : (ones n).size_up_to i = min i n := by simp [size_up_to, ones_blocks, take_repeat] @[simp] lemma ones_embedding (i : fin (ones n).length) (h : 0 < (ones n).blocks_fun i) : (ones n).embedding i ⟨0, h⟩ = ⟨i, lt_of_lt_of_le i.2 (ones n).length_le⟩ := by { ext, simpa using i.2.le } lemma eq_ones_iff {c : composition n} : c = ones n ↔ βˆ€ i ∈ c.blocks, i = 1 := begin split, { rintro rfl, exact Ξ» i, eq_of_mem_repeat }, { assume H, ext1, have A : c.blocks = repeat 1 c.blocks.length := eq_repeat_of_mem H, have : c.blocks.length = n, by { conv_rhs { rw [← c.blocks_sum, A] }, simp }, rw [A, this, ones_blocks] }, end lemma ne_ones_iff {c : composition n} : c β‰  ones n ↔ βˆƒ i ∈ c.blocks, 1 < i := begin refine (not_congr eq_ones_iff).trans _, have : βˆ€ j ∈ c.blocks, j = 1 ↔ j ≀ 1 := Ξ» j hj, by simp [le_antisymm_iff, c.one_le_blocks hj], simp [this] {contextual := tt} end lemma eq_ones_iff_length {c : composition n} : c = ones n ↔ c.length = n := begin split, { rintro rfl, exact ones_length n }, { contrapose, assume H length_n, apply lt_irrefl n, calc n = βˆ‘ (i : fin c.length), 1 : by simp [length_n] ... < βˆ‘ (i : fin c.length), c.blocks_fun i : begin obtain ⟨i, hi, i_blocks⟩ : βˆƒ i ∈ c.blocks, 1 < i := ne_ones_iff.1 H, rw [← of_fn_blocks_fun, mem_of_fn c.blocks_fun, set.mem_range] at hi, obtain ⟨j : fin c.length, hj : c.blocks_fun j = i⟩ := hi, rw ← hj at i_blocks, exact finset.sum_lt_sum (Ξ» i hi, by simp [blocks_fun]) ⟨j, finset.mem_univ _, i_blocks⟩, end ... = n : c.sum_blocks_fun } end lemma eq_ones_iff_le_length {c : composition n} : c = ones n ↔ n ≀ c.length := by simp [eq_ones_iff_length, le_antisymm_iff, c.length_le] /-! ### The composition `composition.single` -/ /-- The composition made of a single block of size `n`. -/ def single (n : β„•) (h : 0 < n) : composition n := ⟨[n], by simp [h], by simp⟩ @[simp] lemma single_length {n : β„•} (h : 0 < n) : (single n h).length = 1 := rfl @[simp] lemma single_blocks {n : β„•} (h : 0 < n) : (single n h).blocks = [n] := rfl @[simp] lemma single_blocks_fun {n : β„•} (h : 0 < n) (i : fin (single n h).length) : (single n h).blocks_fun i = n := by simp [blocks_fun, single, blocks, i.2] @[simp] lemma single_embedding {n : β„•} (h : 0 < n) (i : fin n) : (single n h).embedding ⟨0, single_length h β–Έ zero_lt_one⟩ i = i := by { ext, simp } lemma eq_single_iff_length {n : β„•} (h : 0 < n) {c : composition n} : c = single n h ↔ c.length = 1 := begin split, { assume H, rw H, exact single_length h }, { assume H, ext1, have A : c.blocks.length = 1 := H β–Έ c.blocks_length, have B : c.blocks.sum = n := c.blocks_sum, rw eq_cons_of_length_one A at B ⊒, simpa [single_blocks] using B } end lemma ne_single_iff {n : β„•} (hn : 0 < n) {c : composition n} : c β‰  single n hn ↔ βˆ€ i, c.blocks_fun i < n := begin rw ← not_iff_not, push_neg, split, { rintros rfl, exact ⟨⟨0, by simp⟩, by simp⟩ }, { rintros ⟨i, hi⟩, rw eq_single_iff_length, have : βˆ€ j : fin c.length, j = i, { intros j, by_contradiction ji, apply lt_irrefl βˆ‘ k, c.blocks_fun k, calc βˆ‘ k, c.blocks_fun k ≀ c.blocks_fun i : by simp only [c.sum_blocks_fun, hi] ... < βˆ‘ k, c.blocks_fun k : finset.single_lt_sum ji (finset.mem_univ _) (finset.mem_univ _) (c.one_le_blocks_fun j) (Ξ» _ _ _, zero_le _) }, simpa using fintype.card_eq_one_of_forall_eq this } end end composition /-! ### Splitting a list Given a list of length `n` and a composition `c` of `n`, one can split `l` into `c.length` sublists of respective lengths `c.blocks_fun 0`, ..., `c.blocks_fun (c.length-1)`. This is inverse to the join operation. -/ namespace list variable {Ξ± : Type*} /-- Auxiliary for `list.split_wrt_composition`. -/ def split_wrt_composition_aux : list Ξ± β†’ list β„• β†’ list (list Ξ±) | l [] := [] | l (n :: ns) := let (l₁, lβ‚‚) := l.split_at n in l₁ :: split_wrt_composition_aux lβ‚‚ ns /-- Given a list of length `n` and a composition `[i₁, ..., iβ‚–]` of `n`, split `l` into a list of `k` lists corresponding to the blocks of the composition, of respective lengths `i₁`, ..., `iβ‚–`. This makes sense mostly when `n = l.length`, but this is not necessary for the definition. -/ def split_wrt_composition (l : list Ξ±) (c : composition n) : list (list Ξ±) := split_wrt_composition_aux l c.blocks local attribute [simp] split_wrt_composition_aux.equations._eqn_1 local attribute [simp] lemma split_wrt_composition_aux_cons (l : list Ξ±) (n ns) : l.split_wrt_composition_aux (n :: ns) = take n l :: (drop n l).split_wrt_composition_aux ns := by simp [split_wrt_composition_aux] lemma length_split_wrt_composition_aux (l : list Ξ±) (ns) : length (l.split_wrt_composition_aux ns) = ns.length := by induction ns generalizing l; simp * /-- When one splits a list along a composition `c`, the number of sublists thus created is `c.length`. -/ @[simp] lemma length_split_wrt_composition (l : list Ξ±) (c : composition n) : length (l.split_wrt_composition c) = c.length := length_split_wrt_composition_aux _ _ lemma map_length_split_wrt_composition_aux {ns : list β„•} : βˆ€ {l : list Ξ±}, ns.sum ≀ l.length β†’ map length (l.split_wrt_composition_aux ns) = ns := begin induction ns with n ns IH; intros l h; simp at h ⊒, have := le_trans (nat.le_add_right _ _) h, rw IH, {simp [this]}, rwa [length_drop, le_tsub_iff_left this] end /-- When one splits a list along a composition `c`, the lengths of the sublists thus created are given by the block sizes in `c`. -/ lemma map_length_split_wrt_composition (l : list Ξ±) (c : composition l.length) : map length (l.split_wrt_composition c) = c.blocks := map_length_split_wrt_composition_aux (le_of_eq c.blocks_sum) lemma length_pos_of_mem_split_wrt_composition {l l' : list Ξ±} {c : composition l.length} (h : l' ∈ l.split_wrt_composition c) : 0 < length l' := begin have : l'.length ∈ (l.split_wrt_composition c).map list.length := list.mem_map_of_mem list.length h, rw map_length_split_wrt_composition at this, exact c.blocks_pos this end lemma sum_take_map_length_split_wrt_composition (l : list Ξ±) (c : composition l.length) (i : β„•) : (((l.split_wrt_composition c).map length).take i).sum = c.size_up_to i := by { congr, exact map_length_split_wrt_composition l c } lemma nth_le_split_wrt_composition_aux (l : list Ξ±) (ns : list β„•) {i : β„•} (hi) : nth_le (l.split_wrt_composition_aux ns) i hi = (l.take (ns.take (i+1)).sum).drop (ns.take i).sum := begin induction ns with n ns IH generalizing l i, {cases hi}, cases i; simp [IH], rw [add_comm n, drop_add, drop_take], end /-- The `i`-th sublist in the splitting of a list `l` along a composition `c`, is the slice of `l` between the indices `c.size_up_to i` and `c.size_up_to (i+1)`, i.e., the indices in the `i`-th block of the composition. -/ lemma nth_le_split_wrt_composition (l : list Ξ±) (c : composition n) {i : β„•} (hi : i < (l.split_wrt_composition c).length) : nth_le (l.split_wrt_composition c) i hi = (l.take (c.size_up_to (i+1))).drop (c.size_up_to i) := nth_le_split_wrt_composition_aux _ _ _ theorem join_split_wrt_composition_aux {ns : list β„•} : βˆ€ {l : list Ξ±}, ns.sum = l.length β†’ (l.split_wrt_composition_aux ns).join = l := begin induction ns with n ns IH; intros l h; simp at h ⊒, { exact (length_eq_zero.1 h.symm).symm }, rw IH, {simp}, rwa [length_drop, ← h, add_tsub_cancel_left] end /-- If one splits a list along a composition, and then joins the sublists, one gets back the original list. -/ @[simp] theorem join_split_wrt_composition (l : list Ξ±) (c : composition l.length) : (l.split_wrt_composition c).join = l := join_split_wrt_composition_aux c.blocks_sum /-- If one joins a list of lists and then splits the join along the right composition, one gets back the original list of lists. -/ @[simp] theorem split_wrt_composition_join (L : list (list Ξ±)) (c : composition L.join.length) (h : map length L = c.blocks) : split_wrt_composition (join L) c = L := by simp only [eq_self_iff_true, and_self, eq_iff_join_eq, join_split_wrt_composition, map_length_split_wrt_composition, h] end list /-! ### Compositions as sets Combinatorial viewpoints on compositions, seen as finite subsets of `fin (n+1)` containing `0` and `n`, where the points of the set (other than `n`) correspond to the leftmost points of each block. -/ /-- Bijection between compositions of `n` and subsets of `{0, ..., n-2}`, defined by considering the restriction of the subset to `{1, ..., n-1}` and shifting to the left by one. -/ def composition_as_set_equiv (n : β„•) : composition_as_set n ≃ finset (fin (n - 1)) := { to_fun := Ξ» c, {i : fin (n-1) | (⟨1 + (i : β„•), begin apply (add_lt_add_left i.is_lt 1).trans_le, rw [nat.succ_eq_add_one, add_comm], exact add_le_add (nat.sub_le n 1) (le_refl 1) end ⟩ : fin n.succ) ∈ c.boundaries}.to_finset, inv_fun := Ξ» s, { boundaries := {i : fin n.succ | (i = 0) ∨ (i = fin.last n) ∨ (βˆƒ (j : fin (n-1)) (hj : j ∈ s), (i : β„•) = j + 1)}.to_finset, zero_mem := by simp, last_mem := by simp }, left_inv := begin assume c, ext i, simp only [exists_prop, add_comm, set.mem_to_finset, true_or, or_true, set.mem_set_of_eq], split, { rintro (rfl | rfl | ⟨j, hj1, hj2⟩), { exact c.zero_mem }, { exact c.last_mem }, { convert hj1, rwa fin.ext_iff } }, { simp only [or_iff_not_imp_left], assume i_mem i_ne_zero i_ne_last, simp [fin.ext_iff] at i_ne_zero i_ne_last, have A : (1 + (i-1) : β„•) = (i : β„•), by { rw add_comm, exact nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr i_ne_zero) }, refine ⟨⟨i - 1, _⟩, _, _⟩, { have : (i : β„•) < n + 1 := i.2, simp [nat.lt_succ_iff_lt_or_eq, i_ne_last] at this, exact nat.pred_lt_pred i_ne_zero this }, { convert i_mem, rw fin.ext_iff, simp only [fin.coe_mk, A] }, { simp [A] } }, end, right_inv := begin assume s, ext i, have : 1 + (i : β„•) β‰  n, { apply ne_of_lt, convert add_lt_add_left i.is_lt 1, rw add_comm, apply (nat.succ_pred_eq_of_pos _).symm, exact (zero_le i.val).trans_lt (i.2.trans_le (nat.sub_le n 1)) }, simp only [fin.ext_iff, exists_prop, fin.coe_zero, add_comm, set.mem_to_finset, set.mem_set_of_eq, fin.coe_last], erw [set.mem_set_of_eq], simp only [this, false_or, add_right_inj, add_eq_zero_iff, one_ne_zero, false_and, fin.coe_mk], split, { rintros ⟨j, js, hj⟩, convert js, exact (fin.ext_iff _ _).2 hj }, { assume h, exact ⟨i, h, rfl⟩ } end } instance composition_as_set_fintype (n : β„•) : fintype (composition_as_set n) := fintype.of_equiv _ (composition_as_set_equiv n).symm lemma composition_as_set_card (n : β„•) : fintype.card (composition_as_set n) = 2 ^ (n - 1) := begin have : fintype.card (finset (fin (n-1))) = 2 ^ (n - 1), by simp, rw ← this, exact fintype.card_congr (composition_as_set_equiv n) end namespace composition_as_set variables (c : composition_as_set n) lemma boundaries_nonempty : c.boundaries.nonempty := ⟨0, c.zero_mem⟩ lemma card_boundaries_pos : 0 < finset.card c.boundaries := finset.card_pos.mpr c.boundaries_nonempty /-- Number of blocks in a `composition_as_set`. -/ def length : β„• := finset.card c.boundaries - 1 lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := (tsub_eq_iff_eq_add_of_le (nat.succ_le_of_lt c.card_boundaries_pos)).mp rfl lemma length_lt_card_boundaries : c.length < c.boundaries.card := by { rw c.card_boundaries_eq_succ_length, exact lt_add_one _ } lemma lt_length (i : fin c.length) : (i : β„•) + 1 < c.boundaries.card := lt_tsub_iff_right.mp i.2 lemma lt_length' (i : fin c.length) : (i : β„•) < c.boundaries.card := lt_of_le_of_lt (nat.le_succ i) (c.lt_length i) /-- Canonical increasing bijection from `fin c.boundaries.card` to `c.boundaries`. -/ def boundary : fin c.boundaries.card β†ͺo fin (n + 1) := c.boundaries.order_emb_of_fin rfl @[simp] lemma boundary_zero : (c.boundary ⟨0, c.card_boundaries_pos⟩ : fin (n + 1)) = 0 := begin rw [boundary, finset.order_emb_of_fin_zero rfl c.card_boundaries_pos], exact le_antisymm (finset.min'_le _ _ c.zero_mem) (fin.zero_le _), end @[simp] lemma boundary_length : c.boundary ⟨c.length, c.length_lt_card_boundaries⟩ = fin.last n := begin convert finset.order_emb_of_fin_last rfl c.card_boundaries_pos, exact le_antisymm (finset.le_max' _ _ c.last_mem) (fin.le_last _) end /-- Size of the `i`-th block in a `composition_as_set`, seen as a function on `fin c.length`. -/ def blocks_fun (i : fin c.length) : β„• := (c.boundary ⟨(i : β„•) + 1, c.lt_length i⟩) - (c.boundary ⟨i, c.lt_length' i⟩) lemma blocks_fun_pos (i : fin c.length) : 0 < c.blocks_fun i := begin have : (⟨i, c.lt_length' i⟩ : fin c.boundaries.card) < ⟨i + 1, c.lt_length i⟩ := nat.lt_succ_self _, exact lt_tsub_iff_left.mpr ((c.boundaries.order_emb_of_fin rfl).strict_mono this) end /-- List of the sizes of the blocks in a `composition_as_set`. -/ def blocks (c : composition_as_set n) : list β„• := of_fn c.blocks_fun @[simp] lemma blocks_length : c.blocks.length = c.length := length_of_fn _ lemma blocks_partial_sum {i : β„•} (h : i < c.boundaries.card) : (c.blocks.take i).sum = c.boundary ⟨i, h⟩ := begin induction i with i IH, { simp }, have A : i < c.blocks.length, { rw c.card_boundaries_eq_succ_length at h, simp [blocks, nat.lt_of_succ_lt_succ h] }, have B : i < c.boundaries.card := lt_of_lt_of_le A (by simp [blocks, length, nat.sub_le]), rw [sum_take_succ _ _ A, IH B], simp only [blocks, blocks_fun, nth_le_of_fn'], apply add_tsub_cancel_of_le, simp end lemma mem_boundaries_iff_exists_blocks_sum_take_eq {j : fin (n+1)} : j ∈ c.boundaries ↔ βˆƒ i < c.boundaries.card, (c.blocks.take i).sum = j := begin split, { assume hj, rcases (c.boundaries.order_iso_of_fin rfl).surjective ⟨j, hj⟩ with ⟨i, hi⟩, rw [subtype.ext_iff, subtype.coe_mk] at hi, refine ⟨i.1, i.2, _⟩, rw [← hi, c.blocks_partial_sum i.2], refl }, { rintros ⟨i, hi, H⟩, convert (c.boundaries.order_iso_of_fin rfl ⟨i, hi⟩).2, have : c.boundary ⟨i, hi⟩ = j, by rwa [fin.ext_iff, ← c.blocks_partial_sum hi], exact this.symm } end lemma blocks_sum : c.blocks.sum = n := begin have : c.blocks.take c.length = c.blocks := take_all_of_le (by simp [blocks]), rw [← this, c.blocks_partial_sum c.length_lt_card_boundaries, c.boundary_length], refl end /-- Associating a `composition n` to a `composition_as_set n`, by registering the sizes of the blocks as a list of positive integers. -/ def to_composition : composition n := { blocks := c.blocks, blocks_pos := by simp only [blocks, forall_mem_of_fn_iff, blocks_fun_pos c, forall_true_iff], blocks_sum := c.blocks_sum } end composition_as_set /-! ### Equivalence between compositions and compositions as sets In this section, we explain how to go back and forth between a `composition` and a `composition_as_set`, by showing that their `blocks` and `length` and `boundaries` correspond to each other, and construct an equivalence between them called `composition_equiv`. -/ @[simp] lemma composition.to_composition_as_set_length (c : composition n) : c.to_composition_as_set.length = c.length := by simp [composition.to_composition_as_set, composition_as_set.length, c.card_boundaries_eq_succ_length] @[simp] lemma composition_as_set.to_composition_length (c : composition_as_set n) : c.to_composition.length = c.length := by simp [composition_as_set.to_composition, composition.length, composition.blocks] @[simp] lemma composition.to_composition_as_set_blocks (c : composition n) : c.to_composition_as_set.blocks = c.blocks := begin let d := c.to_composition_as_set, change d.blocks = c.blocks, have length_eq : d.blocks.length = c.blocks.length, { convert c.to_composition_as_set_length, simp [composition_as_set.blocks] }, suffices H : βˆ€ (i ≀ d.blocks.length), (d.blocks.take i).sum = (c.blocks.take i).sum, from eq_of_sum_take_eq length_eq H, assume i hi, have i_lt : i < d.boundaries.card, { convert nat.lt_succ_iff.2 hi, convert d.card_boundaries_eq_succ_length, exact length_of_fn _ }, have i_lt' : i < c.boundaries.card := i_lt, have i_lt'' : i < c.length + 1, by rwa c.card_boundaries_eq_succ_length at i_lt', have A : d.boundaries.order_emb_of_fin rfl ⟨i, i_lt⟩ = c.boundaries.order_emb_of_fin c.card_boundaries_eq_succ_length ⟨i, i_lt''⟩ := rfl, have B : c.size_up_to i = c.boundary ⟨i, i_lt''⟩ := rfl, rw [d.blocks_partial_sum i_lt, composition_as_set.boundary, ← composition.size_up_to, B, A, c.order_emb_of_fin_boundaries] end @[simp] lemma composition_as_set.to_composition_blocks (c : composition_as_set n) : c.to_composition.blocks = c.blocks := rfl @[simp] lemma composition_as_set.to_composition_boundaries (c : composition_as_set n) : c.to_composition.boundaries = c.boundaries := begin ext j, simp [c.mem_boundaries_iff_exists_blocks_sum_take_eq, c.card_boundaries_eq_succ_length, composition.boundary, fin.ext_iff, composition.size_up_to, exists_prop, finset.mem_univ, take, exists_prop_of_true, finset.mem_image, composition_as_set.to_composition_blocks, composition.boundaries], split, { rintros ⟨i, hi⟩, refine ⟨i.1, _, hi⟩, convert i.2, simp }, { rintros ⟨i, i_lt, hi⟩, have : i < c.to_composition.length + 1, by simpa using i_lt, exact ⟨⟨i, this⟩, hi⟩ } end @[simp] lemma composition.to_composition_as_set_boundaries (c : composition n) : c.to_composition_as_set.boundaries = c.boundaries := rfl /-- Equivalence between `composition n` and `composition_as_set n`. -/ def composition_equiv (n : β„•) : composition n ≃ composition_as_set n := { to_fun := Ξ» c, c.to_composition_as_set, inv_fun := Ξ» c, c.to_composition, left_inv := Ξ» c, by { ext1, exact c.to_composition_as_set_blocks }, right_inv := Ξ» c, by { ext1, exact c.to_composition_boundaries } } instance composition_fintype (n : β„•) : fintype (composition n) := fintype.of_equiv _ (composition_equiv n).symm lemma composition_card (n : β„•) : fintype.card (composition n) = 2 ^ (n - 1) := begin rw ← composition_as_set_card n, exact fintype.card_congr (composition_equiv n) end
323e91326da014b9e98034e58f58d2ef7fb1130a
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/logic/unique.lean
97e6f34fc99cef3a1c03e3f4a96dc5720f3ac11e
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
2,536
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ universes u v w variables {Ξ± : Sort u} {Ξ² : Sort v} {Ξ³ : Sort w} structure unique (Ξ± : Sort u) extends inhabited Ξ± := (uniq : βˆ€ a:Ξ±, a = default) attribute [class] unique instance punit.unique : unique punit.{u} := { default := punit.star, uniq := Ξ» x, punit_eq x _ } instance fin.unique : unique (fin 1) := { default := 0, uniq := Ξ» ⟨n, hn⟩, fin.eq_of_veq (nat.eq_zero_of_le_zero (nat.le_of_lt_succ hn)) } namespace unique open function section variables [unique Ξ±] @[priority 100] -- see Note [lower instance priority] instance : inhabited Ξ± := to_inhabited β€Ήunique Ξ±β€Ί lemma eq_default (a : Ξ±) : a = default Ξ± := uniq _ a lemma default_eq (a : Ξ±) : default Ξ± = a := (uniq _ a).symm @[priority 100] -- see Note [lower instance priority] instance : subsingleton Ξ± := ⟨λ a b, by rw [eq_default a, eq_default b]⟩ lemma forall_iff {p : Ξ± β†’ Prop} : (βˆ€ a, p a) ↔ p (default Ξ±) := ⟨λ h, h _, Ξ» h x, by rwa [unique.eq_default x]⟩ lemma exists_iff {p : Ξ± β†’ Prop} : Exists p ↔ p (default Ξ±) := ⟨λ ⟨a, ha⟩, eq_default a β–Έ ha, exists.intro (default Ξ±)⟩ end protected lemma subsingleton_unique' : βˆ€ (h₁ hβ‚‚ : unique Ξ±), h₁ = hβ‚‚ | ⟨⟨x⟩, h⟩ ⟨⟨y⟩, _⟩ := by congr; rw [h x, h y] instance subsingleton_unique : subsingleton (unique Ξ±) := ⟨unique.subsingleton_unique'⟩ end unique namespace function variable {f : Ξ± β†’ Ξ²} /-- If the domain of a surjective function is a singleton, then the codomain is a singleton as well. -/ def surjective.unique (hf : surjective f) [unique Ξ±] : unique Ξ² := { default := f (default _), uniq := Ξ» b, let ⟨a, ha⟩ := hf b in ha β–Έ congr_arg f (unique.eq_default _) } /-- If the codomain of an injective function is a subsingleton, then the domain is a subsingleton as well. -/ lemma injective.comap_subsingleton (hf : injective f) [subsingleton Ξ²] : subsingleton Ξ± := ⟨λ x y, hf $ subsingleton.elim _ _⟩ end function lemma nonempty_unique_or_exists_ne (x : Ξ±) : nonempty (unique Ξ±) ∨ βˆƒ y, y β‰  x := classical.by_cases or.inr (Ξ» h, or.inl ⟨{ default := x, uniq := Ξ» y, classical.by_contradiction $ Ξ» hy, h ⟨y, hy⟩ }⟩) lemma subsingleton_or_exists_ne (x : Ξ±) : subsingleton Ξ± ∨ βˆƒ y, y β‰  x := (nonempty_unique_or_exists_ne x).elim (Ξ» ⟨h⟩, or.inl $ @unique.subsingleton _ h) or.inr
af03578c1c95296aae5c8394c446e58669be8ecc
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/nat/parity.lean
d170297006cace5095da6c10c69baa02e6d80dd5
[ "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
3,358
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 natural numbers. -/ import .modeq algebra.group_power namespace nat @[simp] theorem mod_two_ne_one {n : nat} : Β¬ 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 : nat} : Β¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] def even (n : nat) : Prop := 2 ∣ n theorem even_iff {n : nat} : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], Ξ» h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ lemma not_even_iff {n : β„•} : Β¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] instance : decidable_pred even := Ξ» n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" @[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : Β¬ even 1 := by rw even_iff; apply one_ne_zero @[simp] theorem even_bit0 (n : nat) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add {m n : nat} : 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 : nat) : Β¬ even (bit1 n) := by simp [bit1] with parity_simps @[parity_simps] theorem even_sub {m n : nat} (h : n ≀ m) : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←nat.sub_add_cancel h, even_add] }, by_cases h : even n; simp [h] end @[parity_simps] theorem even_succ {n : nat} : even (succ n) ↔ Β¬ even n := by rw [succ_eq_add_one, even_add]; simp [not_even_one] @[parity_simps] theorem even_mul {m n : nat} : 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 n : nat} : even (m^n) ↔ even m ∧ n β‰  0 := by { induction n with n ih; simp [*, pow_succ, even_mul], tauto } lemma even_div {a b : β„•} : even (a / b) ↔ a % (2 * b) / b = 0 := by rw [even, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm] theorem neg_one_pow_eq_one_iff_even {Ξ± : Type*} [ring Ξ±] {n : β„•} (h1 : (-1 : Ξ±) β‰  1): (-1 : Ξ±) ^ n = 1 ↔ even n := ⟨λ h, n.mod_two_eq_zero_or_one.elim (dvd_iff_mod_eq_zero _ _).2 (Ξ» hn, by rw [neg_one_pow_eq_pow_mod_two, hn, _root_.pow_one] at h; exact (h1 h).elim), Ξ» ⟨m, hm⟩, by rw [neg_one_pow_eq_pow_mod_two, hm]; simp⟩ -- Here are examples of how `parity_simps` can be used with `nat`. example (m n : nat) (h : even m) : Β¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : Β¬ 2 = 0)] with parity_simps example : Β¬ even 25394535 := by simp end nat
1021cc95ea0b2fd0ed822e43696b4a73f7aa2859
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/sums/associator.lean
2d11f2272160185d35e2484558164e5dccad2bd4
[]
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,688
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.sums.basic import Mathlib.PostPort universes u v namespace Mathlib /-# The associator functor `((C βŠ• D) βŠ• E) β₯€ (C βŠ• (D βŠ• E))` and its inverse form an equivalence. -/ namespace category_theory.sum /-- The associator functor `(C βŠ• D) βŠ• E β₯€ C βŠ• (D βŠ• E)` for sums of categories. -/ def associator (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] : (C βŠ• D) βŠ• E β₯€ C βŠ• D βŠ• E := functor.mk (fun (X : (C βŠ• D) βŠ• E) => sorry) fun (X Y : (C βŠ• D) βŠ• E) (f : X ⟢ Y) => sorry @[simp] theorem associator_obj_inl_inl (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] (X : C) : functor.obj (associator C D E) (sum.inl (sum.inl X)) = sum.inl X := rfl @[simp] theorem associator_obj_inl_inr (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] (X : D) : functor.obj (associator C D E) (sum.inl (sum.inr X)) = sum.inr (sum.inl X) := rfl @[simp] theorem associator_obj_inr (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] (X : E) : functor.obj (associator C D E) (sum.inr X) = sum.inr (sum.inr X) := rfl @[simp] theorem associator_map_inl_inl (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] {X : C} {Y : C} (f : sum.inl (sum.inl X) ⟢ sum.inl (sum.inl Y)) : functor.map (associator C D E) f = f := rfl @[simp] theorem associator_map_inl_inr (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] {X : D} {Y : D} (f : sum.inl (sum.inr X) ⟢ sum.inl (sum.inr Y)) : functor.map (associator C D E) f = f := rfl @[simp] theorem associator_map_inr (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] {X : E} {Y : E} (f : sum.inr X ⟢ sum.inr Y) : functor.map (associator C D E) f = f := rfl /-- The inverse associator functor `C βŠ• (D βŠ• E) β₯€ (C βŠ• D) βŠ• E` for sums of categories. -/ def inverse_associator (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] : C βŠ• D βŠ• E β₯€ (C βŠ• D) βŠ• E := functor.mk (fun (X : C βŠ• D βŠ• E) => sorry) fun (X Y : C βŠ• D βŠ• E) (f : X ⟢ Y) => sorry @[simp] theorem inverse_associator_obj_inl (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] (X : C) : functor.obj (inverse_associator C D E) (sum.inl X) = sum.inl (sum.inl X) := rfl @[simp] theorem inverse_associator_obj_inr_inl (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] (X : D) : functor.obj (inverse_associator C D E) (sum.inr (sum.inl X)) = sum.inl (sum.inr X) := rfl @[simp] theorem inverse_associator_obj_inr_inr (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] (X : E) : functor.obj (inverse_associator C D E) (sum.inr (sum.inr X)) = sum.inr X := rfl @[simp] theorem inverse_associator_map_inl (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] {X : C} {Y : C} (f : sum.inl X ⟢ sum.inl Y) : functor.map (inverse_associator C D E) f = f := rfl @[simp] theorem inverse_associator_map_inr_inl (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] {X : D} {Y : D} (f : sum.inr (sum.inl X) ⟢ sum.inr (sum.inl Y)) : functor.map (inverse_associator C D E) f = f := rfl @[simp] theorem inverse_associator_map_inr_inr (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] {X : E} {Y : E} (f : sum.inr (sum.inr X) ⟢ sum.inr (sum.inr Y)) : functor.map (inverse_associator C D E) f = f := rfl /-- The equivalence of categories expressing associativity of sums of categories. -/ def associativity (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] : (C βŠ• D) βŠ• E β‰Œ C βŠ• D βŠ• E := equivalence.mk (associator C D E) (inverse_associator C D E) (nat_iso.of_components (fun (X : (C βŠ• D) βŠ• E) => eq_to_iso sorry) sorry) (nat_iso.of_components (fun (X : C βŠ• D βŠ• E) => eq_to_iso sorry) sorry) protected instance associator_is_equivalence (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] : is_equivalence (associator C D E) := is_equivalence.of_equivalence (associativity C D E) protected instance inverse_associator_is_equivalence (C : Type u) [category C] (D : Type u) [category D] (E : Type u) [category E] : is_equivalence (inverse_associator C D E) := is_equivalence.of_equivalence_inverse (associativity C D E)
b96d3961102439c747286b826bde0556c5d017c3
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/group/ulift.lean
de04426665198f33edeb04d6d5e91f090901d563
[ "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
6,170
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.int.cast.defs import algebra.hom.equiv /-! # `ulift` instances for groups and monoids This file defines instances for group, monoid, semigroup and related structures on `ulift` types. (Recall `ulift Ξ±` is just a "copy" of a type `Ξ±` in a higher universe.) We use `tactic.pi_instance_derive_field`, even though it wasn't intended for this purpose, which seems to work fine. We also provide `ulift.mul_equiv : ulift R ≃* R` (and its additive analogue). -/ universes u v variables {Ξ± : Type u} {x y : ulift.{v} Ξ±} namespace ulift @[to_additive] instance has_one [has_one Ξ±] : has_one (ulift Ξ±) := ⟨⟨1⟩⟩ @[simp, to_additive] lemma one_down [has_one Ξ±] : (1 : ulift Ξ±).down = 1 := rfl @[to_additive] instance has_mul [has_mul Ξ±] : has_mul (ulift Ξ±) := ⟨λ f g, ⟨f.down * g.down⟩⟩ @[simp, to_additive] lemma mul_down [has_mul Ξ±] : (x * y).down = x.down * y.down := rfl @[to_additive] instance has_div [has_div Ξ±] : has_div (ulift Ξ±) := ⟨λ f g, ⟨f.down / g.down⟩⟩ @[simp, to_additive] lemma div_down [has_div Ξ±] : (x / y).down = x.down / y.down := rfl @[to_additive] instance has_inv [has_inv Ξ±] : has_inv (ulift Ξ±) := ⟨λ f, ⟨f.down⁻¹⟩⟩ @[simp, to_additive] lemma inv_down [has_inv Ξ±] : x⁻¹.down = (x.down)⁻¹ := rfl /-- The multiplicative equivalence between `ulift Ξ±` and `Ξ±`. -/ @[to_additive "The additive equivalence between `ulift Ξ±` and `Ξ±`."] def _root_.mul_equiv.ulift [has_mul Ξ±] : ulift Ξ± ≃* Ξ± := { map_mul' := Ξ» x y, rfl, .. equiv.ulift } @[to_additive] instance semigroup [semigroup Ξ±] : semigroup (ulift Ξ±) := mul_equiv.ulift.injective.semigroup _ $ Ξ» x y, rfl @[to_additive] instance comm_semigroup [comm_semigroup Ξ±] : comm_semigroup (ulift Ξ±) := equiv.ulift.injective.comm_semigroup _ $ Ξ» x y, rfl @[to_additive] instance mul_one_class [mul_one_class Ξ±] : mul_one_class (ulift Ξ±) := equiv.ulift.injective.mul_one_class _ rfl $ Ξ» x y, rfl instance mul_zero_one_class [mul_zero_one_class Ξ±] : mul_zero_one_class (ulift Ξ±) := equiv.ulift.injective.mul_zero_one_class _ rfl rfl $ Ξ» x y, rfl @[to_additive] instance has_smul {Ξ² : Type*} [has_smul Ξ± Ξ²] : has_smul Ξ± (ulift Ξ²) := ⟨λ n x, up (n β€’ x.down)⟩ @[to_additive has_smul, to_additive_reorder 1] instance has_pow {Ξ² : Type*} [has_pow Ξ± Ξ²] : has_pow (ulift Ξ±) Ξ² := ⟨λ x n, up (x.down ^ n)⟩ @[to_additive] instance monoid [monoid Ξ±] : monoid (ulift Ξ±) := equiv.ulift.injective.monoid _ rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance add_monoid_with_one [add_monoid_with_one Ξ±] : add_monoid_with_one (ulift Ξ±) := { nat_cast := Ξ» n, ⟨n⟩, nat_cast_zero := congr_arg ulift.up nat.cast_zero, nat_cast_succ := Ξ» n, congr_arg ulift.up (nat.cast_succ _), .. ulift.has_one, .. ulift.add_monoid } @[to_additive] instance comm_monoid [comm_monoid Ξ±] : comm_monoid (ulift Ξ±) := equiv.ulift.injective.comm_monoid _ rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance monoid_with_zero [monoid_with_zero Ξ±] : monoid_with_zero (ulift Ξ±) := equiv.ulift.injective.monoid_with_zero _ rfl rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance comm_monoid_with_zero [comm_monoid_with_zero Ξ±] : comm_monoid_with_zero (ulift Ξ±) := equiv.ulift.injective.comm_monoid_with_zero _ rfl rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) @[to_additive] instance div_inv_monoid [div_inv_monoid Ξ±] : div_inv_monoid (ulift Ξ±) := equiv.ulift.injective.div_inv_monoid _ rfl (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) @[to_additive] instance group [group Ξ±] : group (ulift Ξ±) := equiv.ulift.injective.group _ rfl (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance add_group_with_one [add_group_with_one Ξ±] : add_group_with_one (ulift Ξ±) := { int_cast := Ξ» n, ⟨n⟩, int_cast_of_nat := Ξ» n, congr_arg ulift.up (int.cast_of_nat _), int_cast_neg_succ_of_nat := Ξ» n, congr_arg ulift.up (int.cast_neg_succ_of_nat _), .. ulift.add_monoid_with_one, .. ulift.add_group } @[to_additive] instance comm_group [comm_group Ξ±] : comm_group (ulift Ξ±) := equiv.ulift.injective.comm_group _ rfl (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance group_with_zero [group_with_zero Ξ±] : group_with_zero (ulift Ξ±) := equiv.ulift.injective.group_with_zero _ rfl rfl (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance comm_group_with_zero [comm_group_with_zero Ξ±] : comm_group_with_zero (ulift Ξ±) := equiv.ulift.injective.comm_group_with_zero _ rfl rfl (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [left_cancel_semigroup Ξ±] : left_cancel_semigroup (ulift Ξ±) := equiv.ulift.injective.left_cancel_semigroup _ (Ξ» _ _, rfl) @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [right_cancel_semigroup Ξ±] : right_cancel_semigroup (ulift Ξ±) := equiv.ulift.injective.right_cancel_semigroup _ (Ξ» _ _, rfl) @[to_additive add_left_cancel_monoid] instance left_cancel_monoid [left_cancel_monoid Ξ±] : left_cancel_monoid (ulift Ξ±) := equiv.ulift.injective.left_cancel_monoid _ rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) @[to_additive add_right_cancel_monoid] instance right_cancel_monoid [right_cancel_monoid Ξ±] : right_cancel_monoid (ulift Ξ±) := equiv.ulift.injective.right_cancel_monoid _ rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) @[to_additive add_cancel_monoid] instance cancel_monoid [cancel_monoid Ξ±] : cancel_monoid (ulift Ξ±) := equiv.ulift.injective.cancel_monoid _ rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) @[to_additive add_cancel_monoid] instance cancel_comm_monoid [cancel_comm_monoid Ξ±] : cancel_comm_monoid (ulift Ξ±) := equiv.ulift.injective.cancel_comm_monoid _ rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance nontrivial [nontrivial Ξ±] : nontrivial (ulift Ξ±) := equiv.ulift.symm.injective.nontrivial -- TODO we don't do `ordered_cancel_comm_monoid` or `ordered_comm_group` -- We'd need to add instances for `ulift` in `order.basic`. end ulift
f8bcbcc04eb0eb9ca2f17c6edfd3b88fca921e65
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast6.lean
c545005343ad1b97f39768de1dce24fd74524e6a
[ "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
220
lean
set_option blast.strategy "preprocess" lemma lemma1 (bv : nat β†’ Type) (n m : nat) (H : n = m) (b1 : bv n) (b2 : bv m) (H2 : eq.rec_on H b1 = b2) : b1 = eq.rec_on (eq.symm H) b2 := by blast reveal lemma1 print lemma1
3dab79e73bf9a6b9267f0639e99d0348a37cc009
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/def4.lean
a7f1bed40f7dc017a1e9e94e82fc2fe31bd10951
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
410
lean
inductive Foo : Bool β†’ Type | Z : Foo false | O : Foo false β†’ Foo true | E : Foo true β†’ Foo false open Foo def toNat : {b : Bool} β†’ Foo b β†’ Nat | _, Z => 0 | _, O n => toNat n + 1 | _, E n => toNat n + 1 example : toNat (E (O Z)) = 2 := rfl example : toNat Z = 0 := rfl example (a : Foo false) : toNat (O a) = toNat a + 1 := rfl example (a : Foo true) : toNat (E a) = toNat a + 1 := rfl
ea1de4aa6d51be0cfe392151cf782482b2281bd4
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/trace.lean
ff569475b5e2b6ff32ce16b919c2a05f07df7c23
[ "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
1,376
lean
import Lean.CoreM open Lean structure MyState := (traceState : TraceState := {}) (s : Nat := 0) abbrev M := CoreM def tst1 : M Unit := do trace! `module ("hello" ++ MessageData.nest 9 (Format.line ++ "world")); trace! `module.aux "another message"; pure () def tst2 (b : Bool) : M Unit := traceCtx `module $ do tst1; trace! `bughunt "at test2"; when b $ throwError "error"; tst1; pure () partial def ack : Nat β†’ Nat β†’ Nat | 0, n => n+1 | m+1, 0 => ack m 1 | m+1, n+1 => ack m (ack (m+1) n) def slow (b : Bool) : Nat := ack 4 (cond b 0 1) def tst3 (b : Bool) : M Unit := do traceCtx `module $ do { tst2 b; tst1 }; trace! `bughunt "at end of tst3"; -- Messages are computed lazily. The following message will only be computed -- if `trace.slow is active. trace! `slow ("slow message: " ++ toString (slow b)) def run (x : M Unit) : M Unit := withReader (fun ctx => -- Try commeting/uncommeting the following `setBool`s let opts := ctx.options; let opts := opts.setBool `trace.module true; -- let opts := opts.setBool `trace.module.aux false; let opts := opts.setBool `trace.bughunt true; -- let opts := opts.setBool `trace.slow true; { ctx with options := opts }) (tryCatch (tryFinally x printTraces) (fun _ => IO.println "ERROR")) #eval run (tst3 true) #eval run (tst3 false)
0e938c6383f2ab077d54f6f18e7cfe46d126f4d7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/partialApp.lean
2dca230158e1d31a4edc306977b25088ce562f84
[ "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
922
lean
def f (x : Nat) (y : Nat := 1) (w : Nat := 2) (z : Nat) := x + y + w - z theorem ex1 (x z : Nat) : f (z := z) x = x + 1 + 2 - z := rfl theorem ex2 (x z : Nat) : f x (z := z) = x + 1 + 2 - z := rfl theorem ex3 (x y : Nat) : f x y = fun z => x + y + 2 - z := rfl theorem ex4 : f = (fun x z => x + 1 + 2 - z) := rfl theorem ex5 (x : Nat) : f x = fun z => x + 1 + 2 - z := rfl theorem ex6 (y : Nat) : f (y := 5) = fun x z => x + 5 + 2 - z := rfl def g {Ξ±} [Add Ξ±] (a : Ξ±) (b? : Option Ξ± := none) (c : Ξ±) : Ξ± := match b? with | none => a + c | some b => a + b + c variable {Ξ±} [Add Ξ±] theorem ex7 : g = fun (a c : Ξ±) => a + c := rfl theorem ex8 (x : Ξ±) : g (c := x) = fun (a : Ξ±) => a + x := rfl theorem ex9 (x : Ξ±) : g (b? := some x) = fun (a c : Ξ±) => a + x + c := rfl theorem ex10 (x : Ξ±) : g x = fun (c : Ξ±) => x + c := rfl theorem ex11 (x y : Ξ±) : g x y = fun (c : Ξ±) => x + y + c := rfl
937c25ba590aa25d8c8786925a45a59a8482a891
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/affine_space/barycentric_coords.lean
bde394de87eea3c527772b7eade0a28721b276fd
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,284
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import linear_algebra.affine_space.independent /-! # Barycentric coordinates Suppose `P` is an affine space modelled on the module `V` over the ring `k`, and `p : ΞΉ β†’ P` is an affine-independent family of points spanning `P`. Given this data, each point `q : P` may be written uniquely as an affine combination: `q = wβ‚€ pβ‚€ + w₁ p₁ + β‹―` for some (finitely-supported) weights `wα΅’`. For each `i : ΞΉ`, we thus have an affine map `P →ᡃ[k] k`, namely `q ↦ wα΅’`. This family of maps is known as the family of barycentric coordinates. It is defined in this file. ## The construction Fixing `i : ΞΉ`, and allowing `j : ΞΉ` to range over the values `j β‰  i`, we obtain a basis `bα΅’` of `V` defined by `bα΅’ j = p j -α΅₯ p i`. Let `fα΅’ j : V β†’β‚—[k] k` be the corresponding dual basis and let `fα΅’ = βˆ‘ j, fα΅’ j : V β†’β‚—[k] k` be the corresponding "sum of all coordinates" form. Then the `i`th barycentric coordinate of `q : P` is `1 - fα΅’ (q -α΅₯ p i)`. ## Main definitions * `barycentric_coord`: the map `P →ᡃ[k] k` corresponding to `i : ΞΉ`. * `barycentric_coord_apply_eq`: the behaviour of `barycentric_coord i` on `p i`. * `barycentric_coord_apply_neq`: the behaviour of `barycentric_coord i` on `p j` when `j β‰  i`. * `barycentric_coord_apply`: the behaviour of `barycentric_coord i` on `p j` for general `j`. * `barycentric_coord_apply_combination`: the characterisation of `barycentric_coord i` in terms of affine combinations, i.e., `barycentric_coord i (wβ‚€ pβ‚€ + w₁ p₁ + β‹―) = wα΅’`. ## TODO * Construct the affine equivalence between `P` and `{ f : ΞΉ β†’β‚€ k | f.sum = 1 }`. -/ open_locale affine big_operators open set universes u₁ uβ‚‚ u₃ uβ‚„ variables {ΞΉ : Type u₁} {k : Type uβ‚‚} {V : Type u₃} {P : Type uβ‚„} variables [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {p : ΞΉ β†’ P} (h_ind : affine_independent k p) (h_tot : affine_span k (range p) = ⊀) include V h_ind h_tot /-- Given an affine-independent family of points spanning the point space `P`, if we single out one member of the family, we obtain a basis for the model space `V`. The basis correpsonding to the singled-out member `i : ΞΉ` is indexed by `{j : ΞΉ // j β‰  i}` and its `j`th element is `p j -α΅₯ p i`. (See `basis_of_aff_ind_span_eq_top_apply`.) -/ noncomputable def basis_of_aff_ind_span_eq_top (i : ΞΉ) : basis {j : ΞΉ // j β‰  i} k V := basis.mk ((affine_independent_iff_linear_independent_vsub k p i).mp h_ind) begin suffices : submodule.span k (range (Ξ» (j : {x // x β‰  i}), p ↑j -α΅₯ p i)) = vector_span k (range p), { rw [this, ← direction_affine_span, h_tot, affine_subspace.direction_top], }, conv_rhs { rw ← image_univ, }, rw vector_span_image_eq_span_vsub_set_right_ne k p (mem_univ i), congr, ext v, simp, end local notation `basis_of` := basis_of_aff_ind_span_eq_top h_ind h_tot @[simp] lemma basis_of_aff_ind_span_eq_top_apply (i : ΞΉ) (j : {j : ΞΉ // j β‰  i}) : basis_of i j = p ↑j -α΅₯ p i := by simp [basis_of_aff_ind_span_eq_top] /-- The `i`th barycentric coordinate of a point. -/ noncomputable def barycentric_coord (i : ΞΉ) : P →ᡃ[k] k := { to_fun := Ξ» q, 1 - (basis_of i).sum_coords (q -α΅₯ p i), linear := -(basis_of i).sum_coords, map_vadd' := Ξ» q v, by rw [vadd_vsub_assoc, linear_map.map_add, vadd_eq_add, linear_map.neg_apply, sub_add_eq_sub_sub_swap, add_comm, sub_eq_add_neg], } @[simp] lemma barycentric_coord_apply_eq (i : ΞΉ) : barycentric_coord h_ind h_tot i (p i) = 1 := by simp only [barycentric_coord, basis.coe_sum_coords, linear_equiv.map_zero, linear_equiv.coe_coe, sub_zero, affine_map.coe_mk, finsupp.sum_zero_index, vsub_self] @[simp] lemma barycentric_coord_apply_neq (i j : ΞΉ) (h : j β‰  i) : barycentric_coord h_ind h_tot i (p j) = 0 := by rw [barycentric_coord, affine_map.coe_mk, ← subtype.coe_mk j h, ← basis_of_aff_ind_span_eq_top_apply h_ind h_tot i ⟨j, h⟩, basis.sum_coords_self_apply, sub_self] lemma barycentric_coord_apply [decidable_eq ΞΉ] (i j : ΞΉ) : barycentric_coord h_ind h_tot i (p j) = if i = j then 1 else 0 := by { cases eq_or_ne i j; simp [h.symm], simp [h], } @[simp] lemma barycentric_coord_apply_combination_of_mem {s : finset ΞΉ} {i : ΞΉ} (hi : i ∈ s) {w : ΞΉ β†’ k} (hw : s.sum w = 1) : barycentric_coord h_ind h_tot i (s.affine_combination p w) = w i := begin classical, simp only [barycentric_coord_apply, hi, finset.affine_combination_eq_linear_combination, if_true, hw, mul_boole, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination p w hw], end @[simp] lemma barycentric_coord_apply_combination_of_not_mem {s : finset ΞΉ} {i : ΞΉ} (hi : i βˆ‰ s) {w : ΞΉ β†’ k} (hw : s.sum w = 1) : barycentric_coord h_ind h_tot i (s.affine_combination p w) = 0 := begin classical, simp only [barycentric_coord_apply, hi, finset.affine_combination_eq_linear_combination, if_false, hw, mul_boole, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination p w hw], end @[simp] lemma sum_barycentric_coord_apply_eq_one [fintype ΞΉ] (q : P) : βˆ‘ i, barycentric_coord h_ind h_tot i q = 1 := begin have hq : q ∈ affine_span k (range p), { rw h_tot, exact affine_subspace.mem_top k V q, }, obtain ⟨w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span_of_fintype hq, convert hw, ext i, exact barycentric_coord_apply_combination_of_mem h_ind h_tot (finset.mem_univ i) hw, end @[simp] lemma affine_combination_barycentric_coord_eq_self [fintype ΞΉ] (q : P) : finset.univ.affine_combination p (Ξ» i, barycentric_coord h_ind h_tot i q) = q := begin have hq : q ∈ affine_span k (range p), { rw h_tot, exact affine_subspace.mem_top k V q, }, obtain ⟨w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span_of_fintype hq, congr, ext i, exact barycentric_coord_apply_combination_of_mem h_ind h_tot (finset.mem_univ i) hw, end @[simp] lemma coe_barycentric_coord_of_subsingleton_eq_one [subsingleton ΞΉ] (i : ΞΉ) : (barycentric_coord h_ind h_tot i : P β†’ k) = 1 := begin ext q, have hp : (range p).subsingleton, { rw ← image_univ, apply subsingleton.image, apply subsingleton_of_subsingleton, }, haveI := affine_subspace.subsingleton_of_subsingleton_span_eq_top hp h_tot, let s : finset ΞΉ := {i}, have hi : i ∈ s, { simp, }, have hw : s.sum (function.const ΞΉ (1 : k)) = 1, { simp, }, have hq : q = s.affine_combination p (function.const ΞΉ (1 : k)), { simp, }, rw [pi.one_apply, hq, barycentric_coord_apply_combination_of_mem h_ind h_tot hi hw], end lemma surjective_barycentric_coord [nontrivial ΞΉ] (i : ΞΉ) : function.surjective $ barycentric_coord h_ind h_tot i := begin classical, intros x, obtain ⟨j, hij⟩ := exists_ne i, let s : finset ΞΉ := {i, j}, have hi : i ∈ s, { simp, }, have hj : j ∈ s, { simp, }, let w : ΞΉ β†’ k := Ξ» j', if j' = i then x else 1-x, have hw : s.sum w = 1, { simp [hij, finset.sum_ite, finset.filter_insert, finset.filter_eq'], }, use s.affine_combination p w, simp [barycentric_coord_apply_combination_of_mem h_ind h_tot hi hw], end
5e5b1dcd11b8ee72faec4ed2e7ed2170faddeff7
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebra/ordered_group.lean
200e0431e16f7fede6a2eaf58875500220c8cadb
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
30,319
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes HΓΆlzl -/ import algebra.ordered_monoid set_option old_structure_cmd true /-! # Ordered groups This file develops the basics of ordered groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ universe u variable {Ξ± : Type u} /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (Ξ± : Type u) extends add_comm_group Ξ±, partial_order Ξ± := (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (Ξ± : Type u) extends comm_group Ξ±, partial_order Ξ± := (mul_le_mul_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c * a ≀ c * b) attribute [to_additive] ordered_comm_group /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid Ξ±] : ordered_comm_group (units Ξ±) := { mul_le_mul_left := Ξ» a b h c, mul_le_mul_left' h _, .. units.partial_order, .. (infer_instance : comm_group (units Ξ±)) } section ordered_comm_group variables [ordered_comm_group Ξ±] {a b c d : Ξ±} @[to_additive ordered_add_comm_group.add_lt_add_left] lemma ordered_comm_group.mul_lt_mul_left' (a b : Ξ±) (h : a < b) (c : Ξ±) : c * a < c * b := begin rw lt_iff_le_not_le at h ⊒, split, { apply ordered_comm_group.mul_le_mul_left _ _ h.1 }, { intro w, replace w : c⁻¹ * (c * b) ≀ c⁻¹ * (c * a) := ordered_comm_group.mul_le_mul_left _ _ w _, simp only [mul_one, mul_comm, mul_left_inv, mul_left_comm] at w, exact h.2 w }, end @[to_additive ordered_add_comm_group.le_of_add_le_add_left] lemma ordered_comm_group.le_of_mul_le_mul_left (h : a * b ≀ a * c) : b ≀ c := have a⁻¹ * (a * b) ≀ a⁻¹ * (a * c), from ordered_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] lemma ordered_comm_group.lt_of_mul_lt_mul_left (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_comm_group.mul_lt_mul_left' _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_comm_group.to_ordered_cancel_comm_monoid (Ξ± : Type u) [s : ordered_comm_group Ξ±] : ordered_cancel_comm_monoid Ξ± := { mul_left_cancel := @mul_left_cancel Ξ± _, mul_right_cancel := @mul_right_cancel Ξ± _, le_of_mul_le_mul_left := @ordered_comm_group.le_of_mul_le_mul_left Ξ± _, ..s } @[to_additive neg_le_neg] lemma inv_le_inv' (h : a ≀ b) : b⁻¹ ≀ a⁻¹ := have 1 ≀ a⁻¹ * b, from mul_left_inv a β–Έ mul_le_mul_left' h _, have 1 * b⁻¹ ≀ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _, by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma le_of_inv_le_inv (h : b⁻¹ ≀ a⁻¹) : a ≀ b := suffices (a⁻¹)⁻¹ ≀ (b⁻¹)⁻¹, from begin simp [inv_inv] at this, assumption end, inv_le_inv' h @[to_additive] lemma one_le_of_inv_le_one (h : a⁻¹ ≀ 1) : 1 ≀ a := have a⁻¹ ≀ 1⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive] lemma inv_le_one_of_one_le (h : 1 ≀ a) : a⁻¹ ≀ 1 := have a⁻¹ ≀ 1⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive nonpos_of_neg_nonneg] lemma le_one_of_one_le_inv (h : 1 ≀ a⁻¹) : a ≀ 1 := have 1⁻¹ ≀ a⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one (h : a ≀ 1) : 1 ≀ a⁻¹ := have 1⁻¹ ≀ a⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive neg_lt_neg] lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := have 1 < a⁻¹ * b, from mul_left_inv a β–Έ mul_lt_mul_left' h (a⁻¹), have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹), by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b := inv_inv a β–Έ inv_inv b β–Έ inv_lt_inv' h @[to_additive] lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a := have a⁻¹ < 1⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive] lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 := have a⁻¹ < 1⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive neg_of_neg_pos] lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 := have 1⁻¹ < a⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive neg_pos_of_neg] lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ := have 1⁻¹ < a⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive] lemma le_inv_of_le_inv (h : a ≀ b⁻¹) : b ≀ a⁻¹ := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_le_of_inv_le (h : a⁻¹ ≀ b) : b⁻¹ ≀ a := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma mul_le_of_le_inv_mul (h : b ≀ a⁻¹ * c) : a * b ≀ c := begin have h := mul_le_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma le_inv_mul_of_mul_le (h : a * b ≀ c) : b ≀ a⁻¹ * c := begin have h := mul_le_mul_left' h a⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≀ c) : a ≀ b * c := begin have h := mul_le_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_le_of_le_mul (h : a ≀ b * c) : b⁻¹ * a ≀ c := begin have h := mul_le_mul_left' h b⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≀ c) : a ≀ b * c := le_mul_of_inv_mul_le h @[to_additive] lemma inv_mul_le_left_of_le_mul (h : a ≀ b * c) : b⁻¹ * a ≀ c := inv_mul_le_of_le_mul h @[to_additive] lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≀ b) : a ≀ b * c := by { rw mul_comm, exact le_mul_of_inv_mul_le h } @[to_additive] lemma inv_mul_le_right_of_le_mul (h : a ≀ b * c) : c⁻¹ * a ≀ b := by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h } @[to_additive] lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c := begin have h := mul_lt_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c := begin have h := mul_lt_mul_left' h (a⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c := begin have h := mul_lt_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := begin have h := mul_lt_mul_left' h (b⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c := lt_mul_of_inv_mul_lt h @[to_additive] lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := inv_mul_lt_of_lt_mul h @[to_additive] lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c := by { rw mul_comm, exact lt_mul_of_inv_mul_lt h } @[to_additive] lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b := by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h } @[simp, to_additive] lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a := ⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩ @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≀ b⁻¹ ↔ b ≀ a := have a * b * a⁻¹ ≀ a * b * b⁻¹ ↔ a⁻¹ ≀ b⁻¹, from mul_le_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_le] lemma inv_le' : a⁻¹ ≀ b ↔ b⁻¹ ≀ a := have a⁻¹ ≀ (b⁻¹)⁻¹ ↔ b⁻¹ ≀ a, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive le_neg] lemma le_inv' : a ≀ b⁻¹ ↔ b ≀ a⁻¹ := have (a⁻¹)⁻¹ ≀ b⁻¹ ↔ b ≀ a⁻¹, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≀ b ↔ 1 ≀ b * a := (mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive neg_le_iff_add_nonneg'] lemma inv_le_iff_one_le_mul' : a⁻¹ ≀ b ↔ 1 ≀ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive neg_lt_iff_add_nonneg] lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a := (mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive neg_lt_iff_add_nonneg'] lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b := (mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one : a ≀ b⁻¹ ↔ a * b ≀ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[to_additive] lemma le_inv_iff_mul_le_one' : a ≀ b⁻¹ ↔ b * a ≀ 1 := (mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self @[to_additive] lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 := (mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self @[simp, to_additive neg_nonpos] lemma inv_le_one' : a⁻¹ ≀ 1 ↔ 1 ≀ a := have a⁻¹ ≀ 1⁻¹ ↔ 1 ≀ a, from inv_le_inv_iff, by rwa one_inv at this @[simp, to_additive neg_nonneg] lemma one_le_inv' : 1 ≀ a⁻¹ ↔ a ≀ 1 := have 1⁻¹ ≀ a⁻¹ ↔ a ≀ 1, from inv_le_inv_iff, by rwa one_inv at this @[to_additive] lemma inv_le_self (h : 1 ≀ a) : a⁻¹ ≀ a := le_trans (inv_le_one'.2 h) h @[to_additive] lemma self_le_inv (h : a ≀ 1) : a ≀ a⁻¹ := le_trans h (one_le_inv'.2 h) @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_lt_zero] lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a := have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_pos] lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 := have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive] lemma inv_lt_self (h : 1 < a) : a⁻¹ < a := (inv_lt_one'.2 h).trans h @[to_additive] lemma le_inv_mul_iff_mul_le : b ≀ a⁻¹ * c ↔ a * b ≀ c := have a⁻¹ * (a * b) ≀ a⁻¹ * c ↔ a * b ≀ c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≀ c ↔ a ≀ b * c := have b⁻¹ * a ≀ b⁻¹ * (b * c) ↔ a ≀ b * c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≀ b ↔ a ≀ b * c := by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≀ c ↔ a ≀ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≀ b ↔ a ≀ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive add_neg_le_add_neg_iff] lemma div_le_div_iff' : a * b⁻¹ ≀ c * d⁻¹ ↔ a * d ≀ c * b := begin split ; intro h, have := mul_le_mul_right' (mul_le_mul_right' h b) d, rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right] at this, have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹, rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc, mul_inv_cancel_right] at this, end end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group Ξ±] {a b c d : Ξ±} lemma sub_le_sub (hab : a ≀ b) (hcd : c ≀ d) : a - d ≀ b - c := by simpa only [sub_eq_add_neg] using add_le_add hab (neg_le_neg hcd) lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c := by simpa only [sub_eq_add_neg] using add_lt_add hab (neg_lt_neg hcd) @[simp] lemma sub_le_self_iff (a : Ξ±) {b : Ξ±} : a - b ≀ a ↔ 0 ≀ b := by simp [sub_eq_add_neg] alias sub_le_self_iff ↔ _ sub_le_self @[simp] lemma sub_lt_self_iff (a : Ξ±) {b : Ξ±} : a - b < a ↔ 0 < b := by simp [sub_eq_add_neg] alias sub_lt_self_iff ↔ _ sub_lt_self lemma sub_le_sub_iff : a - b ≀ c - d ↔ a + d ≀ c + b := by simpa only [sub_eq_add_neg] using add_neg_le_add_neg_iff @[simp] lemma sub_le_sub_iff_left (a : Ξ±) {b c : Ξ±} : a - b ≀ a - c ↔ c ≀ b := by rw [sub_eq_add_neg, sub_eq_add_neg, add_le_add_iff_left, neg_le_neg_iff] lemma sub_le_sub_left (h : a ≀ b) (c : Ξ±) : c - b ≀ c - a := (sub_le_sub_iff_left c).2 h @[simp] lemma sub_le_sub_iff_right (c : Ξ±) : a - c ≀ b - c ↔ a ≀ b := by simpa only [sub_eq_add_neg] using add_le_add_iff_right _ lemma sub_le_sub_right (h : a ≀ b) (c : Ξ±) : a - c ≀ b - c := (sub_le_sub_iff_right c).2 h @[simp] lemma sub_lt_sub_iff_left (a : Ξ±) {b c : Ξ±} : a - b < a - c ↔ c < b := by rw [sub_eq_add_neg, sub_eq_add_neg, add_lt_add_iff_left, neg_lt_neg_iff] lemma sub_lt_sub_left (h : a < b) (c : Ξ±) : c - b < c - a := (sub_lt_sub_iff_left c).2 h @[simp] lemma sub_lt_sub_iff_right (c : Ξ±) : a - c < b - c ↔ a < b := by simpa only [sub_eq_add_neg] using add_lt_add_iff_right _ lemma sub_lt_sub_right (h : a < b) (c : Ξ±) : a - c < b - c := (sub_lt_sub_iff_right c).2 h @[simp] lemma sub_nonneg : 0 ≀ a - b ↔ b ≀ a := by rw [← sub_self a, sub_le_sub_iff_left] alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le @[simp] lemma sub_nonpos : a - b ≀ 0 ↔ a ≀ b := by rw [← sub_self b, sub_le_sub_iff_right] alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le @[simp] lemma sub_pos : 0 < a - b ↔ b < a := by rw [← sub_self a, sub_lt_sub_iff_left] alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := by rw [← sub_self b, sub_lt_sub_iff_right] alias sub_lt_zero ↔ lt_of_sub_neg sub_neg_of_lt lemma le_sub_iff_add_le' : b ≀ c - a ↔ a + b ≀ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≀ c - b ↔ a + b ≀ c := by rw [le_sub_iff_add_le', add_comm] alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le lemma sub_le_iff_le_add' : a - b ≀ c ↔ a ≀ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le lemma sub_le_iff_le_add : a - c ≀ b ↔ a ≀ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≀ a - c ↔ c ≀ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≀ b - c ↔ c ≀ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≀ c ↔ a - c ≀ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≀ b - c ↔ c ≀ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm end ordered_add_comm_group /-! ### Linearly ordered commutative groups -/ /-- A linearly ordered additive commutative group is an additive commutative group with a linear order in which addition is monotone. -/ @[protect_proj] class linear_ordered_add_comm_group (Ξ± : Type u) extends add_comm_group Ξ±, linear_order Ξ± := (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) /-- A linearly ordered commutative group is a commutative group with a linear order in which multiplication is monotone. -/ @[protect_proj, to_additive] class linear_ordered_comm_group (Ξ± : Type u) extends comm_group Ξ±, linear_order Ξ± := (mul_le_mul_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c * a ≀ c * b) @[to_additive, priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_ordered_comm_group (Ξ± : Type u) [s : linear_ordered_comm_group Ξ±] : ordered_comm_group Ξ± := { ..s } section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group Ξ±] {a b c : Ξ±} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_add_comm_group.to_linear_ordered_cancel_add_comm_monoid : linear_ordered_cancel_add_comm_monoid Ξ± := { le_of_add_le_add_left := Ξ» x y z, le_of_add_le_add_left, add_left_cancel := Ξ» x y z, add_left_cancel, add_right_cancel := Ξ» x y z, add_right_cancel, ..β€Ήlinear_ordered_add_comm_group Ξ±β€Ί } lemma linear_ordered_add_comm_group.add_lt_add_left (a b : Ξ±) (h : a < b) (c : Ξ±) : c + a < c + b := ordered_add_comm_group.add_lt_add_left a b h c lemma min_neg_neg (a b : Ξ±) : min (-a) (-b) = -max a b := eq.symm $ @monotone.map_max Ξ± (order_dual Ξ±) _ _ has_neg.neg a b $ Ξ» a b, neg_le_neg lemma max_neg_neg (a b : Ξ±) : max (-a) (-b) = -min a b := eq.symm $ @monotone.map_min Ξ± (order_dual Ξ±) _ _ has_neg.neg a b $ Ξ» a b, neg_le_neg lemma min_sub_sub_right (a b c : Ξ±) : min (a - c) (b - c) = min a b - c := by simpa only [sub_eq_add_neg] using min_add_add_right a b (-c) lemma max_sub_sub_right (a b c : Ξ±) : max (a - c) (b - c) = max a b - c := by simpa only [sub_eq_add_neg] using max_add_add_right a b (-c) lemma min_sub_sub_left (a b c : Ξ±) : min (a - b) (a - c) = a - max b c := by simp only [sub_eq_add_neg, min_add_add_left, min_neg_neg] lemma max_sub_sub_left (a b c : Ξ±) : max (a - b) (a - c) = a - min b c := by simp only [sub_eq_add_neg, max_add_add_left, max_neg_neg] lemma max_zero_sub_eq_self (a : Ξ±) : max a 0 - max (-a) 0 = a := begin rcases le_total a 0, { rw [max_eq_right h, max_eq_left, zero_sub, neg_neg], { rwa [le_neg, neg_zero] } }, { rw [max_eq_left, max_eq_right, sub_zero], { rwa [neg_le, neg_zero] }, exact h } end /-- `abs a` is the absolute value of `a`. -/ def abs (a : Ξ±) : Ξ± := max a (-a) lemma abs_of_nonneg (h : 0 ≀ a) : abs a = a := max_eq_left $ (neg_nonpos.2 h).trans h lemma abs_of_pos (h : 0 < a) : abs a = a := abs_of_nonneg h.le lemma abs_of_nonpos (h : a ≀ 0) : abs a = -a := max_eq_right $ h.trans (neg_nonneg.2 h) lemma abs_of_neg (h : a < 0) : abs a = -a := abs_of_nonpos h.le @[simp] lemma abs_zero : abs 0 = (0:Ξ±) := abs_of_nonneg le_rfl @[simp] lemma abs_neg (a : Ξ±) : abs (-a) = abs a := begin unfold abs, rw [max_comm, neg_neg] end @[simp] lemma abs_pos : 0 < abs a ↔ a β‰  0 := begin rcases lt_trichotomy a 0 with (ha|rfl|ha), { simp [abs_of_neg ha, neg_pos, ha.ne, ha] }, { simp }, { simp [abs_of_pos ha, ha, ha.ne.symm] } end lemma abs_pos_of_pos (h : 0 < a) : 0 < abs a := abs_pos.2 h.ne.symm lemma abs_pos_of_neg (h : a < 0) : 0 < abs a := abs_pos.2 h.ne lemma abs_sub (a b : Ξ±) : abs (a - b) = abs (b - a) := by rw [← neg_sub, abs_neg] theorem abs_le' : abs a ≀ b ↔ a ≀ b ∧ -a ≀ b := max_le_iff theorem abs_le : abs a ≀ b ↔ - b ≀ a ∧ a ≀ b := by rw [abs_le', and.comm, neg_le] lemma le_abs_self (a : Ξ±) : a ≀ abs a := le_max_left _ _ lemma neg_le_abs_self (a : Ξ±) : -a ≀ abs a := le_max_right _ _ lemma abs_nonneg (a : Ξ±) : 0 ≀ abs a := (le_total 0 a).elim (Ξ» h, h.trans (le_abs_self a)) (Ξ» h, (neg_nonneg.2 h).trans $ neg_le_abs_self a) @[simp] lemma abs_abs (a : Ξ±) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a @[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 := not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos @[simp] lemma abs_nonpos_iff {a : Ξ±} : abs a ≀ 0 ↔ a = 0 := (abs_nonneg a).le_iff_eq.trans abs_eq_zero lemma abs_lt {a b : Ξ±} : abs a < b ↔ - b < a ∧ a < b := max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt] lemma lt_abs {a b : Ξ±} : a < abs b ↔ a < b ∨ a < -b := lt_max_iff lemma max_sub_min_eq_abs' (a b : Ξ±) : max a b - min a b = abs (a - b) := begin cases le_total a b with ab ba, { rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos }, { rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg } end lemma max_sub_min_eq_abs (a b : Ξ±) : max a b - min a b = abs (b - a) := by { rw [abs_sub], exact max_sub_min_eq_abs' _ _ } lemma abs_add (a b : Ξ±) : abs (a + b) ≀ abs a + abs b := abs_le.2 ⟨(neg_add (abs a) (abs b)).symm β–Έ add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _), add_le_add (le_abs_self _) (le_abs_self _)⟩ lemma abs_sub_le_iff : abs (a - b) ≀ c ↔ a - b ≀ c ∧ b - a ≀ c := by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm] lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm] lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≀ c) : b - c ≀ a := sub_le.1 $ (abs_sub_le_iff.1 h).2 lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≀ c) : a - c ≀ b := sub_le_of_abs_sub_le_left (abs_sub a b β–Έ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := sub_lt.1 $ (abs_sub_lt_iff.1 h).2 lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b β–Έ h) lemma abs_sub_abs_le_abs_sub (a b : Ξ±) : abs a - abs b ≀ abs (a - b) := sub_le_iff_le_add.2 $ calc abs a = abs (a - b + b) : by rw [sub_add_cancel] ... ≀ abs (a - b) + abs b : abs_add _ _ lemma abs_abs_sub_abs_le_abs_sub (a b : Ξ±) : abs (abs a - abs b) ≀ abs (a - b) := abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub; apply abs_sub_abs_le_abs_sub⟩ lemma abs_eq (hb : 0 ≀ b) : abs a = b ↔ a = b ∨ a = -b := iff.intro begin cases le_total a 0 with a_nonpos a_nonneg, { rw [abs_of_nonpos a_nonpos, neg_eq_iff_neg_eq, eq_comm], exact or.inr }, { rw [abs_of_nonneg a_nonneg, eq_comm], exact or.inl } end (by intro h; cases h; subst h; try { rw abs_neg }; exact abs_of_nonneg hb) lemma abs_le_max_abs_abs (hab : a ≀ b) (hbc : b ≀ c) : abs b ≀ max (abs a) (abs c) := abs_le'.2 ⟨by simp [hbc.trans (le_abs_self c)], by simp [(neg_le_neg hab).trans (neg_le_abs_self a)]⟩ theorem abs_le_abs (hβ‚€ : a ≀ b) (h₁ : -a ≀ b) : abs a ≀ abs b := (abs_le'.2 ⟨hβ‚€, hβ‚βŸ©).trans (le_abs_self b) lemma abs_max_sub_max_le_abs (a b c : Ξ±) : abs (max a c - max b c) ≀ abs (a - b) := begin simp_rw [abs_le, le_sub_iff_add_le, sub_le_iff_le_add, ← max_add_add_left], split; apply max_le_max; simp only [← le_sub_iff_add_le, ← sub_le_iff_le_add, sub_self, neg_le, neg_le_abs_self, neg_zero, abs_nonneg, le_abs_self] end lemma eq_zero_of_neg_eq {a : Ξ±} (h : -a = a) : a = 0 := match lt_trichotomy a 0 with | or.inl h₁ := have 0 < a, from h β–Έ neg_pos_of_neg h₁, absurd h₁ this.asymm | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 0, from h β–Έ neg_neg_of_pos h₁, absurd h₁ this.asymm end lemma eq_of_abs_sub_eq_zero {a b : Ξ±} (h : abs (a - b) = 0) : a = b := sub_eq_zero.1 $ abs_eq_zero.1 h lemma abs_by_cases (P : Ξ± β†’ Prop) {a : Ξ±} (h1 : P a) (h2 : P (-a)) : P (abs a) := sup_ind _ _ h1 h2 lemma abs_sub_le (a b c : Ξ±) : abs (a - c) ≀ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_add_sub_cancel] ... ≀ abs (a - b) + abs (b - c) : abs_add _ _ lemma abs_add_three (a b c : Ξ±) : abs (a + b + c) ≀ abs a + abs b + abs c := (abs_add _ _).trans (add_le_add_right (abs_add _ _) _) lemma dist_bdd_within_interval {a b lb ub : Ξ±} (hal : lb ≀ a) (hau : a ≀ ub) (hbl : lb ≀ b) (hbu : b ≀ ub) : abs (a - b) ≀ ub - lb := abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩ lemma eq_of_abs_sub_nonpos (h : abs (a - b) ≀ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) lemma exists_zero_lt [nontrivial Ξ±] : βˆƒ (a:Ξ±), 0 < a := begin obtain ⟨y, hy⟩ := exists_ne (0 : Ξ±), cases hy.lt_or_lt, { exact ⟨- y, neg_pos.mpr h⟩ }, { exact ⟨y, h⟩ } end @[priority 100] -- see Note [lower instance priority] instance linear_ordered_add_comm_group.to_no_top_order [nontrivial Ξ±] : no_top_order Ξ± := ⟨ begin obtain ⟨y, hy⟩ : βˆƒ (a:Ξ±), 0 < a := exists_zero_lt, exact Ξ» a, ⟨a + y, lt_add_of_pos_right a hy⟩ end ⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_add_comm_group.to_no_bot_order [nontrivial Ξ±] : no_bot_order Ξ± := ⟨ begin obtain ⟨y, hy⟩ : βˆƒ (a:Ξ±), 0 < a := exists_zero_lt, exact Ξ» a, ⟨a - y, sub_lt_self a hy⟩ end ⟩ end linear_ordered_add_comm_group /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (Ξ± : Type*) extends add_comm_group Ξ± := (nonneg : Ξ± β†’ Prop) (pos : Ξ± β†’ Prop := Ξ» a, nonneg a ∧ Β¬ nonneg (neg a)) (pos_iff : βˆ€ a, pos a ↔ nonneg a ∧ Β¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : βˆ€ {a b}, nonneg a β†’ nonneg b β†’ nonneg (a + b)) (nonneg_antisymm : βˆ€ {a}, nonneg a β†’ nonneg (-a) β†’ a = 0) namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group Ξ±] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group Ξ± := { le := Ξ» a b, nonneg (b - a), lt := Ξ» a b, pos (b - a), lt_iff_le_not_le := Ξ» a b, by simp; rw [pos_iff]; simp, le_refl := Ξ» a, by simp [zero_nonneg], le_trans := Ξ» a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := Ξ» a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := Ξ» a b nab c, by simpa [(≀), preorder.le] using nab, ..s } theorem nonneg_def {a : Ξ±} : nonneg a ↔ 0 ≀ a := show _ ↔ nonneg _, by simp theorem pos_def {a : Ξ±} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : Β¬ pos (0 : Ξ±) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : Ξ±} : 0 < a ↔ nonneg a ∧ Β¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (βˆ€ a : Ξ±, nonneg a ∨ nonneg (-a)) ↔ (βˆ€ a b : Ξ±, a ≀ b ∨ b ≀ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, Ξ» h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_linear_ordered_add_comm_group [decidable_pred (@nonneg Ξ± _)] (nonneg_total : βˆ€ a : Ξ±, nonneg a ∨ nonneg (-a)) : linear_ordered_add_comm_group Ξ± := { le := (≀), lt := (<), le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace order_dual instance [ordered_add_comm_group Ξ±] : ordered_add_comm_group (order_dual Ξ±) := { add_left_neg := Ξ» a : Ξ±, add_left_neg a, sub := Ξ» a b, (a - b : Ξ±), ..order_dual.ordered_add_comm_monoid, ..show add_comm_group Ξ±, by apply_instance } instance [linear_ordered_add_comm_group Ξ±] : linear_ordered_add_comm_group (order_dual Ξ±) := { add_le_add_left := Ξ» a b h c, @add_le_add_left Ξ± _ b a h _, ..order_dual.linear_order Ξ±, ..show add_comm_group Ξ±, by apply_instance } end order_dual namespace prod variables {G H : Type*} @[to_additive] instance [ordered_comm_group G] [ordered_comm_group H] : ordered_comm_group (G Γ— H) := { .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid } end prod section type_tags instance [ordered_add_comm_group Ξ±] : ordered_comm_group (multiplicative Ξ±) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group Ξ±] : ordered_add_comm_group (additive Ξ±) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } end type_tags
57a3e063fb75f0e29d4c4cf73a8a9a201314e698
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/order/filter/germ.lean
87ea9b15959ab9be38bbfca0d3888f5092f39e5c
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
21,563
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Abhimanyu Pallavi Sudhir -/ import order.filter.basic import algebra.pi_instances /-! # Germ of a function at a filter The germ of a function `f : Ξ± β†’ Ξ²` at a filter `l : filter Ξ±` is the equivalence class of `f` with respect to the equivalence relation `eventually_eq l`: `f β‰ˆ g` means `βˆ€αΆ  x in l, f x = g x`. ## Main definitions We define * `germ l Ξ²` to be the space of germs of functions `Ξ± β†’ Ξ²` at a filter `l : filter Ξ±`; * coercion from `Ξ± β†’ Ξ²` to `germ l Ξ²`: `(f : germ l Ξ²)` is the germ of `f : Ξ± β†’ Ξ²` at `l : filter Ξ±`; this coercion is declared as `has_coe_t`, so it does not require an explicit up arrow `↑`; * coercion from `Ξ²` to `germ l Ξ²`: `(↑c : germ l Ξ²)` is the germ of the constant function `Ξ» x:Ξ±, c` at a filter `l`; this coercion is declared as `has_lift_t`, so it requires an explicit up arrow `↑`, see [TPiL][TPiL_coe] for details. * `map (F : Ξ² β†’ Ξ³) (f : germ l Ξ²)` to be the composition of a function `F` and a germ `f`; * `mapβ‚‚ (F : Ξ² β†’ Ξ³ β†’ Ξ΄) (f : germ l Ξ²) (g : germ l Ξ³)` to be the germ of `Ξ» x, F (f x) (g x)` at `l`; * `f.tendsto lb`: we say that a germ `f : germ l Ξ²` tends to a filter `lb` if its representatives tend to `lb` along `l`; * `f.comp_tendsto g hg` and `f.comp_tendsto' g hg`: given `f : germ l Ξ²` and a function `g : Ξ³ β†’ Ξ±` (resp., a germ `g : germ lc Ξ±`), if `g` tends to `l` along `lc`, then the composition `f ∘ g` is a well-defined germ at `lc`; * `germ.lift_pred`, `germ.lift_rel`: lift a predicate or a relation to the space of germs: `(f : germ l Ξ²).lift_pred p` means `βˆ€αΆ  x in l, p (f x)`, and similarly for a relation. [TPiL_coe]: https://leanprover.github.io/theorem_proving_in_lean/type_classes.html#coercions-using-type-classes We also define `map (F : Ξ² β†’ Ξ³) : germ l Ξ² β†’ germ l Ξ³` sending each germ `f` to `F ∘ f`. For each of the following structures we prove that if `Ξ²` has this structure, then so does `germ l Ξ²`: * one-operation algebraic structures up to `comm_group`; * `mul_zero_class`, `distrib`, `semiring`, `comm_semiring`, `ring`, `comm_ring`; * `mul_action`, `distrib_mul_action`, `semimodule`; * `preorder`, `partial_order`, and `lattice` structures up to `bounded_lattice`; * `ordered_cancel_comm_monoid` and `ordered_cancel_add_comm_monoid`. ## Tags filter, germ -/ namespace filter variables {Ξ± Ξ² Ξ³ Ξ΄ : Type*} {l : filter Ξ±} {f g h : Ξ± β†’ Ξ²} lemma const_eventually_eq' (hl : l β‰  βŠ₯) {a b : Ξ²} : (βˆ€αΆ  x in l, a = b) ↔ a = b := eventually_const hl lemma const_eventually_eq (hl : l β‰  βŠ₯) {a b : Ξ²} : ((Ξ» _, a) =αΆ [l] (Ξ» _, b)) ↔ a = b := @const_eventually_eq' _ _ _ hl a b lemma eventually_eq.comp_tendsto {f' : Ξ± β†’ Ξ²} (H : f =αΆ [l] f') {g : Ξ³ β†’ Ξ±} {lc : filter Ξ³} (hg : tendsto g lc l) : f ∘ g =αΆ [lc] f' ∘ g := hg.eventually H /-- Setoid used to define the space of germs. -/ def germ_setoid (l : filter Ξ±) (Ξ² : Type*) : setoid (Ξ± β†’ Ξ²) := { r := eventually_eq l, iseqv := ⟨eventually_eq.refl _, Ξ» _ _, eventually_eq.symm, Ξ» _ _ _, eventually_eq.trans⟩ } /-- The space of germs of functions `Ξ± β†’ Ξ²` at a filter `l`. -/ def germ (l : filter Ξ±) (Ξ² : Type*) : Type* := quotient (germ_setoid l Ξ²) namespace germ instance : has_coe_t (Ξ± β†’ Ξ²) (germ l Ξ²) := ⟨quotient.mk'⟩ instance : has_lift_t Ξ² (germ l Ξ²) := ⟨λ c, ↑(Ξ» (x : Ξ±), c)⟩ @[simp] lemma quot_mk_eq_coe (l : filter Ξ±) (f : Ξ± β†’ Ξ²) : quot.mk _ f = (f : germ l Ξ²) := rfl @[simp] lemma mk'_eq_coe (l : filter Ξ±) (f : Ξ± β†’ Ξ²) : quotient.mk' f = (f : germ l Ξ²) := rfl @[elab_as_eliminator] lemma induction_on (f : germ l Ξ²) {p : germ l Ξ² β†’ Prop} (h : βˆ€ f : Ξ± β†’ Ξ², p f) : p f := quotient.induction_on' f h @[elab_as_eliminator] lemma induction_onβ‚‚ (f : germ l Ξ²) (g : germ l Ξ³) {p : germ l Ξ² β†’ germ l Ξ³ β†’ Prop} (h : βˆ€ (f : Ξ± β†’ Ξ²) (g : Ξ± β†’ Ξ³), p f g) : p f g := quotient.induction_onβ‚‚' f g h @[elab_as_eliminator] lemma induction_on₃ (f : germ l Ξ²) (g : germ l Ξ³) (h : germ l Ξ΄) {p : germ l Ξ² β†’ germ l Ξ³ β†’ germ l Ξ΄ β†’ Prop} (H : βˆ€ (f : Ξ± β†’ Ξ²) (g : Ξ± β†’ Ξ³) (h : Ξ± β†’ Ξ΄), p f g h) : p f g h := quotient.induction_on₃' f g h H /-- Given a map `F : (Ξ± β†’ Ξ²) β†’ (Ξ³ β†’ Ξ΄)` that sends functions eventually equal at `l` to functions eventually equal at `lc`, returns a map from `germ l Ξ²` to `germ lc Ξ΄`. -/ def map' {lc : filter Ξ³} (F : (Ξ± β†’ Ξ²) β†’ (Ξ³ β†’ Ξ΄)) (hF : (l.eventually_eq β‡’ lc.eventually_eq) F F) : germ l Ξ² β†’ germ lc Ξ΄ := quotient.map' F hF /-- Given a germ `f : germ l Ξ²` and a function `F : (Ξ± β†’ Ξ²) β†’ Ξ³` sending eventually equal functions to the same value, returns the value `F` takes on functions having germ `f` at `l`. -/ def lift_on {Ξ³ : Sort*} (f : germ l Ξ²) (F : (Ξ± β†’ Ξ²) β†’ Ξ³) (hF : (l.eventually_eq β‡’ (=)) F F) : Ξ³ := quotient.lift_on' f F hF @[simp] lemma map'_coe {lc : filter Ξ³} (F : (Ξ± β†’ Ξ²) β†’ (Ξ³ β†’ Ξ΄)) (hF : (l.eventually_eq β‡’ lc.eventually_eq) F F) (f : Ξ± β†’ Ξ²) : map' F hF f = F f := rfl @[simp, norm_cast] lemma coe_eq : (f : germ l Ξ²) = g ↔ (f =αΆ [l] g) := quotient.eq' alias coe_eq ↔ _ filter.eventually_eq.germ_eq /-- Lift a function `Ξ² β†’ Ξ³` to a function `germ l Ξ² β†’ germ l Ξ³`. -/ def map (op : Ξ² β†’ Ξ³) : germ l Ξ² β†’ germ l Ξ³ := map' ((∘) op) $ Ξ» f g H, H.mono $ Ξ» x H, congr_arg op H @[simp] lemma map_coe (op : Ξ² β†’ Ξ³) (f : Ξ± β†’ Ξ²) : map op (f : germ l Ξ²) = op ∘ f := rfl @[simp] lemma map_id : map id = (id : germ l Ξ² β†’ germ l Ξ²) := by { ext ⟨f⟩, refl } lemma map_map (op₁ : Ξ³ β†’ Ξ΄) (opβ‚‚ : Ξ² β†’ Ξ³) (f : germ l Ξ²) : map op₁ (map opβ‚‚ f) = map (op₁ ∘ opβ‚‚) f := induction_on f $ Ξ» f, rfl /-- Lift a binary function `Ξ² β†’ Ξ³ β†’ Ξ΄` to a function `germ l Ξ² β†’ germ l Ξ³ β†’ germ l Ξ΄`. -/ def mapβ‚‚ (op : Ξ² β†’ Ξ³ β†’ Ξ΄) : germ l Ξ² β†’ germ l Ξ³ β†’ germ l Ξ΄ := quotient.mapβ‚‚' (Ξ» f g x, op (f x) (g x)) $ Ξ» f f' Hf g g' Hg, Hg.mp $ Hf.mono $ Ξ» x Hf Hg, by simp only [Hf, Hg] /-- A germ at `l` of maps from `Ξ±` to `Ξ²` tends to `lb : filter Ξ²` if it is represented by a map which tends to `lb` along `l`. -/ protected def tendsto (f : germ l Ξ²) (lb : filter Ξ²) : Prop := lift_on f (Ξ» f, tendsto f l lb) $ Ξ» f g H, propext (tendsto_congr' H) @[simp, norm_cast] lemma coe_tendsto {f : Ξ± β†’ Ξ²} {lb : filter Ξ²} : (f : germ l Ξ²).tendsto lb ↔ tendsto f l lb := iff.rfl alias coe_tendsto ↔ _ filter.tendsto.germ_tendsto /-- Given two germs `f : germ l Ξ²`, and `g : germ lc Ξ±`, where `l : filter Ξ±`, if `g` tends to `l`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto' (f : germ l Ξ²) {lc : filter Ξ³} (g : germ lc Ξ±) (hg : g.tendsto l) : germ lc Ξ² := lift_on f (Ξ» f, g.map f) $ Ξ» f₁ fβ‚‚ hF, (induction_on g $ Ξ» g hg, coe_eq.2 $ hg.eventually hF) hg @[simp] lemma coe_comp_tendsto' (f : Ξ± β†’ Ξ²) {lc : filter Ξ³} {g : germ lc Ξ±} (hg : g.tendsto l) : (f : germ l Ξ²).comp_tendsto' g hg = g.map f := rfl /-- Given a germ `f : germ l Ξ²` and a function `g : Ξ³ β†’ Ξ±`, where `l : filter Ξ±`, if `g` tends to `l` along `lc : filter Ξ³`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto (f : germ l Ξ²) {lc : filter Ξ³} (g : Ξ³ β†’ Ξ±) (hg : tendsto g lc l) : germ lc Ξ² := f.comp_tendsto' _ hg.germ_tendsto @[simp] lemma coe_comp_tendsto (f : Ξ± β†’ Ξ²) {lc : filter Ξ³} {g : Ξ³ β†’ Ξ±} (hg : tendsto g lc l) : (f : germ l Ξ²).comp_tendsto g hg = f ∘ g := rfl @[simp] lemma comp_tendsto'_coe (f : germ l Ξ²) {lc : filter Ξ³} {g : Ξ³ β†’ Ξ±} (hg : tendsto g lc l) : f.comp_tendsto' _ hg.germ_tendsto = f.comp_tendsto g hg := rfl @[simp, norm_cast] lemma const_inj (hl : l β‰  βŠ₯) {a b : Ξ²} : (↑a : germ l Ξ²) = ↑b ↔ a = b := coe_eq.trans $ const_eventually_eq hl @[simp] lemma map_const (l : filter Ξ±) (a : Ξ²) (f : Ξ² β†’ Ξ³) : (↑a : germ l Ξ²).map f = ↑(f a) := rfl @[simp] lemma mapβ‚‚_const (l : filter Ξ±) (b : Ξ²) (c : Ξ³) (f : Ξ² β†’ Ξ³ β†’ Ξ΄) : mapβ‚‚ f (↑b : germ l Ξ²) ↑c = ↑(f b c) := rfl @[simp] lemma const_comp_tendsto {l : filter Ξ±} (b : Ξ²) {lc : filter Ξ³} {g : Ξ³ β†’ Ξ±} (hg : tendsto g lc l) : (↑b : germ l Ξ²).comp_tendsto g hg = ↑b := rfl @[simp] lemma const_comp_tendsto' {l : filter Ξ±} (b : Ξ²) {lc : filter Ξ³} {g : germ lc Ξ±} (hg : g.tendsto l) : (↑b : germ l Ξ²).comp_tendsto' g hg = ↑b := induction_on g (Ξ» _ _, rfl) hg /-- Lift a predicate on `Ξ²` to `germ l Ξ²`. -/ def lift_pred (p : Ξ² β†’ Prop) (f : germ l Ξ²) : Prop := lift_on f (Ξ» f, βˆ€αΆ  x in l, p (f x)) $ Ξ» f g H, propext $ eventually_congr $ H.mono $ Ξ» x hx, hx β–Έ iff.rfl @[simp] lemma lift_pred_coe {p : Ξ² β†’ Prop} {f : Ξ± β†’ Ξ²} : lift_pred p (f : germ l Ξ²) ↔ βˆ€αΆ  x in l, p (f x) := iff.rfl lemma lift_pred_const {p : Ξ² β†’ Prop} {x : Ξ²} (hx : p x) : lift_pred p (↑x : germ l Ξ²) := eventually_of_forall $ Ξ» y, hx @[simp] lemma lift_pred_const_iff (hl : l β‰  βŠ₯) {p : Ξ² β†’ Prop} {x : Ξ²} : lift_pred p (↑x : germ l Ξ²) ↔ p x := @eventually_const _ _ hl (p x) /-- Lift a relation `r : Ξ² β†’ Ξ³ β†’ Prop` to `germ l Ξ² β†’ germ l Ξ³ β†’ Prop`. -/ def lift_rel (r : Ξ² β†’ Ξ³ β†’ Prop) (f : germ l Ξ²) (g : germ l Ξ³) : Prop := quotient.lift_onβ‚‚' f g (Ξ» f g, βˆ€αΆ  x in l, r (f x) (g x)) $ Ξ» f g f' g' Hf Hg, propext $ eventually_congr $ Hg.mp $ Hf.mono $ Ξ» x hf hg, hf β–Έ hg β–Έ iff.rfl @[simp] lemma lift_rel_coe {r : Ξ² β†’ Ξ³ β†’ Prop} {f : Ξ± β†’ Ξ²} {g : Ξ± β†’ Ξ³} : lift_rel r (f : germ l Ξ²) g ↔ βˆ€αΆ  x in l, r (f x) (g x) := iff.rfl lemma lift_rel_const {r : Ξ² β†’ Ξ³ β†’ Prop} {x : Ξ²} {y : Ξ³} (h : r x y) : lift_rel r (↑x : germ l Ξ²) ↑y := eventually_of_forall $ Ξ» _, h @[simp] lemma lift_rel_const_iff (hl : l β‰  βŠ₯) {r : Ξ² β†’ Ξ³ β†’ Prop} {x : Ξ²} {y : Ξ³} : lift_rel r (↑x : germ l Ξ²) ↑y ↔ r x y := @eventually_const _ _ hl (r x y) instance [inhabited Ξ²] : inhabited (germ l Ξ²) := βŸ¨β†‘(default Ξ²)⟩ section monoid variables {M : Type*} {G : Type*} @[to_additive] instance [has_mul M] : has_mul (germ l M) := ⟨mapβ‚‚ (*)⟩ @[simp, to_additive] lemma coe_mul [has_mul M] (f g : Ξ± β†’ M) : ↑(f * g) = (f * g : germ l M) := rfl attribute [norm_cast] coe_mul coe_add @[to_additive] instance [has_one M] : has_one (germ l M) := βŸ¨β†‘(1:M)⟩ @[simp, to_additive] lemma coe_one [has_one M] : ↑(1 : Ξ± β†’ M) = (1 : germ l M) := rfl attribute [norm_cast] coe_one coe_zero @[to_additive add_semigroup] instance [semigroup M] : semigroup (germ l M) := { mul := (*), mul_assoc := by { rintros ⟨f⟩ ⟨g⟩ ⟨h⟩, simp only [mul_assoc, quot_mk_eq_coe, ← coe_mul] } } @[to_additive add_comm_semigroup] instance [comm_semigroup M] : comm_semigroup (germ l M) := { mul := (*), mul_comm := by { rintros ⟨f⟩ ⟨g⟩, simp only [mul_comm, quot_mk_eq_coe, ← coe_mul] }, .. germ.semigroup } @[to_additive add_left_cancel_semigroup] instance [left_cancel_semigroup M] : left_cancel_semigroup (germ l M) := { mul := (*), mul_left_cancel := Ξ» f₁ fβ‚‚ f₃, induction_on₃ f₁ fβ‚‚ f₃ $ Ξ» f₁ fβ‚‚ f₃ H, coe_eq.2 ((coe_eq.1 H).mono $ Ξ» x, mul_left_cancel), .. germ.semigroup } @[to_additive add_right_cancel_semigroup] instance [right_cancel_semigroup M] : right_cancel_semigroup (germ l M) := { mul := (*), mul_right_cancel := Ξ» f₁ fβ‚‚ f₃, induction_on₃ f₁ fβ‚‚ f₃ $ Ξ» f₁ fβ‚‚ f₃ H, coe_eq.2 $ (coe_eq.1 H).mono $ Ξ» x, mul_right_cancel, .. germ.semigroup } @[to_additive add_monoid] instance [monoid M] : monoid (germ l M) := { mul := (*), one := 1, one_mul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [one_mul] }, mul_one := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [mul_one] }, .. germ.semigroup } /-- coercion from functions to germs as a monoid homomorphism. -/ @[to_additive] def coe_mul_hom [monoid M] (l : filter Ξ±) : (Ξ± β†’ M) β†’* germ l M := ⟨coe, rfl, Ξ» f g, rfl⟩ /-- coercion from functions to germs as an additive monoid homomorphism. -/ add_decl_doc coe_add_hom @[simp, to_additive] lemma coe_coe_mul_hom [monoid M] : (coe_mul_hom l : (Ξ± β†’ M) β†’ germ l M) = coe := rfl @[to_additive add_comm_monoid] instance [comm_monoid M] : comm_monoid (germ l M) := { mul := (*), one := 1, .. germ.comm_semigroup, .. germ.monoid } @[to_additive] instance [has_inv G] : has_inv (germ l G) := ⟨map has_inv.inv⟩ @[simp, to_additive] lemma coe_inv [has_inv G] (f : Ξ± β†’ G) : ↑f⁻¹ = (f⁻¹ : germ l G) := rfl attribute [norm_cast] coe_inv coe_neg @[to_additive add_group] instance [group G] : group (germ l G) := { mul := (*), one := 1, inv := has_inv.inv, mul_left_inv := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [mul_left_inv] }, .. germ.monoid } @[simp, norm_cast] lemma coe_sub [add_group G] (f g : Ξ± β†’ G) : ↑(f - g) = (f - g : germ l G) := rfl @[to_additive add_comm_group] instance [comm_group G] : comm_group (germ l G) := { mul := (*), one := 1, inv := has_inv.inv, .. germ.group, .. germ.comm_monoid } end monoid section ring variables {R : Type*} /-- If `Ξ²` is nontrivial and `l` is a non-trivial filter (`l β‰  βŠ₯`), then `germ l Ξ²` is nontrivial. This cannot be an `instance` because it depends on `l β‰  βŠ₯`. -/ protected lemma nontrivial [nontrivial R] (hl : l β‰  βŠ₯) : nontrivial (germ l R) := let ⟨x, y, h⟩ := exists_pair_ne R in βŸ¨βŸ¨β†‘x, ↑y, mt (const_inj hl).1 h⟩⟩ instance [mul_zero_class R] : mul_zero_class (germ l R) := { zero := 0, mul := (*), mul_zero := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [mul_zero] }, zero_mul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [zero_mul] } } instance [distrib R] : distrib (germ l R) := { mul := (*), add := (+), left_distrib := Ξ» f g h, induction_on₃ f g h $ Ξ» f g h, by { norm_cast, rw [left_distrib] }, right_distrib := Ξ» f g h, induction_on₃ f g h $ Ξ» f g h, by { norm_cast, rw [right_distrib] } } instance [semiring R] : semiring (germ l R) := { .. germ.add_comm_monoid, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } /-- Coercion `(Ξ± β†’ R) β†’ germ l R` as a `ring_hom`. -/ def coe_ring_hom [semiring R] (l : filter Ξ±) : (Ξ± β†’ R) β†’+* germ l R := { to_fun := coe, .. (coe_mul_hom l : _ β†’* germ l R), .. (coe_add_hom l : _ β†’+ germ l R) } @[simp] lemma coe_coe_ring_hom [semiring R] : (coe_ring_hom l : (Ξ± β†’ R) β†’ germ l R) = coe := rfl instance [ring R] : ring (germ l R) := { .. germ.add_comm_group, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } instance [comm_semiring R] : comm_semiring (germ l R) := { .. germ.semiring, .. germ.comm_monoid } instance [comm_ring R] : comm_ring (germ l R) := { .. germ.ring, .. germ.comm_monoid } end ring section module variables {M N R : Type*} instance [has_scalar M Ξ²] : has_scalar M (germ l Ξ²) := ⟨λ c, map ((β€’) c)⟩ instance has_scalar' [has_scalar M Ξ²] : has_scalar (germ l M) (germ l Ξ²) := ⟨mapβ‚‚ (β€’)⟩ @[simp, norm_cast] lemma coe_smul [has_scalar M Ξ²] (c : M) (f : Ξ± β†’ Ξ²) : ↑(c β€’ f) = (c β€’ f : germ l Ξ²) := rfl @[simp, norm_cast] lemma coe_smul' [has_scalar M Ξ²] (c : Ξ± β†’ M) (f : Ξ± β†’ Ξ²) : ↑(c β€’ f) = (c : germ l M) β€’ (f : germ l Ξ²) := rfl instance [monoid M] [mul_action M Ξ²] : mul_action M (germ l Ξ²) := { one_smul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, simp only [one_smul] }, mul_smul := Ξ» c₁ cβ‚‚ f, induction_on f $ Ξ» f, by { norm_cast, simp only [mul_smul] } } instance mul_action' [monoid M] [mul_action M Ξ²] : mul_action (germ l M) (germ l Ξ²) := { one_smul := Ξ» f, induction_on f $ Ξ» f, by simp only [← coe_one, ← coe_smul', one_smul], mul_smul := Ξ» c₁ cβ‚‚ f, induction_on₃ c₁ cβ‚‚ f $ Ξ» c₁ cβ‚‚ f, by { norm_cast, simp only [mul_smul] } } instance [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action M (germ l N) := { smul_add := Ξ» c f g, induction_onβ‚‚ f g $ Ξ» f g, by { norm_cast, simp only [smul_add] }, smul_zero := Ξ» c, by simp only [← coe_zero, ← coe_smul, smul_zero] } instance distrib_mul_action' [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action (germ l M) (germ l N) := { smul_add := Ξ» c f g, induction_on₃ c f g $ Ξ» c f g, by { norm_cast, simp only [smul_add] }, smul_zero := Ξ» c, induction_on c $ Ξ» c, by simp only [← coe_zero, ← coe_smul', smul_zero] } instance [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule R (germ l M) := { add_smul := Ξ» c₁ cβ‚‚ f, induction_on f $ Ξ» f, by { norm_cast, simp only [add_smul] }, zero_smul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, simp only [zero_smul, coe_zero] } } instance semimodule' [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule (germ l R) (germ l M) := { add_smul := Ξ» c₁ cβ‚‚ f, induction_on₃ c₁ cβ‚‚ f $ Ξ» c₁ cβ‚‚ f, by { norm_cast, simp only [add_smul] }, zero_smul := Ξ» f, induction_on f $ Ξ» f, by simp only [← coe_zero, ← coe_smul', zero_smul] } end module instance [has_le Ξ²] : has_le (germ l Ξ²) := ⟨λ f g, quotient.lift_onβ‚‚' f g l.eventually_le $ Ξ» f f' g g' h h', propext $ eventually_le_congr h h'⟩ @[simp] lemma coe_le [has_le Ξ²] : (f : germ l Ξ²) ≀ g ↔ (f ≀ᢠ[l] g) := iff.rfl lemma const_le [has_le Ξ²] {x y : Ξ²} (h : x ≀ y) : (↑x : germ l Ξ²) ≀ ↑y := lift_rel_const h @[simp, norm_cast] lemma const_le_iff [has_le Ξ²] (hl : l β‰  βŠ₯) {x y : Ξ²} : (↑x : germ l Ξ²) ≀ ↑y ↔ x ≀ y := lift_rel_const_iff hl instance [preorder Ξ²] : preorder (germ l Ξ²) := { le := (≀), le_refl := Ξ» f, induction_on f $ eventually_le.refl l, le_trans := Ξ» f₁ fβ‚‚ f₃, induction_on₃ f₁ fβ‚‚ f₃ $ Ξ» f₁ fβ‚‚ f₃, eventually_le.trans } instance [partial_order Ξ²] : partial_order (germ l Ξ²) := { le := (≀), le_antisymm := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g h₁ hβ‚‚, (h₁.antisymm hβ‚‚).germ_eq, .. germ.preorder } instance [has_bot Ξ²] : has_bot (germ l Ξ²) := βŸ¨β†‘(βŠ₯:Ξ²)⟩ @[simp, norm_cast] lemma const_bot [has_bot Ξ²] : (↑(βŠ₯:Ξ²) : germ l Ξ²) = βŠ₯ := rfl instance [order_bot Ξ²] : order_bot (germ l Ξ²) := { bot := βŠ₯, le := (≀), bot_le := Ξ» f, induction_on f $ Ξ» f, eventually_of_forall $ Ξ» x, bot_le, .. germ.partial_order } instance [has_top Ξ²] : has_top (germ l Ξ²) := βŸ¨β†‘(⊀:Ξ²)⟩ @[simp, norm_cast] lemma const_top [has_top Ξ²] : (↑(⊀:Ξ²) : germ l Ξ²) = ⊀ := rfl instance [order_top Ξ²] : order_top (germ l Ξ²) := { top := ⊀, le := (≀), le_top := Ξ» f, induction_on f $ Ξ» f, eventually_of_forall $ Ξ» x, le_top, .. germ.partial_order } instance [has_sup Ξ²] : has_sup (germ l Ξ²) := ⟨mapβ‚‚ (βŠ”)⟩ @[simp, norm_cast] lemma const_sup [has_sup Ξ²] (a b : Ξ²) : ↑(a βŠ” b) = (↑a βŠ” ↑b : germ l Ξ²) := rfl instance [has_inf Ξ²] : has_inf (germ l Ξ²) := ⟨mapβ‚‚ (βŠ“)⟩ @[simp, norm_cast] lemma const_inf [has_inf Ξ²] (a b : Ξ²) : ↑(a βŠ“ b) = (↑a βŠ“ ↑b : germ l Ξ²) := rfl instance [semilattice_sup Ξ²] : semilattice_sup (germ l Ξ²) := { sup := (βŠ”), le_sup_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall $ Ξ» x, le_sup_left, le_sup_right := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall $ Ξ» x, le_sup_right, sup_le := Ξ» f₁ fβ‚‚ g, induction_on₃ f₁ fβ‚‚ g $ Ξ» f₁ fβ‚‚ g h₁ hβ‚‚, hβ‚‚.mp $ h₁.mono $ Ξ» x, sup_le, .. germ.partial_order } instance [semilattice_inf Ξ²] : semilattice_inf (germ l Ξ²) := { inf := (βŠ“), inf_le_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall $ Ξ» x, inf_le_left, inf_le_right := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall $ Ξ» x, inf_le_right, le_inf := Ξ» f₁ fβ‚‚ g, induction_on₃ f₁ fβ‚‚ g $ Ξ» f₁ fβ‚‚ g h₁ hβ‚‚, hβ‚‚.mp $ h₁.mono $ Ξ» x, le_inf, .. germ.partial_order } instance [semilattice_inf_bot Ξ²] : semilattice_inf_bot (germ l Ξ²) := { .. germ.semilattice_inf, .. germ.order_bot } instance [semilattice_sup_bot Ξ²] : semilattice_sup_bot (germ l Ξ²) := { .. germ.semilattice_sup, .. germ.order_bot } instance [semilattice_inf_top Ξ²] : semilattice_inf_top (germ l Ξ²) := { .. germ.semilattice_inf, .. germ.order_top } instance [semilattice_sup_top Ξ²] : semilattice_sup_top (germ l Ξ²) := { .. germ.semilattice_sup, .. germ.order_top } instance [lattice Ξ²] : lattice (germ l Ξ²) := { .. germ.semilattice_sup, .. germ.semilattice_inf } instance [bounded_lattice Ξ²] : bounded_lattice (germ l Ξ²) := { .. germ.lattice, .. germ.order_bot, .. germ.order_top } @[to_additive ordered_cancel_add_comm_monoid] instance [ordered_cancel_comm_monoid Ξ²] : ordered_cancel_comm_monoid (germ l Ξ²) := { mul_le_mul_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g H h, induction_on h $ Ξ» h, H.mono $ Ξ» x H, mul_le_mul_left' H _, le_of_mul_le_mul_left := Ξ» f g h, induction_on₃ f g h $ Ξ» f g h H, H.mono $ Ξ» x, le_of_mul_le_mul_left', .. germ.partial_order, .. germ.comm_monoid, .. germ.left_cancel_semigroup, .. germ.right_cancel_semigroup } @[to_additive ordered_add_comm_group] instance ordered_comm_group [ordered_comm_group Ξ²] : ordered_comm_group (germ l Ξ²) := { mul_le_mul_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g H h, induction_on h $ Ξ» h, H.mono $ Ξ» x H, mul_le_mul_left' H _, .. germ.partial_order, .. germ.comm_group } end germ end filter
2b4ac46df6cb98d79fd2cca24926c08d7721c8f0
82e44445c70db0f03e30d7be725775f122d72f3e
/src/group_theory/order_of_element.lean
3b7c5f5875681b30a597395be19c200d943a0f45
[ "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
39,264
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, Julian Kuelshammer -/ import algebra.pointwise import group_theory.coset import dynamics.periodic_pts import algebra.iterate_hom /-! # Order of an element This file defines the order of an element of a finite group. For a finite group `G` the order of `x ∈ G` is the minimal `n β‰₯ 1` such that `x ^ n = 1`. ## Main definitions * `is_of_fin_order` is a predicate on an element `x` of a monoid `G` saying that `x` is of finite order. * `is_of_fin_add_order` is the additive analogue of `is_of_find_order`. * `order_of x` defines the order of an element `x` of a monoid `G`, by convention its value is `0` if `x` has infinite order. * `add_order_of` is the additive analogue of `order_of`. ## Tags order of an element -/ open function nat universes u v variables {G : Type u} {A : Type v} variables {x y : G} {a b : A} {n m : β„•} section monoid_add_monoid variables [monoid G] [add_monoid A] section is_of_fin_order lemma is_periodic_pt_add_iff_nsmul_eq_zero (a : A) : is_periodic_pt ((+) a) n 0 ↔ n β€’ a = 0 := by rw [is_periodic_pt, is_fixed_pt, add_left_iterate, add_zero] @[to_additive is_periodic_pt_add_iff_nsmul_eq_zero] lemma is_periodic_pt_mul_iff_pow_eq_one (x : G) : is_periodic_pt ((*) x) n 1 ↔ x ^ n = 1 := by rw [is_periodic_pt, is_fixed_pt, mul_left_iterate, mul_one] /-- `is_of_fin_add_order` is a predicate on an element `a` of an additive monoid to be of finite order, i.e. there exists `n β‰₯ 1` such that `n β€’ a = 0`.-/ def is_of_fin_add_order (a : A) : Prop := (0 : A) ∈ periodic_pts ((+) a) /-- `is_of_fin_order` is a predicate on an element `x` of a monoid to be of finite order, i.e. there exists `n β‰₯ 1` such that `x ^ n = 1`.-/ @[to_additive is_of_fin_add_order] def is_of_fin_order (x : G) : Prop := (1 : G) ∈ periodic_pts ((*) x) lemma is_of_fin_add_order_of_mul_iff : is_of_fin_add_order (additive.of_mul x) ↔ is_of_fin_order x := iff.rfl lemma is_of_fin_order_of_add_iff : is_of_fin_order (multiplicative.of_add a) ↔ is_of_fin_add_order a := iff.rfl lemma is_of_fin_add_order_iff_nsmul_eq_zero (a : A) : is_of_fin_add_order a ↔ βˆƒ n, 0 < n ∧ n β€’ a = 0 := by { convert iff.rfl, simp only [exists_prop, is_periodic_pt_add_iff_nsmul_eq_zero] } @[to_additive is_of_fin_add_order_iff_nsmul_eq_zero] lemma is_of_fin_order_iff_pow_eq_one (x : G) : is_of_fin_order x ↔ βˆƒ n, 0 < n ∧ x ^ n = 1 := by { convert iff.rfl, simp [is_periodic_pt_mul_iff_pow_eq_one] } end is_of_fin_order /-- `add_order_of a` is the order of the element `a`, i.e. the `n β‰₯ 1`, s.t. `n β€’ a = 0` if it exists. Otherwise, i.e. if `a` is of infinite order, then `add_order_of a` is `0` by convention.-/ noncomputable def add_order_of (a : A) : β„• := minimal_period ((+) a) 0 /-- `order_of x` is the order of the element `x`, i.e. the `n β‰₯ 1`, s.t. `x ^ n = 1` if it exists. Otherwise, i.e. if `x` is of infinite order, then `order_of x` is `0` by convention.-/ @[to_additive add_order_of] noncomputable def order_of (x : G) : β„• := minimal_period ((*) x) 1 attribute [to_additive add_order_of] order_of @[to_additive] lemma commute.order_of_mul_dvd_lcm (h : commute x y) : order_of (x * y) ∣ nat.lcm (order_of x) (order_of y) := begin convert function.commute.minimal_period_of_comp_dvd_lcm h.function_commute_mul_left, rw [order_of, comp_mul_left], end @[simp] lemma add_order_of_of_mul_eq_order_of (x : G) : add_order_of (additive.of_mul x) = order_of x := rfl @[simp] lemma order_of_of_add_eq_add_order_of (a : A) : order_of (multiplicative.of_add a) = add_order_of a := rfl @[to_additive add_order_of_pos'] lemma order_of_pos' (h : is_of_fin_order x) : 0 < order_of x := minimal_period_pos_of_mem_periodic_pts h lemma pow_order_of_eq_one (x : G) : x ^ order_of x = 1 := begin convert is_periodic_pt_minimal_period ((*) x) _, rw [order_of, mul_left_iterate, mul_one], end lemma add_order_of_nsmul_eq_zero (a : A) : add_order_of a β€’ a = 0 := begin convert is_periodic_pt_minimal_period ((+) a) _, rw [add_order_of, add_left_iterate, add_zero], end attribute [to_additive add_order_of_nsmul_eq_zero] pow_order_of_eq_one @[to_additive add_order_of_eq_zero] lemma order_of_eq_zero (h : Β¬ is_of_fin_order x) : order_of x = 0 := by rwa [order_of, minimal_period, dif_neg] lemma nsmul_ne_zero_of_lt_add_order_of' (n0 : n β‰  0) (h : n < add_order_of a) : n β€’ a β‰  0 := Ξ» j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_add_iff_nsmul_eq_zero a).mpr j) @[to_additive nsmul_ne_zero_of_lt_add_order_of'] lemma pow_eq_one_of_lt_order_of' (n0 : n β‰  0) (h : n < order_of x) : x ^ n β‰  1 := Ξ» j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_mul_iff_pow_eq_one x).mpr j) lemma add_order_of_le_of_nsmul_eq_zero (hn : 0 < n) (h : n β€’ a = 0) : add_order_of a ≀ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_add_iff_nsmul_eq_zero) @[to_additive add_order_of_le_of_nsmul_eq_zero] lemma order_of_le_of_pow_eq_one (hn : 0 < n) (h : x ^ n = 1) : order_of x ≀ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_mul_iff_pow_eq_one) @[simp] lemma order_of_one : order_of (1 : G) = 1 := by rw [order_of, one_mul_eq_id, minimal_period_id] @[simp] lemma add_order_of_zero : add_order_of (0 : A) = 1 := by simp only [←order_of_of_add_eq_add_order_of, order_of_one, of_add_zero] attribute [to_additive add_order_of_zero] order_of_one @[simp] lemma order_of_eq_one_iff : order_of x = 1 ↔ x = 1 := by rw [order_of, is_fixed_point_iff_minimal_period_eq_one, is_fixed_pt, mul_one] @[simp] lemma add_order_of_eq_one_iff : add_order_of a = 1 ↔ a = 0 := by simp [← order_of_of_add_eq_add_order_of] attribute [to_additive add_order_of_eq_one_iff] order_of_eq_one_iff lemma pow_eq_mod_order_of {n : β„•} : x ^ n = x ^ (n % order_of x) := calc x ^ n = x ^ (n % order_of x + order_of x * (n / order_of x)) : by rw [nat.mod_add_div] ... = x ^ (n % order_of x) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma nsmul_eq_mod_add_order_of {n : β„•} : n β€’ a = (n % add_order_of a) β€’ a := begin apply multiplicative.of_add.injective, rw [← order_of_of_add_eq_add_order_of, of_add_nsmul, of_add_nsmul, pow_eq_mod_order_of], end attribute [to_additive nsmul_eq_mod_add_order_of] pow_eq_mod_order_of lemma order_of_dvd_of_pow_eq_one (h : x ^ n = 1) : order_of x ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_mul_iff_pow_eq_one _).mpr h) lemma add_order_of_dvd_of_nsmul_eq_zero (h : n β€’ a = 0) : add_order_of a ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_add_iff_nsmul_eq_zero _).mpr h) attribute [to_additive add_order_of_dvd_of_nsmul_eq_zero] order_of_dvd_of_pow_eq_one lemma add_order_of_dvd_iff_nsmul_eq_zero {n : β„•} : add_order_of a ∣ n ↔ n β€’ a = 0 := ⟨λ h, by rw [nsmul_eq_mod_add_order_of, nat.mod_eq_zero_of_dvd h, zero_nsmul], add_order_of_dvd_of_nsmul_eq_zero⟩ @[to_additive add_order_of_dvd_iff_nsmul_eq_zero] lemma order_of_dvd_iff_pow_eq_one {n : β„•} : order_of x ∣ n ↔ x ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ lemma exists_pow_eq_self_of_coprime (h : n.coprime (order_of x)) : βˆƒ m : β„•, (x ^ n) ^ m = x := begin by_cases h0 : order_of x = 0, { rw [h0, coprime_zero_right] at h, exact ⟨1, by rw [h, pow_one, pow_one]⟩ }, by_cases h1 : order_of x = 1, { exact ⟨0, by rw [order_of_eq_one_iff.mp h1, one_pow, one_pow]⟩ }, obtain ⟨m, hm⟩ := exists_mul_mod_eq_one_of_coprime h (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, h1⟩), exact ⟨m, by rw [←pow_mul, pow_eq_mod_order_of, hm, pow_one]⟩, end lemma exists_nsmul_eq_self_of_coprime (a : A) (h : coprime n (add_order_of a)) : βˆƒ m : β„•, m β€’ (n β€’ a) = a := begin change n.coprime (order_of (multiplicative.of_add a)) at h, exact exists_pow_eq_self_of_coprime h, end attribute [to_additive exists_nsmul_eq_self_of_coprime] exists_pow_eq_self_of_coprime lemma add_order_of_eq_add_order_of_iff {B : Type*} [add_monoid B] {b : B} : add_order_of a = add_order_of b ↔ βˆ€ n : β„•, n β€’ a = 0 ↔ n β€’ b = 0 := begin simp_rw ← add_order_of_dvd_iff_nsmul_eq_zero, exact ⟨λ h n, by rw h, Ξ» h, nat.dvd_antisymm ((h _).mpr (dvd_refl _)) ((h _).mp (dvd_refl _))⟩, end @[to_additive add_order_of_eq_add_order_of_iff] lemma order_of_eq_order_of_iff {H : Type*} [monoid H] {y : H} : order_of x = order_of y ↔ βˆ€ n : β„•, x ^ n = 1 ↔ y ^ n = 1 := by simp_rw [← is_periodic_pt_mul_iff_pow_eq_one, ← minimal_period_eq_minimal_period_iff, order_of] lemma add_order_of_injective {B : Type*} [add_monoid B] (f : A β†’+ B) (hf : function.injective f) (a : A) : add_order_of (f a) = add_order_of a := by simp_rw [add_order_of_eq_add_order_of_iff, ←f.map_nsmul, ←f.map_zero, hf.eq_iff, iff_self, forall_const] @[to_additive add_order_of_injective] lemma order_of_injective {H : Type*} [monoid H] (f : G β†’* H) (hf : function.injective f) (x : G) : order_of (f x) = order_of x := by simp_rw [order_of_eq_order_of_iff, ←f.map_pow, ←f.map_one, hf.eq_iff, iff_self, forall_const] @[simp, norm_cast, to_additive] lemma order_of_submonoid {H : submonoid G} (y : H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y variables (x) lemma order_of_pow' (h : n β‰  0) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd h, simp only [order_of, mul_left_iterate], end variables (a) lemma add_order_of_nsmul' (h : n β‰  0) : add_order_of (n β€’ a) = add_order_of a / gcd (add_order_of a) n := by simpa [← order_of_of_add_eq_add_order_of, of_add_nsmul] using order_of_pow' _ h attribute [to_additive add_order_of_nsmul'] order_of_pow' variable (n) lemma order_of_pow'' (h : is_of_fin_order x) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd' h, simp only [order_of, mul_left_iterate], end lemma add_order_of_nsmul'' (h : is_of_fin_add_order a) : add_order_of (n β€’ a) = add_order_of a / gcd (add_order_of a) n := by simp [← order_of_of_add_eq_add_order_of, of_add_nsmul, order_of_pow'' _ n (is_of_fin_order_of_add_iff.mpr h)] attribute [to_additive add_order_of_nsmul''] order_of_pow'' section p_prime variables {a x n} {p : β„•} [hp : fact p.prime] include hp lemma add_order_of_eq_prime (hg : p β€’ a = 0) (hg1 : a β‰  0) : add_order_of a = p := minimal_period_eq_prime ((is_periodic_pt_add_iff_nsmul_eq_zero _).mpr hg) (by rwa [is_fixed_pt, add_zero]) @[to_additive add_order_of_eq_prime] lemma order_of_eq_prime (hg : x ^ p = 1) (hg1 : x β‰  1) : order_of x = p := minimal_period_eq_prime ((is_periodic_pt_mul_iff_pow_eq_one _).mpr hg) (by rwa [is_fixed_pt, mul_one]) lemma add_order_of_eq_prime_pow (hnot : Β¬ (p ^ n) β€’ a = 0) (hfin : (p ^ (n + 1)) β€’ a = 0) : add_order_of a = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_add_iff_nsmul_eq_zero, end @[to_additive add_order_of_eq_prime_pow] lemma order_of_eq_prime_pow (hnot : Β¬ x ^ p ^ n = 1) (hfin : x ^ p ^ (n + 1) = 1) : order_of x = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_mul_iff_pow_eq_one, end omit hp -- An example on how to determine the order of an element of a finite group. example : order_of (-1 : units β„€) = 2 := begin haveI : fact (prime 2) := ⟨prime_two⟩, exact order_of_eq_prime (int.units_mul_self _) dec_trivial, end end p_prime end monoid_add_monoid section cancel_monoid variables [left_cancel_monoid G] (x) variables [add_left_cancel_monoid A] (a) lemma pow_injective_aux (h : n ≀ m) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := by_contradiction $ assume ne : n β‰  m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have hβ‚‚ : m = n + (m - n) := (nat.add_sub_of_le h).symm, have h₃ : x ^ (m - n) = 1, by { rw [hβ‚‚, pow_add] at eq, apply mul_left_cancel, convert eq.symm, exact mul_one (x ^ n) }, have le : order_of x ≀ m - n, from order_of_le_of_pow_eq_one h₁ h₃, have lt : m - n < order_of x, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (le.trans_lt lt) -- TODO: This lemma was originally private, but this doesn't seem to work with `to_additive`, -- therefore the private got removed. lemma nsmul_injective_aux {n m : β„•} (h : n ≀ m) (hm : m < add_order_of a) (eq : n β€’ a = m β€’ a) : n = m := begin apply_fun multiplicative.of_add at eq, rw [of_add_nsmul, of_add_nsmul] at eq, rw ← order_of_of_add_eq_add_order_of at hm, exact pow_injective_aux (multiplicative.of_add a) h hm eq, end attribute [to_additive nsmul_injective_aux] pow_injective_aux lemma nsmul_injective_of_lt_add_order_of {n m : β„•} (hn : n < add_order_of a) (hm : m < add_order_of a) (eq : n β€’ a = m β€’ a) : n = m := (le_total n m).elim (assume h, nsmul_injective_aux a h hm eq) (assume h, (nsmul_injective_aux a h hn eq.symm).symm) @[to_additive nsmul_injective_of_lt_add_order_of] lemma pow_injective_of_lt_order_of (hn : n < order_of x) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux x h hm eq) (assume h, (pow_injective_aux x h hn eq.symm).symm) end cancel_monoid section group variables [group G] [add_group A] {x a} {i : β„€} @[to_additive add_order_of_dvd_iff_gsmul_eq_zero] lemma order_of_dvd_iff_gpow_eq_one : (order_of x : β„€) ∣ i ↔ x ^ i = 1 := begin rcases int.eq_coe_or_neg i with ⟨i, rfl|rfl⟩, { rw [int.coe_nat_dvd, order_of_dvd_iff_pow_eq_one, gpow_coe_nat] }, { rw [dvd_neg, int.coe_nat_dvd, gpow_neg, inv_eq_one, gpow_coe_nat, order_of_dvd_iff_pow_eq_one] } end @[simp, norm_cast, to_additive] lemma order_of_subgroup {H : subgroup G} (y: H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y lemma gpow_eq_mod_order_of : x ^ i = x ^ (i % order_of x) := calc x ^ i = x ^ (i % order_of x + order_of x * (i / order_of x)) : by rw [int.mod_add_div] ... = x ^ (i % order_of x) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma gsmul_eq_mod_add_order_of : i β€’ a = (i % add_order_of a) β€’ a := begin apply multiplicative.of_add.injective, simp [of_add_gsmul, gpow_eq_mod_order_of], end attribute [to_additive gsmul_eq_mod_add_order_of] gpow_eq_mod_order_of @[to_additive add_order_of_eq_zero_iff] lemma order_of_eq_zero_iff : order_of x = 0 ↔ Β¬ is_of_fin_order x := ⟨λ h H, (order_of_pos' H).ne' h, order_of_eq_zero⟩ @[to_additive nsmul_inj_iff_of_add_order_of_eq_zero] lemma pow_inj_iff_of_order_of_eq_zero (h : order_of x = 0) {n m : β„•} : x ^ n = x ^ m ↔ n = m := begin by_cases hx : x = 1, { rw [←order_of_eq_one_iff, h] at hx, contradiction }, rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one] at h, push_neg at h, induction n with n IH generalizing m, { cases m, { simp }, { simpa [eq_comm] using h m.succ m.zero_lt_succ } }, { cases m, { simpa using h n.succ n.zero_lt_succ }, { simp [pow_succ, IH] } } end lemma pow_inj_mod {n m : β„•} : x ^ n = x ^ m ↔ n % order_of x = m % order_of x := begin cases (order_of x).zero_le.eq_or_lt with hx hx, { simp [pow_inj_iff_of_order_of_eq_zero, hx.symm] }, rw [pow_eq_mod_order_of, @pow_eq_mod_order_of _ _ _ m], exact ⟨pow_injective_of_lt_order_of _ (nat.mod_lt _ hx) (nat.mod_lt _ hx), Ξ» h, congr_arg _ h⟩ end lemma nsmul_inj_mod {n m : β„•} : n β€’ a = m β€’ a ↔ n % add_order_of a = m % add_order_of a := begin cases (add_order_of a).zero_le.eq_or_lt with hx hx, { simp [nsmul_inj_iff_of_add_order_of_eq_zero, hx.symm] }, rw [nsmul_eq_mod_add_order_of, @nsmul_eq_mod_add_order_of _ _ _ m], refine ⟨nsmul_injective_of_lt_add_order_of a (nat.mod_lt n hx) (nat.mod_lt m hx), Ξ» h, _⟩, rw h end attribute [to_additive nsmul_inj_mod] pow_inj_mod end group section fintype variables [fintype G] [fintype A] section finite_monoid variables [monoid G] [add_monoid A] open_locale big_operators lemma sum_card_add_order_of_eq_card_nsmul_eq_zero [decidable_eq A] (hn : 0 < n) : βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» a : A, add_order_of a = m)).card = (finset.univ.filter (Ξ» a : A, n β€’ a = 0)).card := calc βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» a : A, add_order_of a = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume a, suffices : add_order_of a ≀ n ∧ add_order_of a ∣ n ↔ n β€’ a = 0, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, mul_comm, mul_nsmul, add_order_of_nsmul_eq_zero, nsmul_zero], Ξ» h, ⟨add_order_of_le_of_nsmul_eq_zero hn h, add_order_of_dvd_of_nsmul_eq_zero h⟩⟩ end)) @[to_additive sum_card_add_order_of_eq_card_nsmul_eq_zero] lemma sum_card_order_of_eq_card_pow_eq_one [decidable_eq G] (hn : 0 < n) : βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» x : G, order_of x = m)).card = (finset.univ.filter (Ξ» x : G, x ^ n = 1)).card := calc βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» x : G, order_of x = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume x, suffices : order_of x ≀ n ∧ order_of x ∣ n ↔ x ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, one_pow], Ξ» h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) end finite_monoid section finite_cancel_monoid -- TODO: Of course everything also works for right_cancel_monoids. variables [left_cancel_monoid G] [add_left_cancel_monoid A] -- TODO: Use this to show that a finite left cancellative monoid is a group. lemma exists_pow_eq_one (x : G) : is_of_fin_order x := begin refine (is_of_fin_order_iff_pow_eq_one _).mpr _, obtain ⟨i, j, a_eq, ne⟩ : βˆƒ(i j : β„•), x ^ i = x ^ j ∧ i β‰  j := by simpa only [not_forall, exists_prop] using (not_injective_infinite_fintype (Ξ»i:β„•, x^i)), wlog h'' : j ≀ i, refine ⟨i - j, nat.sub_pos_of_lt (lt_of_le_of_ne h'' ne.symm), mul_right_injective (x^j) _⟩, rw [mul_one, ← pow_add, ← a_eq, nat.add_sub_cancel' h''], end lemma exists_nsmul_eq_zero (a : A) : is_of_fin_add_order a := begin rcases exists_pow_eq_one (multiplicative.of_add a) with ⟨i, hi1, hi2⟩, refine ⟨i, hi1, multiplicative.of_add.injective _⟩, rw [add_left_iterate, of_add_zero, of_add_eq_one, add_zero], exact (is_periodic_pt_mul_iff_pow_eq_one (multiplicative.of_add a)).mp hi2, end attribute [to_additive exists_nsmul_eq_zero] exists_pow_eq_one lemma add_order_of_le_card_univ : add_order_of a ≀ fintype.card A := finset.le_card_of_inj_on_range (β€’ a) (assume n _, finset.mem_univ _) (assume i hi j hj, nsmul_injective_of_lt_add_order_of a hi hj) @[to_additive add_order_of_le_card_univ] lemma order_of_le_card_univ : order_of x ≀ fintype.card G := finset.le_card_of_inj_on_range ((^) x) (assume n _, finset.mem_univ _) (assume i hi j hj, pow_injective_of_lt_order_of x hi hj) /-- This is the same as `add_order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative additive monoid.-/ lemma add_order_of_pos (a : A) : 0 < add_order_of a := add_order_of_pos' (exists_nsmul_eq_zero _) /-- This is the same as `order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative monoid.-/ @[to_additive add_order_of_pos] lemma order_of_pos (x : G) : 0 < order_of x := order_of_pos' (exists_pow_eq_one x) open nat /-- This is the same as `add_order_of_nsmul'` and `add_order_of_nsmul` but with one assumption less which is automatic in the case of a finite cancellative additive monoid. -/ lemma add_order_of_nsmul (a : A) : add_order_of (n β€’ a) = add_order_of a / gcd (add_order_of a) n := add_order_of_nsmul'' _ _ (exists_nsmul_eq_zero _) /-- This is the same as `order_of_pow'` and `order_of_pow''` but with one assumption less which is automatic in the case of a finite cancellative monoid.-/ @[to_additive add_order_of_nsmul] lemma order_of_pow (x : G) : order_of (x ^ n) = order_of x / gcd (order_of x) n := order_of_pow'' _ _ (exists_pow_eq_one _) lemma mem_multiples_iff_mem_range_add_order_of [decidable_eq A] : b ∈ add_submonoid.multiples a ↔ b ∈ (finset.range (add_order_of a)).image ((β€’ a) : β„• β†’ A) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (add_order_of_pos a) (assume i, nsmul_eq_mod_add_order_of.symm) @[to_additive mem_multiples_iff_mem_range_add_order_of] lemma mem_powers_iff_mem_range_order_of [decidable_eq G] : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : β„• β†’ G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (order_of_pos x) (assume i, pow_eq_mod_order_of.symm) noncomputable instance decidable_multiples [decidable_eq A] : decidable_pred (∈ add_submonoid.multiples a) := begin assume b, apply decidable_of_iff' (b ∈ (finset.range (add_order_of a)).image (β€’ a)), exact mem_multiples_iff_mem_range_add_order_of, end @[to_additive decidable_multiples] noncomputable instance decidable_powers [decidable_eq G] : decidable_pred (∈ submonoid.powers x) := begin assume y, apply decidable_of_iff' (y ∈ (finset.range (order_of x)).image ((^) x)), exact mem_powers_iff_mem_range_order_of end /-- The equivalence between `fin (order_of x)` and `submonoid.powers x`, sending `i` to `x ^ i`. -/ noncomputable def fin_equiv_powers (x : G) : fin (order_of x) ≃ (submonoid.powers x : set G) := equiv.of_bijective (Ξ» n, ⟨x ^ ↑n, ⟨n, rfl⟩⟩) ⟨λ ⟨i, hi⟩ ⟨j, hj⟩ ij, subtype.mk_eq_mk.2 (pow_injective_of_lt_order_of x hi hj (subtype.mk_eq_mk.1 ij)), Ξ» ⟨_, i, rfl⟩, ⟨⟨i % order_of x, mod_lt i (order_of_pos x)⟩, subtype.eq pow_eq_mod_order_of.symm⟩⟩ /-- The equivalence between `fin (add_order_of a)` and `add_submonoid.multiples a`, sending `i` to `i β€’ a`."-/ noncomputable def fin_equiv_multiples (a : A) : fin (add_order_of a) ≃ (add_submonoid.multiples a : set A) := fin_equiv_powers (multiplicative.of_add a) attribute [to_additive fin_equiv_multiples] fin_equiv_powers @[simp] lemma fin_equiv_powers_apply {x : G} {n : fin (order_of x)} : fin_equiv_powers x n = ⟨x ^ ↑n, n, rfl⟩ := rfl @[simp] lemma fin_equiv_multiples_apply {a : A} {n : fin (add_order_of a)} : fin_equiv_multiples a n = ⟨nsmul ↑n a, n, rfl⟩ := rfl attribute [to_additive fin_equiv_multiples_apply] fin_equiv_powers_apply @[simp] lemma fin_equiv_powers_symm_apply (x : G) (n : β„•) {hn : βˆƒ (m : β„•), x ^ m = x ^ n} : ((fin_equiv_powers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by rw [equiv.symm_apply_eq, fin_equiv_powers_apply, subtype.mk_eq_mk, pow_eq_mod_order_of, fin.coe_mk] @[simp] lemma fin_equiv_multiples_symm_apply (a : A) (n : β„•) {hn : βˆƒ (m : β„•), m β€’ a = n β€’ a} : ((fin_equiv_multiples a).symm ⟨n β€’ a, hn⟩) = ⟨n % add_order_of a, nat.mod_lt _ (add_order_of_pos a)⟩ := fin_equiv_powers_symm_apply (multiplicative.of_add a) n attribute [to_additive fin_equiv_multiples_symm_apply] fin_equiv_powers_symm_apply /-- The equivalence between `submonoid.powers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ noncomputable def powers_equiv_powers (h : order_of x = order_of y) : (submonoid.powers x : set G) ≃ (submonoid.powers y : set G) := (fin_equiv_powers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_powers y)) /-- The equivalence between `submonoid.multiples` of two elements `a, b` of the same additive order, mapping `i β€’ a` to `i β€’ b`. -/ noncomputable def multiples_equiv_multiples (h : add_order_of a = add_order_of b) : (add_submonoid.multiples a : set A) ≃ (add_submonoid.multiples b : set A) := (fin_equiv_multiples a).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_multiples b)) attribute [to_additive multiples_equiv_multiples] powers_equiv_powers @[simp] lemma powers_equiv_powers_apply (h : order_of x = order_of y) (n : β„•) : powers_equiv_powers h ⟨x ^ n, n, rfl⟩ = ⟨y ^ n, n, rfl⟩ := begin rw [powers_equiv_powers, equiv.trans_apply, equiv.trans_apply, fin_equiv_powers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_powers_symm_apply], simp [h] end @[simp] lemma multiples_equiv_multiples_apply (h : add_order_of a = add_order_of b) (n : β„•) : multiples_equiv_multiples h ⟨n β€’ a, n, rfl⟩ = ⟨n β€’ b, n, rfl⟩ := powers_equiv_powers_apply h n attribute [to_additive multiples_equiv_multiples_apply] powers_equiv_powers_apply lemma order_eq_card_powers [decidable_eq G] : order_of x = fintype.card (submonoid.powers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_powers x⟩) lemma add_order_of_eq_card_multiples [decidable_eq A] : add_order_of a = fintype.card (add_submonoid.multiples a : set A) := (fintype.card_fin (add_order_of a)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_multiples a⟩) attribute [to_additive add_order_of_eq_card_multiples] order_eq_card_powers end finite_cancel_monoid section finite_group variables [group G] [add_group A] lemma exists_gpow_eq_one (x : G) : βˆƒ (i : β„€) (H : i β‰  0), x ^ (i : β„€) = 1 := --lemma exists_gpow_eq_one (a : Ξ±) : βˆƒ (i : β„€) (H : i β‰  0), a ^ (i : β„€) = 1 := begin rcases exists_pow_eq_one x with ⟨w, hw1, hw2⟩, refine ⟨w, int.coe_nat_ne_zero.mpr (ne_of_gt hw1), _⟩, rw gpow_coe_nat, exact (is_periodic_pt_mul_iff_pow_eq_one _).mp hw2, end lemma exists_gsmul_eq_zero (a : A) : βˆƒ (i : β„€) (H : i β‰  0), i β€’ a = 0 := @exists_gpow_eq_one (multiplicative A) _ _ a attribute [to_additive] exists_gpow_eq_one lemma mem_multiples_iff_mem_gmultiples : b ∈ add_submonoid.multiples a ↔ b ∈ add_subgroup.gmultiples a := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, Ξ» ⟨i, hi⟩, ⟨(i % add_order_of a).nat_abs, by { simp only [nsmul_eq_smul] at hi ⊒, rwa [← gsmul_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (add_order_of_pos a))), ← gsmul_eq_mod_add_order_of] } ⟩⟩ open subgroup @[to_additive mem_multiples_iff_mem_gmultiples] lemma mem_powers_iff_mem_gpowers : y ∈ submonoid.powers x ↔ y ∈ gpowers x := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, Ξ» ⟨i, hi⟩, ⟨(i % order_of x).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos x))), ← gpow_eq_mod_order_of]⟩⟩ lemma multiples_eq_gmultiples (a : A) : (add_submonoid.multiples a : set A) = add_subgroup.gmultiples a := set.ext $ Ξ» y, mem_multiples_iff_mem_gmultiples @[to_additive multiples_eq_gmultiples] lemma powers_eq_gpowers (x : G) : (submonoid.powers x : set G) = gpowers x := set.ext $ Ξ» x, mem_powers_iff_mem_gpowers lemma mem_gmultiples_iff_mem_range_add_order_of [decidable_eq A] : b ∈ add_subgroup.gmultiples a ↔ b ∈ (finset.range (add_order_of a)).image (β€’ a) := by rw [← mem_multiples_iff_mem_gmultiples, mem_multiples_iff_mem_range_add_order_of] @[to_additive mem_gmultiples_iff_mem_range_add_order_of] lemma mem_gpowers_iff_mem_range_order_of [decidable_eq G] : y ∈ subgroup.gpowers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : β„• β†’ G) := by rw [← mem_powers_iff_mem_gpowers, mem_powers_iff_mem_range_order_of] noncomputable instance decidable_gmultiples [decidable_eq A] : decidable_pred (∈ add_subgroup.gmultiples a) := begin simp_rw ←set_like.mem_coe, rw ← multiples_eq_gmultiples, exact decidable_multiples, end @[to_additive decidable_gmultiples] noncomputable instance decidable_gpowers [decidable_eq G] : decidable_pred (∈ subgroup.gpowers x) := begin simp_rw ←set_like.mem_coe, rw ← powers_eq_gpowers, exact decidable_powers, end /-- The equivalence between `fin (order_of x)` and `subgroup.gpowers x`, sending `i` to `x ^ i`. -/ noncomputable def fin_equiv_gpowers (x : G) : fin (order_of x) ≃ (subgroup.gpowers x : set G) := (fin_equiv_powers x).trans (equiv.set.of_eq (powers_eq_gpowers x)) /-- The equivalence between `fin (add_order_of a)` and `subgroup.gmultiples a`, sending `i` to `i β€’ a`. -/ noncomputable def fin_equiv_gmultiples (a : A) : fin (add_order_of a) ≃ (add_subgroup.gmultiples a : set A) := fin_equiv_gpowers (multiplicative.of_add a) attribute [to_additive fin_equiv_gmultiples] fin_equiv_gpowers @[simp] lemma fin_equiv_gpowers_apply {n : fin (order_of x)} : fin_equiv_gpowers x n = ⟨x ^ (n : β„•), n, gpow_coe_nat x n⟩ := rfl @[simp] lemma fin_equiv_gmultiples_apply {n : fin (add_order_of a)} : fin_equiv_gmultiples a n = ⟨(n : β„•) β€’ a, n, gsmul_coe_nat a n⟩ := fin_equiv_gpowers_apply attribute [to_additive fin_equiv_gmultiples_apply] fin_equiv_gpowers_apply @[simp] lemma fin_equiv_gpowers_symm_apply (x : G) (n : β„•) {hn : βˆƒ (m : β„€), x ^ m = x ^ n} : ((fin_equiv_gpowers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by { rw [fin_equiv_gpowers, equiv.symm_trans_apply, equiv.set.of_eq_symm_apply], exact fin_equiv_powers_symm_apply x n } @[simp] lemma fin_equiv_gmultiples_symm_apply (a : A) (n : β„•) {hn : βˆƒ (m : β„€), m β€’ a = n β€’ a} : ((fin_equiv_gmultiples a).symm ⟨n β€’ a, hn⟩) = ⟨n % add_order_of a, nat.mod_lt _ (add_order_of_pos a)⟩ := fin_equiv_gpowers_symm_apply (multiplicative.of_add a) n attribute [to_additive fin_equiv_gmultiples_symm_apply] fin_equiv_gpowers_symm_apply /-- The equivalence between `subgroup.gpowers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ noncomputable def gpowers_equiv_gpowers (h : order_of x = order_of y) : (subgroup.gpowers x : set G) ≃ (subgroup.gpowers y : set G) := (fin_equiv_gpowers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_gpowers y)) /-- The equivalence between `subgroup.gmultiples` of two elements `a, b` of the same additive order, mapping `i β€’ a` to `i β€’ b`. -/ noncomputable def gmultiples_equiv_gmultiples (h : add_order_of a = add_order_of b) : (add_subgroup.gmultiples a : set A) ≃ (add_subgroup.gmultiples b : set A) := (fin_equiv_gmultiples a).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_gmultiples b)) attribute [to_additive gmultiples_equiv_gmultiples] gpowers_equiv_gpowers @[simp] lemma gpowers_equiv_gpowers_apply (h : order_of x = order_of y) (n : β„•) : gpowers_equiv_gpowers h ⟨x ^ n, n, gpow_coe_nat x n⟩ = ⟨y ^ n, n, gpow_coe_nat y n⟩ := begin rw [gpowers_equiv_gpowers, equiv.trans_apply, equiv.trans_apply, fin_equiv_gpowers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_gpowers_symm_apply], simp [h] end @[simp] lemma gmultiples_equiv_gmultiples_apply (h : add_order_of a = add_order_of b) (n : β„•) : gmultiples_equiv_gmultiples h ⟨n β€’ a, n, gsmul_coe_nat a n⟩ = ⟨n β€’ b, n, gsmul_coe_nat b n⟩ := gpowers_equiv_gpowers_apply h n attribute [to_additive gmultiples_equiv_gmultiples_apply] gpowers_equiv_gpowers_apply lemma order_eq_card_gpowers [decidable_eq G] : order_of x = fintype.card (subgroup.gpowers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_gpowers x⟩) lemma add_order_eq_card_gmultiples [decidable_eq A] : add_order_of a = fintype.card (add_subgroup.gmultiples a : set A) := (fintype.card_fin (add_order_of a)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_gmultiples a⟩) attribute [to_additive add_order_eq_card_gmultiples] order_eq_card_gpowers open quotient_group /- TODO: use cardinal theory, introduce `card : set G β†’ β„•`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of x ∣ fintype.card G := begin classical, have ft_prod : fintype (quotient (gpowers x) Γ— (gpowers x)), from fintype.of_equiv G group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers x), from @fintype.prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers x)), from @fintype.prod_left _ _ _ ft_prod ⟨⟨1, (gpowers x).one_mem⟩⟩, have eq₁ : fintype.card G = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card G = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eqβ‚‚ : order_of x = @fintype.card _ ft_s, from calc order_of x = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, exact dvd.intro (@fintype.card (quotient (subgroup.gpowers x)) ft_cosets) (by rw [eq₁, eqβ‚‚, mul_comm]) end lemma add_order_of_dvd_card_univ : add_order_of a ∣ fintype.card A := begin rw ← order_of_of_add_eq_add_order_of, exact order_of_dvd_card_univ, end attribute [to_additive add_order_of_dvd_card_univ] order_of_dvd_card_univ @[simp] lemma pow_card_eq_one : x ^ fintype.card G = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ x _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] @[simp] lemma card_nsmul_eq_zero {a : A} : fintype.card A β€’ a = 0 := begin apply multiplicative.of_add.injective, rw [of_add_nsmul, of_add_zero], exact pow_card_eq_one, end @[to_additive nsmul_eq_mod_card] lemma pow_eq_mod_card (n : β„•) : x ^ n = x ^ (n % fintype.card G) := by rw [pow_eq_mod_order_of, ←nat.mod_mod_of_dvd n order_of_dvd_card_univ, ← pow_eq_mod_order_of] @[to_additive] lemma gpow_eq_mod_card (n : β„€) : x ^ n = x ^ (n % fintype.card G) := by by rw [gpow_eq_mod_order_of, ← int.mod_mod_of_dvd n (int.coe_nat_dvd.2 order_of_dvd_card_univ), ← gpow_eq_mod_order_of] attribute [to_additive card_nsmul_eq_zero] pow_card_eq_one /-- If `gcd(|G|,n)=1` then the `n`th power map is a bijection -/ @[simps] def pow_coprime (h : nat.coprime (fintype.card G) n) : G ≃ G := { to_fun := Ξ» g, g ^ n, inv_fun := Ξ» g, g ^ (nat.gcd_b (fintype.card G) n), left_inv := Ξ» g, by { have key : g ^ _ = g ^ _ := congr_arg (Ξ» n : β„€, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [gpow_add, gpow_mul, gpow_mul, gpow_coe_nat, gpow_coe_nat, gpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_gpow, one_mul, eq_comm] at key }, right_inv := Ξ» g, by { have key : g ^ _ = g ^ _ := congr_arg (Ξ» n : β„€, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [gpow_add, gpow_mul, gpow_mul', gpow_coe_nat, gpow_coe_nat, gpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_gpow, one_mul, eq_comm] at key } } @[simp] lemma pow_coprime_one (h : nat.coprime (fintype.card G) n) : pow_coprime h 1 = 1 := one_pow n @[simp] lemma pow_coprime_inv (h : nat.coprime (fintype.card G) n) {g : G} : pow_coprime h g⁻¹ = (pow_coprime h g)⁻¹ := inv_pow g n lemma inf_eq_bot_of_coprime {G : Type*} [group G] {H K : subgroup G} [fintype H] [fintype K] (h : nat.coprime (fintype.card H) (fintype.card K)) : H βŠ“ K = βŠ₯ := begin refine (H βŠ“ K).eq_bot_iff_forall.mpr (Ξ» x hx, _), rw [←order_of_eq_one_iff, ←nat.dvd_one, ←h.gcd_eq_one, nat.dvd_gcd_iff], exact ⟨(congr_arg (∣ fintype.card H) (order_of_subgroup ⟨x, hx.1⟩)).mpr order_of_dvd_card_univ, (congr_arg (∣ fintype.card K) (order_of_subgroup ⟨x, hx.2⟩)).mpr order_of_dvd_card_univ⟩, end variable (a) lemma image_range_add_order_of [decidable_eq A] : finset.image (Ξ» i, i β€’ a) (finset.range (add_order_of a)) = (add_subgroup.gmultiples a : set A).to_finset := by {ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_gmultiples_iff_mem_range_add_order_of] } /-- TODO: Generalise to `submonoid.powers`.-/ @[to_additive image_range_add_order_of] lemma image_range_order_of [decidable_eq G] : finset.image (Ξ» i, x ^ i) (finset.range (order_of x)) = (gpowers x : set G).to_finset := by { ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_gpowers_iff_mem_range_order_of] } lemma gcd_nsmul_card_eq_zero_iff : n β€’ a = 0 ↔ (gcd n (fintype.card A)) β€’ a = 0 := ⟨λ h, gcd_nsmul_eq_zero _ h $ card_nsmul_eq_zero, Ξ» h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card A) in by rw [hm, mul_comm, mul_nsmul, h, nsmul_zero]⟩ /-- TODO: Generalise to `finite_cancel_monoid`. -/ @[to_additive gcd_nsmul_card_eq_zero_iff] lemma pow_gcd_card_eq_one_iff : x ^ n = 1 ↔ x ^ (gcd n (fintype.card G)) = 1 := ⟨λ h, pow_gcd_eq_one _ h $ pow_card_eq_one, Ξ» h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card G) in by rw [hm, pow_mul, h, one_pow]⟩ end finite_group end fintype section pow_is_subgroup /-- A nonempty idempotent subset of a finite cancellative monoid is a submonoid -/ def submonoid_of_idempotent {M : Type*} [left_cancel_monoid M] [fintype M] (S : set M) (hS1 : S.nonempty) (hS2 : S * S = S) : submonoid M := have pow_mem : βˆ€ a : M, a ∈ S β†’ βˆ€ n : β„•, a ^ (n + 1) ∈ S := Ξ» a ha, nat.rec (by rwa [zero_add, pow_one]) (Ξ» n ih, (congr_arg2 (∈) (pow_succ a (n + 1)).symm hS2).mp (set.mul_mem_mul ha ih)), { carrier := S, one_mem' := by { obtain ⟨a, ha⟩ := hS1, rw [←pow_order_of_eq_one a, ←nat.sub_add_cancel (order_of_pos a)], exact pow_mem a ha (order_of a - 1) }, mul_mem' := Ξ» a b ha hb, (congr_arg2 (∈) rfl hS2).mp (set.mul_mem_mul ha hb) } /-- A nonempty idempotent subset of a finite group is a subgroup -/ def subgroup_of_idempotent {G : Type*} [group G] [fintype G] (S : set G) (hS1 : S.nonempty) (hS2 : S * S = S) : subgroup G := { carrier := S, inv_mem' := Ξ» a ha, by { rw [←one_mul a⁻¹, ←pow_one a, ←pow_order_of_eq_one a, ←pow_sub a (order_of_pos a)], exact (submonoid_of_idempotent S hS1 hS2).pow_mem ha (order_of a - 1) }, .. submonoid_of_idempotent S hS1 hS2 } /-- If `S` is a nonempty subset of a finite group `G`, then `S ^ |G|` is a subgroup -/ def pow_card_subgroup {G : Type*} [group G] [fintype G] (S : set G) (hS : S.nonempty) : subgroup G := have one_mem : (1 : G) ∈ (S ^ fintype.card G) := by { obtain ⟨a, ha⟩ := hS, rw ← pow_card_eq_one, exact set.pow_mem_pow ha (fintype.card G) }, subgroup_of_idempotent (S ^ (fintype.card G)) ⟨1, one_mem⟩ begin classical, refine (set.eq_of_subset_of_card_le (Ξ» b hb, (congr_arg (∈ _) (one_mul b)).mp (set.mul_mem_mul one_mem hb)) (ge_of_eq _)).symm, change _ = fintype.card (_ * _ : set G), rw [←pow_add, group.card_pow_eq_card_pow_card_univ S (fintype.card G) le_rfl, group.card_pow_eq_card_pow_card_univ S (fintype.card G + fintype.card G) le_add_self], end end pow_is_subgroup
da5db5aef610190422a77ecb36653300c7c50d2d
bf532e3e865883a676110e756f800e0ddeb465be
/data/seq/wseq.lean
406290984c7118831fa66c218dea25b151b8352a
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,190
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.seq.seq data.seq.computation data.list.basic data.dlist 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 /-- 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] def is_finite (s : wseq Ξ±) : Prop := (to_list s).terminates instance to_list_terminates (s : wseq Ξ±) [h : is_finite s] : (to_list s).terminates := h /-- 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] def productive (s : wseq Ξ±) : Prop := βˆ€ n, (nth s n).terminates instance nth_terminates (s : wseq Ξ±) [h : productive s] : βˆ€ n, (nth s n).terminates := h instance head_terminates (s : wseq Ξ±) [h : productive s] : (head s).terminates := h 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 ~ := 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) : function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.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 (function.swap R) s2 s1 := begin refine ⟨function.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) : function.swap (lift_rel R) = lift_rel (function.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 : function.swap (lift_rel R) s2 s1), by rwa [lift_rel.swap, show function.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, _⟩, cases h with t h, cases h with 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, _⟩, cases h1.left ha with b hb, cases hb with 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 has_map.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 has_map.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 dsimp [tail], simp, rw [←monad.bind_pure_comp_eq_map, monad.bind_assoc], apply congr_arg, funext o, rcases o with _|⟨a, s⟩; apply (monad.pure_bind _ _).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, 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 cases (head_terminates_iff _).1 T with a h, simp [tail] at h, cases exists_of_mem_bind h with s' h1, cases h1 with h1 h2, unfold has_map.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 has_map.map at h, simp at h, cases exists_of_mem_bind h with t ht, cases ht with tm td, clear h, cases exists_of_mem_map tm with t' ht', cases ht' with 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, cases exists_of_mem_map h with o ho, cases ho with 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 induction e : computation.get (nth s (n + 1)), {trivial}, 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, { cases exists_of_mem_map h with o h, cases h with 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 cases (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, cases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ds dsm, cases dsm with dsm dse, rw ←dse, cases destruct_congr h with l r, cases l dsm with dt dtm, cases dtm with 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 _ _ (@has_map.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 has_map.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 := 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, cases h with l h, cases h with 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, cases h with l' h, cases h with 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 has_map.map, simp [option.map, option.bind, 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, funext o, cases o; 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; simp, { refl }, { refl }, { 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 [option.map, option.bind], { 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, cases h with s h, cases h with t h, rw [h.left, h.right], apply s.cases_on _ (Ξ» a s, _) (Ξ» s, _); simp; simp, { apply t.cases_on _ (Ξ» b t, _) (Ξ» t, _); simp; 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; 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 [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 (function.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, apply s.cases_on _ (Ξ» a s, _) (Ξ» s, _); simp [ret]; simp [ret], { refine ⟨_, ret_mem _, _⟩, simp }, { exact ⟨s, rfl, rfl⟩ } 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; simp, { apply wseq.cases_on S _ (Ξ» s S, _) (Ξ» S, _); simp; simp, { apply wseq.cases_on T _ (Ξ» s T, _) (Ξ» T, _); simp; 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; simp, { apply wseq.cases_on S _ (Ξ» s S, _) (Ξ» S, _); simp; 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; simp, { apply wseq.cases_on S _ (Ξ» s S, _) (Ξ» S, _); simp; simp, { apply wseq.cases_on SS _ (Ξ» S SS, _) (Ξ» SS, _); simp; 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 /- Unfortunately, wseq is not a 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 : monad wseq := { map := @map, pure := @ret, bind := @bind, id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end wseq
779b675fffdd1d3ad3b57de22b403a48d55a81e5
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/bounded_continuous_function.lean
89ab5ee3539c03600afc89b4bb411c0509fa8ab8
[ "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
22,117
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, Mario Carneiro -/ import analysis.normed_space.basic topology.metric_space.lipschitz /-! # Bounded continuous functions The type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ noncomputable theory open_locale topological_space classical open set filter metric universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (Ξ± : Type u) (Ξ² : Type v) [topological_space Ξ±] [metric_space Ξ²] : Type (max u v) := {f : Ξ± β†’ Ξ² // continuous f ∧ βˆƒC, βˆ€x y:Ξ±, dist (f x) (f y) ≀ C} local infixr ` →ᡇ `:25 := bounded_continuous_function namespace bounded_continuous_function section basics variables [topological_space Ξ±] [metric_space Ξ²] [metric_space Ξ³] variables {f g : Ξ± →ᡇ Ξ²} {x : Ξ±} {C : ℝ} instance : has_coe_to_fun (Ξ± →ᡇ Ξ²) := ⟨_, subtype.val⟩ lemma bounded_range : bounded (range f) := bounded_range_iff.2 f.2.2 /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact [compact_space Ξ±] (f : Ξ± β†’ Ξ²) (hf : continuous f) : Ξ± →ᡇ Ξ² := ⟨f, hf, bounded_range_iff.1 $ bounded_of_compact $ compact_range hf⟩ /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete [discrete_topology Ξ±] (f : Ξ± β†’ Ξ²) (hf : βˆƒC, βˆ€x y, dist (f x) (f y) ≀ C) : Ξ± →ᡇ Ξ² := ⟨f, continuous_of_discrete_topology, hf⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (Ξ± →ᡇ Ξ²) := ⟨λf g, Inf {C | C β‰₯ 0 ∧ βˆ€ x : Ξ±, dist (f x) (g x) ≀ C}⟩ lemma dist_eq : dist f g = Inf {C | C β‰₯ 0 ∧ βˆ€ x : Ξ±, dist (f x) (g x) ≀ C} := rfl lemma dist_set_exists : βˆƒ C, C β‰₯ 0 ∧ βˆ€ x : Ξ±, dist (f x) (g x) ≀ C := begin refine if h : nonempty Ξ± then _ else ⟨0, le_refl _, Ξ» x, h.elim ⟨x⟩⟩, cases h with x, rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : βˆ€ (x y : Ξ±), dist (f.val x) (f.val y) ≀ Cf -/ rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : βˆ€ (x y : Ξ±), dist (g.val x) (g.val y) ≀ Cg -/ let C := max 0 (dist (f x) (g x) + (Cf + Cg)), exact ⟨C, le_max_left _ _, Ξ» y, calc dist (f y) (g y) ≀ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _ ... ≀ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _ ... ≀ C : le_max_right _ _⟩ end /-- The pointwise distance is controlled by the distance between functions, by definition -/ lemma dist_coe_le_dist (x : Ξ±) : dist (f x) (g x) ≀ dist f g := le_cInf dist_set_exists $ Ξ»b hb, hb.2 x @[ext] lemma ext (H : βˆ€x, f x = g x) : f = g := subtype.eq $ by ext; apply H /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ private lemma dist_nonneg' : 0 ≀ dist f g := le_cInf dist_set_exists (Ξ» C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≀ C) : dist f g ≀ C ↔ βˆ€x:Ξ±, dist (f x) (g x) ≀ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, Ξ» H, cInf_le ⟨0, Ξ» C, and.left⟩ ⟨C0, H⟩⟩ /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty (e : Β¬ nonempty Ξ±) : dist f g = 0 := le_antisymm ((dist_le (le_refl _)).2 $ Ξ» x, e.elim ⟨x⟩) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance : metric_space (Ξ± →ᡇ Ξ²) := { dist_self := Ξ» f, le_antisymm ((dist_le (le_refl _)).2 $ Ξ» x, by simp) dist_nonneg', eq_of_dist_eq_zero := Ξ» f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg β–Έ dist_coe_le_dist _) dist_nonneg), dist_comm := Ξ» f g, by simp [dist_eq, dist_comm], dist_triangle := Ξ» f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ Ξ» x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } /-- Constant as a continuous bounded function. -/ def const (b : Ξ²) : Ξ± →ᡇ Ξ² := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩ /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited Ξ²] : inhabited (Ξ± →ᡇ Ξ²) := ⟨const (default Ξ²)⟩ /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval : continuous (Ξ» p : (Ξ± →ᡇ Ξ²) Γ— Ξ±, p.1 p.2) := continuous_iff'.2 $ Ξ» ⟨f, x⟩ Ξ΅ Ξ΅0, /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by Ξ΅/2 -/ have Hs : _ := continuous_iff'.1 f.2.1 x (Ξ΅/2) (half_pos Ξ΅0), mem_sets_of_superset (prod_mem_nhds_sets (ball_mem_nhds _ (half_pos Ξ΅0)) Hs) $ Ξ» ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x) ≀ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _ ... < Ξ΅/2 + Ξ΅/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) hy ... = Ξ΅ : add_halves _ /-- In particular, when `x` is fixed, `f β†’ f x` is continuous -/ theorem continuous_evalx {x : Ξ±} : continuous (Ξ» f : Ξ± →ᡇ Ξ², f x) := continuous_eval.comp (continuous_id.prod_mk continuous_const) /-- When `f` is fixed, `x β†’ f x` is also continuous, by definition -/ theorem continuous_evalf {f : Ξ± →ᡇ Ξ²} : continuous f := f.2.1 /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space Ξ²] : complete_space (Ξ± →ᡇ Ξ²) := complete_of_cauchy_seq_tendsto $ Ξ» (f : β„• β†’ Ξ± →ᡇ Ξ²) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := Ξ»x n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : βˆ€x, cauchy_seq (Ξ»n, f n x) := Ξ»x, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using Ξ»x, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : Ξ± β†’ Ξ², hF : βˆ€ (x : Ξ±), tendsto (Ξ» (n : β„•), f n x) at_top (𝓝 (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : βˆ€x N, dist (f N x) (F x) ≀ b N := Ξ» x N, le_of_tendsto (by simp) (tendsto_const_nhds.dist (hF x)) (filter.eventually_at_top.2 ⟨N, Ξ»n hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨F, _, _⟩, _⟩, { /- Check that `F` is continuous, as a uniform limit of continuous functions -/ have : tendsto_uniformly (Ξ»n x, f n x) F at_top, { refine metric.tendsto_uniformly_iff.2 (Ξ» Ξ΅ Ξ΅0, _), refine ((tendsto_order.1 b_lim).2 Ξ΅ Ξ΅0).mono (Ξ» n hn x, _), rw dist_comm, exact lt_of_le_of_lt (fF_bdd x n) hn }, exact this.continuous (Ξ»N, (f N).2.1) at_top_ne_bot }, { /- Check that `F` is bounded -/ rcases (f 0).2.2 with ⟨C, hC⟩, exact ⟨C + (b 0 + b 0), Ξ» x y, calc dist (F x) (F y) ≀ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≀ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (Ξ» _, dist_nonneg) _ b_lim), exact Ξ» N, (dist_le (b0 _)).2 (Ξ»x, fF_bdd x N) } end /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : Ξ² β†’ Ξ³) {C : nnreal} (H : lipschitz_with C G) (f : Ξ± →ᡇ Ξ²) : Ξ± →ᡇ Ξ³ := ⟨λx, G (f x), H.continuous.comp f.2.1, let ⟨D, hD⟩ := f.2.2 in ⟨max C 0 * D, Ξ» x y, calc dist (G (f x)) (G (f y)) ≀ C * dist (f x) (f y) : H.dist_le_mul _ _ ... ≀ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≀ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/ lemma lipschitz_comp {G : Ξ² β†’ Ξ³} {C : nnreal} (H : lipschitz_with C G) : lipschitz_with C (comp G H : (Ξ± →ᡇ Ξ²) β†’ Ξ± →ᡇ Ξ³) := lipschitz_with.of_dist_le_mul $ Ξ» f g, (dist_le (mul_nonneg C.2 dist_nonneg)).2 $ Ξ» x, calc dist (G (f x)) (G (g x)) ≀ C * dist (f x) (g x) : H.dist_le_mul _ _ ... ≀ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2 /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/ lemma uniform_continuous_comp {G : Ξ² β†’ Ξ³} {C : nnreal} (H : lipschitz_with C G) : uniform_continuous (comp G H : (Ξ± →ᡇ Ξ²) β†’ Ξ± →ᡇ Ξ³) := (lipschitz_comp H).uniform_continuous /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : Ξ² β†’ Ξ³} {C : nnreal} (H : lipschitz_with C G) : continuous (comp G H : (Ξ± →ᡇ Ξ²) β†’ Ξ± →ᡇ Ξ³) := (lipschitz_comp H).continuous /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set Ξ²) (f : Ξ± →ᡇ Ξ²) (H : βˆ€x, f x ∈ s) : Ξ± →ᡇ s := ⟨λx, ⟨f x, H x⟩, continuous_subtype_mk _ f.2.1, f.2.2⟩ end basics section arzela_ascoli variables [topological_space Ξ±] [compact_space Ξ±] [metric_space Ξ²] variables {f g : Ξ± →ᡇ Ξ²} {x : Ξ±} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space Ξ²] (A : set (Ξ± →ᡇ Ξ²)) (closed : is_closed A) (H : βˆ€ (x:Ξ±) (Ξ΅ > 0), βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅) : compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (Ξ» Ξ΅ Ξ΅0, _), rcases dense Ξ΅0 with βŸ¨Ξ΅β‚, Ρ₁0, Ξ΅Ξ΅β‚βŸ©, let Ξ΅β‚‚ := Ρ₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to Ξ΅. This information will be provided by the values of `u` on a sufficiently dense set tΞ±, slightly translated to fit in a finite Ξ΅β‚‚-dense set tΞ² in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to Ξ΅, one uses the control on the modulus of continuity to extend the closeness on tΞ± to closeness everywhere. -/ have Ξ΅β‚‚0 : Ξ΅β‚‚ > 0 := half_pos (half_pos Ρ₁0), have : βˆ€x:Ξ±, βˆƒU, x ∈ U ∧ is_open U ∧ βˆ€ (y z ∈ U) {f : Ξ± →ᡇ Ξ²}, f ∈ A β†’ dist (f y) (f z) < Ξ΅β‚‚ := Ξ» x, let ⟨U, nhdsU, hU⟩ := H x _ Ξ΅β‚‚0, ⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in ⟨V, xV, openV, Ξ»y z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most Ξ΅β‚‚. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_univ.elim_finite_subcover_image (Ξ»x _, (hU x).2.1) (Ξ»x hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tΞ±, _, ⟨_⟩, htα⟩, /- tΞ± : set Ξ±, htΞ± : univ βŠ† ⋃x ∈ tΞ±, U x -/ rcases @finite_cover_balls_of_compact Ξ² _ _ compact_univ _ Ξ΅β‚‚0 with ⟨tΞ², _, ⟨_⟩, htβ⟩, resetI, /- tΞ² : set Ξ², htΞ² : univ βŠ† ⋃y ∈ tΞ², ball y Ξ΅β‚‚ -/ /- Associate to every point `y` in the space a nearby point `F y` in tΞ² -/ choose F hF using Ξ»y, show βˆƒz∈tΞ², dist y z < Ξ΅β‚‚, by simpa using htΞ² (mem_univ y), /- F : Ξ² β†’ Ξ², hF : βˆ€ (y : Ξ²), F y ∈ tΞ² ∧ dist y (F y) < Ξ΅β‚‚ -/ /- Associate to every function a discrete approximation, mapping each point in `tΞ±` to a point in `tΞ²` close to its true image by the function. -/ refine ⟨tΞ± β†’ tΞ², by apply_instance, Ξ» f a, ⟨F (f a), (hF (f a)).1⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance Ξ΅ -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt Ρ₁0).2 (Ξ» x, _)) ΡΡ₁, obtain ⟨x', x'tΞ±, hx'⟩ : βˆƒx' ∈ tΞ±, x ∈ U x' := mem_bUnion_iff.1 (htΞ± (mem_univ x)), refine calc dist (f x) (g x) ≀ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≀ Ξ΅β‚‚ + Ξ΅β‚‚ + Ρ₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = Ρ₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ _ hx' ((hU x').1) hf }, { exact (hU x').2.2 _ _ hx' ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (Ξ» f:tΞ± β†’ tΞ², (f ⟨x', x'tα⟩ : Ξ²)) f_eq_g : _), calc dist (f x') (g x') ≀ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < Ξ΅β‚‚ + Ξ΅β‚‚ : add_lt_add (hF (f x')).2 (hF (g x')).2 ... = Ρ₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoliβ‚‚ (s : set Ξ²) (hs : compact s) (A : set (Ξ± →ᡇ Ξ²)) (closed : is_closed A) (in_s : βˆ€(f : Ξ± →ᡇ Ξ²) (x : Ξ±), f ∈ A β†’ f x ∈ s) (H : βˆ€(x:Ξ±) (Ξ΅ > 0), βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅) : compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s, let F : (Ξ± →ᡇ s) β†’ Ξ± →ᡇ Ξ² := comp coe M, refine compact_of_is_closed_subset ((_ : compact (F ⁻¹' A)).image (continuous_comp M)) closed (Ξ» f hf, _), { haveI : compact_space s := compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (Ξ» x Ξ΅ Ξ΅0, bex.imp_right (Ξ» U U_nhds hU y z hy hz f hf, _) (H x Ξ΅ Ξ΅0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < Ξ΅ : hU y z hy hz (F f) hf }, { let g := cod_restrict s f (Ξ»x, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊒, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli (s : set Ξ²) (hs : compact s) (A : set (Ξ± →ᡇ Ξ²)) (in_s : βˆ€(f : Ξ± →ᡇ Ξ²) (x : Ξ±), f ∈ A β†’ f x ∈ s) (H : βˆ€(x:Ξ±) (Ξ΅ > 0), βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅) : compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoliβ‚‚ s hs (closure A) is_closed_closure (Ξ» f x hf, (mem_of_closed' (closed_of_compact _ hs)).2 $ Ξ» Ξ΅ Ξ΅0, let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf Ξ΅ Ξ΅0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (Ξ» x Ξ΅ Ξ΅0, show βˆƒ U ∈ 𝓝 x, βˆ€ y z ∈ U, βˆ€ (f : Ξ± →ᡇ Ξ²), f ∈ closure A β†’ dist (f y) (f z) < Ξ΅, begin refine bex.imp_right (Ξ» U U_set hU y z hy hz f hf, _) (H x (Ξ΅/2) (half_pos Ξ΅0)), rcases metric.mem_closure_iff.1 hf (Ξ΅/2/2) (half_pos (half_pos Ξ΅0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := Ξ» x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≀ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < Ξ΅/2/2 + Ξ΅/2/2 + Ξ΅/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA) ... = Ξ΅ : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {Ξ± : Type u} [metric_space Ξ±] (b : ℝ β†’ ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0)) (A : set (Ξ± →ᡇ Ξ²)) (H : βˆ€(x y:Ξ±) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f x) (f y) ≀ b (dist x y)) (x:Ξ±) (Ξ΅ : ℝ) (Ξ΅0 : Ξ΅ > 0) : βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅ := begin rcases tendsto_nhds_nhds.1 b_lim Ξ΅ Ξ΅0 with ⟨δ, Ξ΄0, hδ⟩, refine ⟨ball x (Ξ΄/2), ball_mem_nhds x (half_pos Ξ΄0), Ξ» y z hy hz f hf, _⟩, have : dist y z < Ξ΄ := calc dist y z ≀ dist y x + dist z x : dist_triangle_right _ _ _ ... < Ξ΄/2 + Ξ΄/2 : add_lt_add hy hz ... = Ξ΄ : add_halves _, calc dist (f y) (f z) ≀ b (dist y z) : H y z f hf ... ≀ abs (b (dist y z)) : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < Ξ΅ : hΞ΄ (by simpa [real.dist_eq] using this), end end arzela_ascoli section normed_group /- In this section, if Ξ² is a normed group, then we show that the space of bounded continuous functions from Ξ± to Ξ² inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space Ξ±] [normed_group Ξ²] variables {f g : Ξ± →ᡇ Ξ²} {x : Ξ±} {C : ℝ} instance : has_zero (Ξ± →ᡇ Ξ²) := ⟨const 0⟩ @[simp] lemma coe_zero : (0 : Ξ± →ᡇ Ξ²) x = 0 := rfl instance : has_norm (Ξ± →ᡇ Ξ²) := ⟨λu, dist u 0⟩ lemma norm_def : βˆ₯fβˆ₯ = dist f 0 := rfl lemma norm_coe_le_norm (x : Ξ±) : βˆ₯f xβˆ₯ ≀ βˆ₯fβˆ₯ := calc βˆ₯f xβˆ₯ = dist (f x) ((0 : Ξ± →ᡇ Ξ²) x) : by simp [dist_zero_right] ... ≀ βˆ₯fβˆ₯ : dist_coe_le_dist _ /-- Distance between the images of any two points is at most twice the norm of the function. -/ lemma dist_le_two_norm (x y : Ξ±) : dist (f x) (f y) ≀ 2 * βˆ₯fβˆ₯ := calc dist (f x) (f y) ≀ βˆ₯f xβˆ₯ + βˆ₯f yβˆ₯ : dist_le_norm_add_norm _ _ ... ≀ βˆ₯fβˆ₯ + βˆ₯fβˆ₯ : add_le_add (norm_coe_le_norm x) (norm_coe_le_norm y) ... = 2 * βˆ₯fβˆ₯ : (two_mul _).symm /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≀ C) : βˆ₯fβˆ₯ ≀ C ↔ βˆ€x:Ξ±, βˆ₯f xβˆ₯ ≀ C := by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0 /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (Ξ± →ᡇ Ξ²) := ⟨λf g, ⟨λx, f x + g x, f.2.1.add g.2.1, let ⟨_, fM, hf⟩ := f.2 in let ⟨_, gM, hg⟩ := g.2 in ⟨fM + gM, Ξ» x y, dist_add_add_le_of_le (hf _ _) (hg _ _)⟩⟩⟩ /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (Ξ± →ᡇ Ξ²) := ⟨λf, ⟨λx, -f x, f.2.1.neg, by simpa only [dist_neg_neg] using f.2.2⟩⟩ @[simp] lemma coe_add : (f + g) x = f x + g x := rfl @[simp] lemma coe_neg : (-f) x = - (f x) := rfl lemma forall_coe_zero_iff_zero : (βˆ€x, f x = 0) ↔ f = 0 := ⟨@ext _ _ _ _ f 0, by rintro rfl _; refl⟩ instance : add_comm_group (Ξ± →ᡇ Ξ²) := { add_assoc := assume f g h, by ext; simp, zero_add := assume f, by ext; simp, add_zero := assume f, by ext; simp, add_left_neg := assume f, by ext; simp, add_comm := assume f g, by ext; simp [add_comm], ..bounded_continuous_function.has_add, ..bounded_continuous_function.has_neg, ..bounded_continuous_function.has_zero } @[simp] lemma coe_diff : (f - g) x = f x - g x := rfl instance : normed_group (Ξ± →ᡇ Ξ²) := normed_group.of_add_dist (Ξ» _, rfl) $ Ξ» f g h, (dist_le dist_nonneg).2 $ Ξ» x, le_trans (by rw [dist_eq_norm, dist_eq_norm, coe_add, coe_add, add_sub_add_right_eq_sub]) (dist_coe_le_dist x) lemma abs_diff_coe_le_dist : norm (f x - g x) ≀ dist f g := by rw normed_group.dist_eq; exact @norm_coe_le_norm _ _ _ _ (f-g) x lemma coe_le_coe_add_dist {f g : Ξ± →ᡇ ℝ} : f x ≀ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {Ξ± : Type u} {Ξ² : Type v} [topological_space Ξ±] [normed_group Ξ²] (f : Ξ± β†’ Ξ²) (C : ℝ) (H : βˆ€x, norm (f x) ≀ C) (Hf : continuous f) : Ξ± →ᡇ Ξ² := ⟨λn, f n, ⟨Hf, ⟨C + C, Ξ» m n, calc dist (f m) (f n) ≀ dist (f m) 0 + dist (f n) 0 : dist_triangle_right _ _ _ ... = norm (f m) + norm (f n) : by simp ... ≀ C + C : add_le_add (H m) (H n)⟩⟩⟩ /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {Ξ± : Type u} {Ξ² : Type v} [topological_space Ξ±] [discrete_topology Ξ±] [normed_group Ξ²] (f : Ξ± β†’ Ξ²) (C : ℝ) (H : βˆ€x, norm (f x) ≀ C) : Ξ± →ᡇ Ξ² := of_normed_group f C H continuous_of_discrete_topology end normed_group end bounded_continuous_function
5b98d751cff87703534027195b086a77eef64057
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/nat/main_auto.lean
be3bb185b4040574b61c771e4ddfb68aeba090f6
[]
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
676
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.prove_unsats import Mathlib.tactic.omega.nat.dnf import Mathlib.tactic.omega.nat.neg_elim import Mathlib.tactic.omega.nat.sub_elim import Mathlib.PostPort namespace Mathlib /- Main procedure for linear natural number arithmetic. -/ namespace omega namespace nat theorem univ_close_of_unsat_neg_elim_not (m : β„•) (p : preform) : preform.unsat (neg_elim (preform.not p)) β†’ univ_close p (fun (_x : β„•) => 0) m := sorry end Mathlib
deb95caf9baf3e4649d259e81059556c4ba8e04c
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/ordered_group.lean
047708bac624a939a67caef3c3258e0723f5ed52
[ "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
28,125
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes HΓΆlzl Ordered monoids and groups. -/ import algebra.group order.bounded_lattice tactic.basic universe u variable {Ξ± : Type u} section old_structure_cmd set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that addition is an order embedding, i.e. `a + b ≀ a + c ↔ b ≀ c`. These monoids are automatically cancellative. -/ class ordered_comm_monoid (Ξ± : Type*) extends add_comm_monoid Ξ±, partial_order Ξ± := (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) (lt_of_add_lt_add_left : βˆ€ a b c : Ξ±, a + b < a + c β†’ b < c) /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≀ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ class canonically_ordered_monoid (Ξ± : Type*) extends ordered_comm_monoid Ξ±, lattice.order_bot Ξ± := (le_iff_exists_add : βˆ€a b:Ξ±, a ≀ b ↔ βˆƒc, b = a + c) end old_structure_cmd section ordered_comm_monoid variables [ordered_comm_monoid Ξ±] {a b c d : Ξ±} lemma add_le_add_left' (h : a ≀ b) : c + a ≀ c + b := ordered_comm_monoid.add_le_add_left a b h c lemma add_le_add_right' (h : a ≀ b) : a + c ≀ b + c := add_comm c a β–Έ add_comm c b β–Έ add_le_add_left' h lemma lt_of_add_lt_add_left' : a + b < a + c β†’ b < c := ordered_comm_monoid.lt_of_add_lt_add_left a b c lemma add_le_add' (h₁ : a ≀ b) (hβ‚‚ : c ≀ d) : a + c ≀ b + d := le_trans (add_le_add_right' h₁) (add_le_add_left' hβ‚‚) lemma le_add_of_nonneg_right' (h : 0 ≀ b) : a ≀ a + b := have a + b β‰₯ a + 0, from add_le_add_left' h, by rwa add_zero at this lemma le_add_of_nonneg_left' (h : 0 ≀ b) : a ≀ b + a := have 0 + a ≀ b + a, from add_le_add_right' h, by rwa zero_add at this lemma lt_of_add_lt_add_right' (h : a + b < c + b) : a < c := lt_of_add_lt_add_left' (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) -- here we start using properties of zero. lemma le_add_of_nonneg_of_le' (ha : 0 ≀ a) (hbc : b ≀ c) : b ≀ a + c := zero_add b β–Έ add_le_add' ha hbc lemma le_add_of_le_of_nonneg' (hbc : b ≀ c) (ha : 0 ≀ a) : b ≀ c + a := add_zero b β–Έ add_le_add' hbc ha lemma add_nonneg' (ha : 0 ≀ a) (hb : 0 ≀ b) : 0 ≀ a + b := le_add_of_nonneg_of_le' ha hb lemma add_pos_of_pos_of_nonneg' (ha : 0 < a) (hb : 0 ≀ b) : 0 < a + b := lt_of_lt_of_le ha $ le_add_of_nonneg_right' hb lemma add_pos' (ha : 0 < a) (hb : 0 < b) : 0 < a + b := add_pos_of_pos_of_nonneg' ha $ le_of_lt hb lemma add_pos_of_nonneg_of_pos' (ha : 0 ≀ a) (hb : 0 < b) : 0 < a + b := lt_of_lt_of_le hb $ le_add_of_nonneg_left' ha lemma add_nonpos' (ha : a ≀ 0) (hb : b ≀ 0) : a + b ≀ 0 := zero_add (0:Ξ±) β–Έ (add_le_add' ha hb) lemma add_le_of_nonpos_of_le' (ha : a ≀ 0) (hbc : b ≀ c) : a + b ≀ c := zero_add c β–Έ add_le_add' ha hbc lemma add_le_of_le_of_nonpos' (hbc : b ≀ c) (ha : a ≀ 0) : b + a ≀ c := add_zero c β–Έ add_le_add' hbc ha lemma add_neg_of_neg_of_nonpos' (ha : a < 0) (hb : b ≀ 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) hb) ha lemma add_neg_of_nonpos_of_neg' (ha : a ≀ 0) (hb : b < 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hb lemma add_neg' (ha : a < 0) (hb : b < 0) : a + b < 0 := add_neg_of_nonpos_of_neg' (le_of_lt ha) hb lemma lt_add_of_nonneg_of_lt' (ha : 0 ≀ a) (hbc : b < c) : b < a + c := lt_of_lt_of_le hbc $ le_add_of_nonneg_left' ha lemma lt_add_of_lt_of_nonneg' (hbc : b < c) (ha : 0 ≀ a) : b < c + a := lt_of_lt_of_le hbc $ le_add_of_nonneg_right' ha lemma lt_add_of_pos_of_lt' (ha : 0 < a) (hbc : b < c) : b < a + c := lt_add_of_nonneg_of_lt' (le_of_lt ha) hbc lemma lt_add_of_lt_of_pos' (hbc : b < c) (ha : 0 < a) : b < c + a := lt_add_of_lt_of_nonneg' hbc (le_of_lt ha) lemma add_lt_of_nonpos_of_lt' (ha : a ≀ 0) (hbc : b < c) : a + b < c := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hbc lemma add_lt_of_lt_of_nonpos' (hbc : b < c) (ha : a ≀ 0) : b + a < c := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) ha) hbc lemma add_lt_of_neg_of_lt' (ha : a < 0) (hbc : b < c) : a + b < c := add_lt_of_nonpos_of_lt' (le_of_lt ha) hbc lemma add_lt_of_lt_of_neg' (hbc : b < c) (ha : a < 0) : b + a < c := add_lt_of_lt_of_nonpos' hbc (le_of_lt ha) lemma add_eq_zero_iff' (ha : 0 ≀ a) (hb : 0 ≀ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume hab : a + b = 0, have a ≀ 0, from hab β–Έ le_add_of_le_of_nonneg' (le_refl _) hb, have a = 0, from le_antisymm this ha, have b ≀ 0, from hab β–Έ le_add_of_nonneg_of_le' ha (le_refl _), have b = 0, from le_antisymm this hb, and.intro β€Ήa = 0β€Ί β€Ήb = 0β€Ί) (assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero]) lemma bit0_pos {a : Ξ±} (h : 0 < a) : 0 < bit0 a := add_pos' h h end ordered_comm_monoid namespace units instance [monoid Ξ±] [i : preorder Ξ±] : preorder (units Ξ±) := preorder.lift (coe : units Ξ± β†’ Ξ±) i @[simp] theorem coe_le_coe [monoid Ξ±] [preorder Ξ±] {a b : units Ξ±} : (a : Ξ±) ≀ b ↔ a ≀ b := iff.rfl @[simp] theorem coe_lt_coe [monoid Ξ±] [preorder Ξ±] {a b : units Ξ±} : (a : Ξ±) < b ↔ a < b := iff.rfl instance [monoid Ξ±] [i : partial_order Ξ±] : partial_order (units Ξ±) := partial_order.lift (coe : units Ξ± β†’ Ξ±) (by ext) i instance [monoid Ξ±] [i : linear_order Ξ±] : linear_order (units Ξ±) := linear_order.lift (coe : units Ξ± β†’ Ξ±) (by ext) i instance [monoid Ξ±] [i : decidable_linear_order Ξ±] : decidable_linear_order (units Ξ±) := decidable_linear_order.lift (coe : units Ξ± β†’ Ξ±) (by ext) i theorem max_coe [monoid Ξ±] [decidable_linear_order Ξ±] {a b : units Ξ±} : (↑(max a b) : Ξ±) = max a b := by by_cases a ≀ b; simp [max, h] theorem min_coe [monoid Ξ±] [decidable_linear_order Ξ±] {a b : units Ξ±} : (↑(min a b) : Ξ±) = min a b := by by_cases a ≀ b; simp [min, h] end units namespace with_zero open lattice instance [preorder Ξ±] : preorder (with_zero Ξ±) := with_bot.preorder instance [partial_order Ξ±] : partial_order (with_zero Ξ±) := with_bot.partial_order instance [partial_order Ξ±] : order_bot (with_zero Ξ±) := with_bot.order_bot instance [lattice Ξ±] : lattice (with_zero Ξ±) := with_bot.lattice instance [linear_order Ξ±] : linear_order (with_zero Ξ±) := with_bot.linear_order instance [decidable_linear_order Ξ±] : decidable_linear_order (with_zero Ξ±) := with_bot.decidable_linear_order def ordered_comm_monoid [ordered_comm_monoid Ξ±] (zero_le : βˆ€ a : Ξ±, 0 ≀ a) : ordered_comm_monoid (with_zero Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊒, refine ⟨λ b hβ‚‚, _, Ξ» hβ‚‚, h'.2 $ this _ _ hβ‚‚ _⟩, cases hβ‚‚, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left' $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca hβ‚‚, cases b with b, { rw le_antisymm h bot_le at hβ‚‚, exact ⟨_, hβ‚‚, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at hβ‚‚, simp at hβ‚‚, simp [hβ‚‚], exact ⟨_, rfl, by simpa using add_le_add_left' (zero_le b)⟩ }, { simp at h, cases c with c; change some _ = _ at hβ‚‚; simp [-add_comm] at hβ‚‚; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left' h } } } end end with_zero namespace with_top open lattice instance [add_semigroup Ξ±] : add_semigroup (with_top Ξ±) := { add := Ξ» o₁ oβ‚‚, o₁.bind (Ξ» a, oβ‚‚.map (Ξ» b, a + b)), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative Ξ±) _ } lemma coe_add [add_semigroup Ξ±] {a b : Ξ±} : ((a + b : Ξ±) : with_top Ξ±) = a + b := rfl instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_top Ξ±) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative Ξ±) _ } instance [add_monoid Ξ±] : add_monoid (with_top Ξ±) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @with_zero.monoid (multiplicative Ξ±) _ } instance [add_comm_monoid Ξ±] : add_comm_monoid (with_top Ξ±) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @with_zero.comm_monoid (multiplicative Ξ±) _ } instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (with_top Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_top.partial_order, ..with_top.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊒, refine ⟨λ c hβ‚‚, _, Ξ» hβ‚‚, h'.2 $ this _ _ hβ‚‚ _⟩, cases hβ‚‚, cases a with a, { exact (not_le_of_lt h).elim le_top }, cases b with b, { exact (not_le_of_lt h).elim le_top }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $ with_top.some_lt_some.1 h)⟩ } }, { intros a b h c ca hβ‚‚, cases c with c, {cases hβ‚‚}, cases b with b; cases hβ‚‚, cases a with a, {cases le_antisymm h le_top }, simp at h, exact ⟨_, rfl, add_le_add_left' h⟩, } end @[simp] lemma zero_lt_top [ordered_comm_monoid Ξ±] : (0 : with_top Ξ±) < ⊀ := coe_lt_top 0 @[simp] lemma zero_lt_coe [ordered_comm_monoid Ξ±] (a : Ξ±) : (0 : with_top Ξ±) < a ↔ 0 < a := coe_lt_coe @[simp] lemma add_top [ordered_comm_monoid Ξ±] : βˆ€{a : with_top Ξ±}, a + ⊀ = ⊀ | none := rfl | (some a) := rfl @[simp] lemma top_add [ordered_comm_monoid Ξ±] {a : with_top Ξ±} : ⊀ + a = ⊀ := rfl lemma add_eq_top [ordered_comm_monoid Ξ±] (a b : with_top Ξ±) : a + b = ⊀ ↔ a = ⊀ ∨ b = ⊀ := by cases a; cases b; simp [none_eq_top, some_eq_coe, coe_add.symm] lemma add_lt_top [ordered_comm_monoid Ξ±] (a b : with_top Ξ±) : a + b < ⊀ ↔ a < ⊀ ∧ b < ⊀ := begin apply not_iff_not.1, simp [lt_top_iff_ne_top, add_eq_top], finish, apply classical.dec _, apply classical.dec _, end instance [canonically_ordered_monoid Ξ±] : canonically_ordered_monoid (with_top Ξ±) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≀ ⊀ ↔ βˆƒc, ⊀ = a + c, by simp; refine ⟨⊀, _⟩; cases a; refl | (some a), (some b) := show (a:with_top Ξ±) ≀ ↑b ↔ βˆƒc:with_top Ξ±, ↑b = ↑a + c, begin simp [canonically_ordered_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, simp [coe_add] }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊀ : with_top Ξ±) ≀ b ↔ βˆƒc:with_top Ξ±, ↑b = ⊀ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_comm_monoid } end with_top namespace with_bot open lattice instance [add_semigroup Ξ±] : add_semigroup (with_bot Ξ±) := with_top.add_semigroup instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_bot Ξ±) := with_top.add_comm_semigroup instance [add_monoid Ξ±] : add_monoid (with_bot Ξ±) := with_top.add_monoid instance [add_comm_monoid Ξ±] : add_comm_monoid (with_bot Ξ±) := with_top.add_comm_monoid instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (with_bot Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊒, refine ⟨λ b hβ‚‚, _, Ξ» hβ‚‚, h'.2 $ this _ _ hβ‚‚ _⟩, cases hβ‚‚, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca hβ‚‚, cases c with c, {cases hβ‚‚}, cases a with a; cases hβ‚‚, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left' h⟩, } end @[simp] lemma coe_zero [add_monoid Ξ±] : ((0 : Ξ±) : with_bot Ξ±) = 0 := rfl @[simp] lemma coe_add [add_semigroup Ξ±] (a b : Ξ±) : ((a + b : Ξ±) : with_bot Ξ±) = a + b := rfl @[simp] lemma bot_add [ordered_comm_monoid Ξ±] (a : with_bot Ξ±) : βŠ₯ + a = βŠ₯ := rfl @[simp] lemma add_bot [ordered_comm_monoid Ξ±] (a : with_bot Ξ±) : a + βŠ₯ = βŠ₯ := by cases a; refl instance has_one [has_one Ξ±] : has_one (with_bot Ξ±) := ⟨(1 : Ξ±)⟩ @[simp] lemma coe_one [has_one Ξ±] : ((1 : Ξ±) : with_bot Ξ±) = 1 := rfl end with_bot section canonically_ordered_monoid variables [canonically_ordered_monoid Ξ±] {a b c d : Ξ±} lemma le_iff_exists_add : a ≀ b ↔ βˆƒc, b = a + c := canonically_ordered_monoid.le_iff_exists_add a b @[simp] lemma zero_le (a : Ξ±) : 0 ≀ a := le_iff_exists_add.mpr ⟨a, by simp⟩ lemma bot_eq_zero : (βŠ₯ : Ξ±) = 0 := le_antisymm lattice.bot_le (zero_le βŠ₯) @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff' (zero_le _) (zero_le _) @[simp] lemma le_zero_iff_eq : a ≀ 0 ↔ a = 0 := iff.intro (assume h, le_antisymm h (zero_le a)) (assume h, h β–Έ le_refl a) protected lemma zero_lt_iff_ne_zero : 0 < a ↔ a β‰  0 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm lemma le_add_left (h : a ≀ c) : a ≀ b + c := calc a = 0 + a : by simp ... ≀ b + c : add_le_add' (zero_le _) h lemma le_add_right (h : a ≀ b) : a ≀ b + c := calc a = a + 0 : by simp ... ≀ b + c : add_le_add' h (zero_le _) instance with_zero.canonically_ordered_monoid : canonically_ordered_monoid (with_zero Ξ±) := { le_iff_exists_add := Ξ» a b, begin cases a with a, { exact iff_of_true lattice.bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm lattice.bot_le) (by simp)) (Ξ» ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_comm_monoid zero_le } end canonically_ordered_monoid @[priority 100] -- see Note [lower instance priority] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid [H : ordered_cancel_comm_monoid Ξ±] : ordered_comm_monoid Ξ± := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, ..H } section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid Ξ±] {a b c x y : Ξ±} @[simp] lemma add_le_add_iff_left (a : Ξ±) {b c : Ξ±} : a + b ≀ a + c ↔ b ≀ c := ⟨le_of_add_le_add_left, Ξ» h, add_le_add_left h _⟩ @[simp] lemma add_le_add_iff_right (c : Ξ±) : a + c ≀ b + c ↔ a ≀ b := add_comm c a β–Έ add_comm c b β–Έ add_le_add_iff_left c @[simp] lemma add_lt_add_iff_left (a : Ξ±) {b c : Ξ±} : a + b < a + c ↔ b < c := ⟨lt_of_add_lt_add_left, Ξ» h, add_lt_add_left h _⟩ @[simp] lemma add_lt_add_iff_right (c : Ξ±) : a + c < b + c ↔ a < b := add_comm c a β–Έ add_comm c b β–Έ add_lt_add_iff_left c @[simp] lemma le_add_iff_nonneg_right (a : Ξ±) {b : Ξ±} : a ≀ a + b ↔ 0 ≀ b := have a + 0 ≀ a + b ↔ 0 ≀ b, from add_le_add_iff_left a, by rwa add_zero at this @[simp] lemma le_add_iff_nonneg_left (a : Ξ±) {b : Ξ±} : a ≀ b + a ↔ 0 ≀ b := by rw [add_comm, le_add_iff_nonneg_right] @[simp] lemma lt_add_iff_pos_right (a : Ξ±) {b : Ξ±} : a < a + b ↔ 0 < b := have a + 0 < a + b ↔ 0 < b, from add_lt_add_iff_left a, by rwa add_zero at this @[simp] lemma lt_add_iff_pos_left (a : Ξ±) {b : Ξ±} : a < b + a ↔ 0 < b := by rw [add_comm, lt_add_iff_pos_right] @[simp] lemma add_le_iff_nonpos_left : x + y ≀ y ↔ x ≀ 0 := by { convert add_le_add_iff_right y, rw [zero_add] } @[simp] lemma add_le_iff_nonpos_right : x + y ≀ x ↔ y ≀ 0 := by { convert add_le_add_iff_left x, rw [add_zero] } @[simp] lemma add_lt_iff_neg_right : x + y < y ↔ x < 0 := by { convert add_lt_add_iff_right y, rw [zero_add] } @[simp] lemma add_lt_iff_neg_left : x + y < x ↔ y < 0 := by { convert add_lt_add_iff_left x, rw [add_zero] } lemma add_eq_zero_iff_eq_zero_of_nonneg (ha : 0 ≀ a) (hb : 0 ≀ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := ⟨λ hab : a + b = 0, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], Ξ» ⟨ha', hb'⟩, by rw [ha', hb', add_zero]⟩ lemma with_top.add_lt_add_iff_left : βˆ€{a b c : with_top Ξ±}, a < ⊀ β†’ (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊀ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { rw [← with_top.coe_add], exact with_top.coe_lt_top _ }, { rw [← with_top.coe_add, ← with_top.coe_add, with_top.coe_lt_coe], exact add_lt_add_iff_left _ } end lemma with_top.add_lt_add_iff_right {a b c : with_top Ξ±} : a < ⊀ β†’ (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c end ordered_cancel_comm_monoid section ordered_comm_group /-- The `add_lt_add_left` field of `ordered_comm_group` is redundant, but it is in core so we can't remove it for now. This alternative constructor is the best we can do. -/ def ordered_comm_group.mk' {Ξ± : Type u} [add_comm_group Ξ±] [partial_order Ξ±] (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) : ordered_comm_group Ξ± := { add_le_add_left := add_le_add_left, add_lt_add_left := Ξ» a b h c, begin rw lt_iff_le_not_le at h, rw lt_iff_le_not_le, split, { apply add_le_add_left _ _ h.1 }, { intro w, replace w : -c + (c + b) ≀ -c + (c + a) := add_le_add_left _ _ w _, simp only [add_zero, add_comm, add_left_neg, add_left_comm] at w, exact h.2 w }, end, ..(by apply_instance : add_comm_group Ξ±), ..(by apply_instance : partial_order Ξ±) } variables [ordered_comm_group Ξ±] {a b c : Ξ±} lemma neg_neg_iff_pos {Ξ± : Type} [_inst_1 : ordered_comm_group Ξ±] {a : Ξ±} : -a < 0 ↔ 0 < a := ⟨ pos_of_neg_neg, neg_neg_of_pos ⟩ @[simp] lemma neg_le_neg_iff : -a ≀ -b ↔ b ≀ a := have a + b + -a ≀ a + b + -b ↔ -a ≀ -b, from add_le_add_iff_left _, by simp at this; simp [this] lemma neg_le : -a ≀ b ↔ -b ≀ a := have -a ≀ -(-b) ↔ -b ≀ a, from neg_le_neg_iff, by rwa neg_neg at this lemma le_neg : a ≀ -b ↔ b ≀ -a := have -(-a) ≀ -b ↔ b ≀ -a, from neg_le_neg_iff, by rwa neg_neg at this lemma neg_le_iff_add_nonneg : -a ≀ b ↔ 0 ≀ a + b := (add_le_add_iff_left a).symm.trans $ by rw add_neg_self lemma le_neg_iff_add_nonpos : a ≀ -b ↔ a + b ≀ 0 := (add_le_add_iff_right b).symm.trans $ by rw neg_add_self @[simp] lemma neg_nonpos : -a ≀ 0 ↔ 0 ≀ a := have -a ≀ -0 ↔ 0 ≀ a, from neg_le_neg_iff, by rwa neg_zero at this @[simp] lemma neg_nonneg : 0 ≀ -a ↔ a ≀ 0 := have -0 ≀ -a ↔ a ≀ 0, from neg_le_neg_iff, by rwa neg_zero at this lemma neg_le_self (h : 0 ≀ a) : -a ≀ a := le_trans (neg_nonpos.2 h) h lemma self_le_neg (h : a ≀ 0) : a ≀ -a := le_trans h (neg_nonneg.2 h) @[simp] lemma neg_lt_neg_iff : -a < -b ↔ b < a := have a + b + -a < a + b + -b ↔ -a < -b, from add_lt_add_iff_left _, by simp at this; simp [this] lemma neg_lt_zero : -a < 0 ↔ 0 < a := have -a < -0 ↔ 0 < a, from neg_lt_neg_iff, by rwa neg_zero at this lemma neg_pos : 0 < -a ↔ a < 0 := have -0 < -a ↔ a < 0, from neg_lt_neg_iff, by rwa neg_zero at this lemma neg_lt : -a < b ↔ -b < a := have -a < -(-b) ↔ -b < a, from neg_lt_neg_iff, by rwa neg_neg at this lemma lt_neg : a < -b ↔ b < -a := have -(-a) < -b ↔ b < -a, from neg_lt_neg_iff, by rwa neg_neg at this lemma sub_le_sub_iff_left (a : Ξ±) {b c : Ξ±} : a - b ≀ a - c ↔ c ≀ b := (add_le_add_iff_left _).trans neg_le_neg_iff lemma sub_le_sub_iff_right (c : Ξ±) : a - c ≀ b - c ↔ a ≀ b := add_le_add_iff_right _ lemma sub_lt_sub_iff_left (a : Ξ±) {b c : Ξ±} : a - b < a - c ↔ c < b := (add_lt_add_iff_left _).trans neg_lt_neg_iff lemma sub_lt_sub_iff_right (c : Ξ±) : a - c < b - c ↔ a < b := add_lt_add_iff_right _ @[simp] lemma sub_nonneg : 0 ≀ a - b ↔ b ≀ a := have a - a ≀ a - b ↔ b ≀ a, from sub_le_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_nonpos : a - b ≀ 0 ↔ a ≀ b := have a - b ≀ b - b ↔ a ≀ b, from sub_le_sub_iff_right b, by rwa sub_self at this @[simp] lemma sub_pos : 0 < a - b ↔ b < a := have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b, by rwa sub_self at this lemma le_neg_add_iff_add_le : b ≀ -a + c ↔ a + b ≀ c := have -a + (a + b) ≀ -a + c ↔ a + b ≀ c, from add_le_add_iff_left _, by rwa neg_add_cancel_left at this lemma le_sub_iff_add_le' : b ≀ c - a ↔ a + b ≀ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≀ c - b ↔ a + b ≀ c := by rw [le_sub_iff_add_le', add_comm] @[simp] lemma neg_add_le_iff_le_add : -b + a ≀ c ↔ a ≀ b + c := have -b + a ≀ -b + (b + c) ↔ a ≀ b + c, from add_le_add_iff_left _, by rwa neg_add_cancel_left at this lemma sub_le_iff_le_add' : a - b ≀ c ↔ a ≀ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] lemma sub_le_iff_le_add : a - c ≀ b ↔ a ≀ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma add_neg_le_iff_le_add : a + -c ≀ b ↔ a ≀ b + c := sub_le_iff_le_add @[simp] lemma add_neg_le_iff_le_add' : a + -b ≀ c ↔ a ≀ b + c := sub_le_iff_le_add' lemma neg_add_le_iff_le_add' : -c + a ≀ b ↔ a ≀ b + c := by rw [neg_add_le_iff_le_add, add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≀ a - c ↔ c ≀ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≀ b - c ↔ c ≀ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≀ c ↔ a - c ≀ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≀ b - c ↔ c ≀ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm @[simp] lemma lt_neg_add_iff_add_lt : b < -a + c ↔ a + b < c := have -a + (a + b) < -a + c ↔ a + b < c, from add_lt_add_iff_left _, by rwa neg_add_cancel_left at this lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] @[simp] lemma neg_add_lt_iff_lt_add : -b + a < c ↔ a < b + c := have -b + a < -b + (b + c) ↔ a < b + c, from add_lt_add_iff_left _, by rwa neg_add_cancel_left at this lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] lemma neg_add_lt_iff_lt_add_right : -c + a < b ↔ a < b + c := by rw [neg_add_lt_iff_lt_add, add_comm] @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm lemma sub_le_self_iff (a : Ξ±) {b : Ξ±} : a - b ≀ a ↔ 0 ≀ b := sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _) lemma sub_lt_self_iff (a : Ξ±) {b : Ξ±} : a - b < a ↔ 0 < b := sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _) end ordered_comm_group namespace decidable_linear_ordered_comm_group variables [s : decidable_linear_ordered_comm_group Ξ±] include s @[priority 100] -- see Note [lower instance priority] instance : decidable_linear_ordered_cancel_comm_monoid Ξ± := { le_of_add_le_add_left := Ξ» x y z, le_of_add_le_add_left, add_left_cancel := Ξ» x y z, add_left_cancel, add_right_cancel := Ξ» x y z, add_right_cancel, ..s } lemma eq_of_abs_sub_nonpos {a b : Ξ±} (h : abs (a - b) ≀ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm _ _ h (abs_nonneg (a - b))) end decidable_linear_ordered_comm_group set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_comm_group (Ξ± : Type*) extends add_comm_group Ξ± := (nonneg : Ξ± β†’ Prop) (pos : Ξ± β†’ Prop := Ξ» a, nonneg a ∧ Β¬ nonneg (neg a)) (pos_iff : βˆ€ a, pos a ↔ nonneg a ∧ Β¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : βˆ€ {a b}, nonneg a β†’ nonneg b β†’ nonneg (a + b)) (nonneg_antisymm : βˆ€ {a}, nonneg a β†’ nonneg (-a) β†’ a = 0) end prio namespace nonneg_comm_group variable [s : nonneg_comm_group Ξ±] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_comm_group : ordered_comm_group Ξ± := { le := Ξ» a b, nonneg (b - a), lt := Ξ» a b, pos (b - a), lt_iff_le_not_le := Ξ» a b, by simp; rw [pos_iff]; simp, le_refl := Ξ» a, by simp [zero_nonneg], le_trans := Ξ» a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := Ξ» a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := Ξ» a b nab c, by simpa [(≀), preorder.le] using nab, add_lt_add_left := Ξ» a b nab c, by simpa [(<), preorder.lt] using nab, ..s } theorem nonneg_def {a : Ξ±} : nonneg a ↔ 0 ≀ a := show _ ↔ nonneg _, by simp theorem pos_def {a : Ξ±} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : Β¬ pos (0 : Ξ±) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : Ξ±} : 0 < a ↔ nonneg a ∧ Β¬ nonneg (-a) := pos_def.symm.trans (pos_iff Ξ± _) theorem nonneg_total_iff : (βˆ€ a : Ξ±, nonneg a ∨ nonneg (-a)) ↔ (βˆ€ a b : Ξ±, a ≀ b ∨ b ≀ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, Ξ» h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ def to_decidable_linear_ordered_comm_group [decidable_pred (@nonneg Ξ± _)] (nonneg_total : βˆ€ a : Ξ±, nonneg a ∨ nonneg (-a)) : decidable_linear_ordered_comm_group Ξ± := { le := (≀), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_eq := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_comm_group.to_ordered_comm_group _ s } end nonneg_comm_group namespace order_dual instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (order_dual Ξ±) := { add_le_add_left := Ξ» a b h c, @add_le_add_left' Ξ± _ b a c h, lt_of_add_lt_add_left := Ξ» a b c h, @lt_of_add_lt_add_left' Ξ± _ a c b h, ..order_dual.partial_order Ξ±, ..show add_comm_monoid Ξ±, by apply_instance } instance [ordered_cancel_comm_monoid Ξ±] : ordered_cancel_comm_monoid (order_dual Ξ±) := { le_of_add_le_add_left := Ξ» a b c : Ξ±, le_of_add_le_add_left, add_left_cancel := @add_left_cancel Ξ± _, add_right_cancel := @add_right_cancel Ξ± _, ..order_dual.ordered_comm_monoid } instance [ordered_comm_group Ξ±] : ordered_comm_group (order_dual Ξ±) := { add_lt_add_left := Ξ» a b : Ξ±, ordered_comm_group.add_lt_add_left b a, add_left_neg := Ξ» a : Ξ±, add_left_neg a, ..order_dual.ordered_comm_monoid, ..show add_comm_group Ξ±, by apply_instance } end order_dual
7b96411a8c40471e80f075559dbb3055c2ac1283
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Data/Json/Parser.lean
2408df3a648a2174d3b004f5f215d6a004c21e47
[ "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
5,488
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic import Lean.Data.Parsec namespace Lean open Std (RBNode RBNode.singleton RBNode.leaf) namespace Json.Parser open Lean.Parsec @[inline] def hexChar : Parsec Nat := do let c ← anyChar if '0' ≀ c ∧ c ≀ '9' then pure $ c.val.toNat - '0'.val.toNat else if 'a' ≀ c ∧ c ≀ 'f' then pure $ c.val.toNat - 'a'.val.toNat else if 'A' ≀ c ∧ c ≀ 'F' then pure $ c.val.toNat - 'A'.val.toNat else fail "invalid hex character" def escapedChar : Parsec Char := do let c ← anyChar match c with | '\\' => return '\\' | '"' => return '"' | '/' => return '/' | 'b' => return '\x08' | 'f' => return '\x0c' | 'n' => return '\n' | 'r' => return '\x0d' | 't' => return '\t' | 'u' => let u1 ← hexChar; let u2 ← hexChar; let u3 ← hexChar; let u4 ← hexChar return Char.ofNat $ 4096*u1 + 256*u2 + 16*u3 + u4 | _ => fail "illegal \\u escape" partial def strCore (acc : String) : Parsec String := do let c ← peek! if c = '"' then -- " skip return acc else let c ← anyChar if c = '\\' then strCore (acc.push (← escapedChar)) -- as to whether c.val > 0xffff should be split up and encoded with multiple \u, -- the JSON standard is not definite: both directly printing the character -- and encoding it with multiple \u is allowed. we choose the former. else if 0x0020 ≀ c.val ∧ c.val ≀ 0x10ffff then strCore (acc.push c) else fail "unexpected character in string" def str : Parsec String := strCore "" partial def natCore (acc digits : Nat) : Parsec (Nat Γ— Nat) := do let some c ← peek? | return (acc, digits) if '0' ≀ c ∧ c ≀ '9' then skip let acc' := 10*acc + (c.val.toNat - '0'.val.toNat) natCore acc' (digits+1) else return (acc, digits) @[inline] def lookahead (p : Char β†’ Prop) (desc : String) [DecidablePred p] : Parsec Unit := do let c ← peek! if p c then return () else fail <| "expected " ++ desc @[inline] def natNonZero : Parsec Nat := do lookahead (fun c => '1' ≀ c ∧ c ≀ '9') "1-9" let (n, _) ← natCore 0 0 return n @[inline] def natNumDigits : Parsec (Nat Γ— Nat) := do lookahead (fun c => '0' ≀ c ∧ c ≀ '9') "digit" natCore 0 0 @[inline] def natMaybeZero : Parsec Nat := do let (n, _) ← natNumDigits return n def num : Parsec JsonNumber := do let c ← peek! let sign ← if c = '-' then skip pure (-1 : Int) else pure 1 let c ← peek! let res ← if c = '0' then skip pure 0 else natNonZero let c? ← peek? let res : JsonNumber ← if c? = some '.' then skip let (n, d) ← natNumDigits if d > USize.size then fail "too many decimals" let mantissa' := sign * (res * (10^d : Nat) + n) let exponent' := d pure <| JsonNumber.mk mantissa' exponent' else pure <| JsonNumber.fromInt (sign * res) let c? ← peek? if c? = some 'e' ∨ c? = some 'E' then skip let c ← peek! if c = '-' then skip let n ← natMaybeZero return res.shiftr n else if c = '+' then skip let n ← natMaybeZero if n > USize.size then fail "exp too large" return res.shiftl n else return res partial def arrayCore (anyCore : Parsec Json) (acc : Array Json) : Parsec (Array Json) := do let hd ← anyCore let acc' := acc.push hd let c ← anyChar if c = ']' then ws return acc' else if c = ',' then ws arrayCore anyCore acc' else fail "unexpected character in array" partial def objectCore (anyCore : Parsec Json) : Parsec (RBNode String (fun _ => Json)) := do lookahead (fun c => c = '"') "\""; skip; -- " let k ← strCore ""; ws lookahead (fun c => c = ':') ":"; skip; ws let v ← anyCore let c ← anyChar if c = '}' then ws return RBNode.singleton k v else if c = ',' then ws let kvs ← objectCore anyCore return kvs.insert compare k v else fail "unexpected character in object" partial def anyCore : Parsec Json := do let c ← peek! if c = '[' then skip; ws let c ← peek! if c = ']' then skip; ws return Json.arr (Array.mkEmpty 0) else let a ← arrayCore anyCore (Array.mkEmpty 4) return Json.arr a else if c = '{' then skip; ws let c ← peek! if c = '}' then skip; ws return Json.obj (RBNode.leaf) else let kvs ← objectCore anyCore return Json.obj kvs else if c = '\"' then skip let s ← strCore "" ws return Json.str s else if c = 'f' then skipString "false"; ws return Json.bool false else if c = 't' then skipString "true"; ws return Json.bool true else if c = 'n' then skipString "null"; ws return Json.null else if c = '-' ∨ ('0' ≀ c ∧ c ≀ '9') then let n ← num ws return Json.num n else fail "unexpected input" def any : Parsec Json := do ws let res ← anyCore eof return res end Json.Parser namespace Json def parse (s : String) : Except String Lean.Json := match Json.Parser.any s.mkIterator with | Parsec.ParseResult.success _ res => Except.ok res | Parsec.ParseResult.error it err => Except.error s!"offset {repr it.i.byteIdx}: {err}" end Json end Lean
5d8868e2b3ba9f64ab915bdbaccdfeba33c50a8d
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/bounded_continuous_function.lean
8b34dcd0f8fb3d40b5a3518755a1f605b13fee7c
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
23,559
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, Mario Carneiro Type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ import analysis.normed_space.basic topology.metric_space.cau_seq_filter topology.metric_space.lipschitz noncomputable theory local attribute [instance] classical.decidable_inhabited classical.prop_decidable open_locale topological_space open set lattice filter metric universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} /-- A locally uniform limit of continuous functions is continuous -/ lemma continuous_of_locally_uniform_limit_of_continuous [topological_space Ξ±] [metric_space Ξ²] {F : β„• β†’ Ξ± β†’ Ξ²} {f : Ξ± β†’ Ξ²} (L : βˆ€x:Ξ±, βˆƒs ∈ 𝓝 x, βˆ€Ξ΅>(0:ℝ), βˆƒn, βˆ€y∈s, dist (F n y) (f y) ≀ Ξ΅) (C : βˆ€ n, continuous (F n)) : continuous f := continuous_iff'.2 $ Ξ» x Ξ΅ Ξ΅0, begin rcases L x with ⟨r, rx, hr⟩, rcases hr (Ξ΅/2/2) (half_pos $ half_pos Ξ΅0) with ⟨n, hn⟩, rcases continuous_iff'.1 (C n) x (Ξ΅/2) (half_pos Ξ΅0) with ⟨s, sx, hs⟩, refine ⟨_, (𝓝 x).inter_sets rx sx, _⟩, rintro y ⟨yr, ys⟩, calc dist (f y) (f x) ≀ dist (F n y) (F n x) + (dist (F n y) (f y) + dist (F n x) (f x)) : dist_triangle4_left _ _ _ _ ... < Ξ΅/2 + (Ξ΅/2/2 + Ξ΅/2/2) : add_lt_add_of_lt_of_le (hs _ ys) (add_le_add (hn _ yr) (hn _ (mem_of_nhds rx))) ... = Ξ΅ : by rw [add_halves, add_halves] end /-- A uniform limit of continuous functions is continuous -/ lemma continuous_of_uniform_limit_of_continuous [topological_space Ξ±] {Ξ² : Type v} [metric_space Ξ²] {F : β„• β†’ Ξ± β†’ Ξ²} {f : Ξ± β†’ Ξ²} (L : βˆ€Ξ΅>(0:ℝ), βˆƒN, βˆ€y, dist (F N y) (f y) ≀ Ξ΅) : (βˆ€ n, continuous (F n)) β†’ continuous f := continuous_of_locally_uniform_limit_of_continuous $ Ξ»x, ⟨univ, by simpa [filter.univ_mem_sets] using L⟩ /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (Ξ± : Type u) (Ξ² : Type v) [topological_space Ξ±] [metric_space Ξ²] : Type (max u v) := {f : Ξ± β†’ Ξ² // continuous f ∧ βˆƒC, βˆ€x y:Ξ±, dist (f x) (f y) ≀ C} local infixr ` →ᡇ `:25 := bounded_continuous_function namespace bounded_continuous_function section basics variables [topological_space Ξ±] [metric_space Ξ²] [metric_space Ξ³] variables {f g : Ξ± →ᡇ Ξ²} {x : Ξ±} {C : ℝ} instance : has_coe_to_fun (Ξ± →ᡇ Ξ²) := ⟨_, subtype.val⟩ lemma bounded_range : bounded (range f) := bounded_range_iff.2 f.2.2 /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact [compact_space Ξ±] (f : Ξ± β†’ Ξ²) (hf : continuous f) : Ξ± →ᡇ Ξ² := ⟨f, hf, bounded_range_iff.1 $ by rw ← image_univ; exact bounded_of_compact (compact_image compact_univ hf)⟩ /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete [discrete_topology Ξ±] (f : Ξ± β†’ Ξ²) (hf : βˆƒC, βˆ€x y, dist (f x) (f y) ≀ C) : Ξ± →ᡇ Ξ² := ⟨f, continuous_of_discrete_topology, hf⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (Ξ± →ᡇ Ξ²) := ⟨λf g, Inf {C | C β‰₯ 0 ∧ βˆ€ x : Ξ±, dist (f x) (g x) ≀ C}⟩ lemma dist_eq : dist f g = Inf {C | C β‰₯ 0 ∧ βˆ€ x : Ξ±, dist (f x) (g x) ≀ C} := rfl lemma dist_set_exists : βˆƒ C, C β‰₯ 0 ∧ βˆ€ x : Ξ±, dist (f x) (g x) ≀ C := begin refine if h : nonempty Ξ± then _ else ⟨0, le_refl _, Ξ» x, h.elim ⟨x⟩⟩, cases h with x, rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : βˆ€ (x y : Ξ±), dist (f.val x) (f.val y) ≀ Cf -/ rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : βˆ€ (x y : Ξ±), dist (g.val x) (g.val y) ≀ Cg -/ let C := max 0 (dist (f x) (g x) + (Cf + Cg)), exact ⟨C, le_max_left _ _, Ξ» y, calc dist (f y) (g y) ≀ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _ ... ≀ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _ ... ≀ C : le_max_right _ _⟩ end /-- The pointwise distance is controlled by the distance between functions, by definition -/ lemma dist_coe_le_dist (x : Ξ±) : dist (f x) (g x) ≀ dist f g := le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) $ Ξ»b hb, hb.2 x @[ext] lemma ext (H : βˆ€x, f x = g x) : f = g := subtype.eq $ by ext; apply H /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ private lemma dist_nonneg' : 0 ≀ dist f g := le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) (Ξ» C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≀ C) : dist f g ≀ C ↔ βˆ€x:Ξ±, dist (f x) (g x) ≀ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, Ξ» H, cInf_le ⟨0, Ξ» C, and.left⟩ ⟨C0, H⟩⟩ /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty (e : Β¬ nonempty Ξ±) : dist f g = 0 := le_antisymm ((dist_le (le_refl _)).2 $ Ξ» x, e.elim ⟨x⟩) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance : metric_space (Ξ± →ᡇ Ξ²) := { dist_self := Ξ» f, le_antisymm ((dist_le (le_refl _)).2 $ Ξ» x, by simp) dist_nonneg', eq_of_dist_eq_zero := Ξ» f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg β–Έ dist_coe_le_dist _) dist_nonneg), dist_comm := Ξ» f g, by simp [dist_eq, dist_comm], dist_triangle := Ξ» f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ Ξ» x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } def const (b : Ξ²) : Ξ± →ᡇ Ξ² := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩ /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited Ξ²] : inhabited (Ξ± →ᡇ Ξ²) := ⟨const (default Ξ²)⟩ /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval : continuous (Ξ» p : (Ξ± →ᡇ Ξ²) Γ— Ξ±, p.1 p.2) := continuous_iff'.2 $ Ξ» ⟨f, x⟩ Ξ΅ Ξ΅0, /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by Ξ΅/2 -/ let ⟨s, sx, Hs⟩ := continuous_iff'.1 f.2.1 x (Ξ΅/2) (half_pos Ξ΅0) in /- s : set Ξ±, sx : s ∈ 𝓝 x, Hs : βˆ€ (b : Ξ±), b ∈ s β†’ dist (f.val b) (f.val x) < Ξ΅ / 2 -/ ⟨set.prod (ball f (Ξ΅/2)) s, prod_mem_nhds_sets (ball_mem_nhds _ (half_pos Ξ΅0)) sx, Ξ» ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x) ≀ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _ ... < Ξ΅/2 + Ξ΅/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) (Hs _ hy) ... = Ξ΅ : add_halves _⟩ /-- In particular, when `x` is fixed, `f β†’ f x` is continuous -/ theorem continuous_evalx {x : Ξ±} : continuous (Ξ» f : Ξ± →ᡇ Ξ², f x) := continuous_eval.comp (continuous_id.prod_mk continuous_const) /-- When `f` is fixed, `x β†’ f x` is also continuous, by definition -/ theorem continuous_evalf {f : Ξ± →ᡇ Ξ²} : continuous f := f.2.1 /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space Ξ²] : complete_space (Ξ± →ᡇ Ξ²) := complete_of_cauchy_seq_tendsto $ Ξ» (f : β„• β†’ Ξ± →ᡇ Ξ²) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := Ξ»x n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : βˆ€x, cauchy_seq (Ξ»n, f n x) := Ξ»x, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using Ξ»x, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : Ξ± β†’ Ξ², hF : βˆ€ (x : Ξ±), tendsto (Ξ» (n : β„•), f n x) at_top (𝓝 (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : βˆ€x N, dist (f N x) (F x) ≀ b N := Ξ» x N, le_of_tendsto (by simp) (tendsto_dist tendsto_const_nhds (hF x)) (filter.mem_at_top_sets.2 ⟨N, Ξ»n hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨F, _, _⟩, _⟩, { /- Check that `F` is continuous -/ refine continuous_of_uniform_limit_of_continuous (Ξ» Ξ΅ Ξ΅0, _) (Ξ»N, (f N).2.1), rcases metric.tendsto_at_top.1 b_lim Ξ΅ Ξ΅0 with ⟨N, hN⟩, exact ⟨N, Ξ»y, calc dist (f N y) (F y) ≀ b N : fF_bdd y N ... ≀ dist (b N) 0 : begin simp, show b N ≀ abs(b N), from le_abs_self _ end ... ≀ Ξ΅ : le_of_lt (hN N (le_refl N))⟩ }, { /- Check that `F` is bounded -/ rcases (f 0).2.2 with ⟨C, hC⟩, exact ⟨C + (b 0 + b 0), Ξ» x y, calc dist (F x) (F y) ≀ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≀ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (Ξ» _, dist_nonneg) _ b_lim), exact Ξ» N, (dist_le (b0 _)).2 (Ξ»x, fF_bdd x N) } end /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : Ξ² β†’ Ξ³) (H : βˆ€x y, dist (G x) (G y) ≀ C * dist x y) (f : Ξ± →ᡇ Ξ²) : Ξ± →ᡇ Ξ³ := ⟨λx, G (f x), (continuous_of_lipschitz H).comp f.2.1, let ⟨D, hD⟩ := f.2.2 in ⟨max C 0 * D, Ξ» x y, calc dist (G (f x)) (G (f y)) ≀ C * dist (f x) (f y) : H _ _ ... ≀ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≀ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : Ξ² β†’ Ξ³} (H : βˆ€x y, dist (G x) (G y) ≀ C * dist x y) : continuous (comp G H : (Ξ± →ᡇ Ξ²) β†’ Ξ± →ᡇ Ξ³) := continuous_of_lipschitz $ Ξ» f g, (dist_le (mul_nonneg (le_max_right C 0) dist_nonneg)).2 $ Ξ» x, calc dist (G (f x)) (G (g x)) ≀ C * dist (f x) (g x) : H _ _ ... ≀ max C 0 * dist (f x) (g x) : mul_le_mul_of_nonneg_right (le_max_left C 0) (dist_nonneg) ... ≀ max C 0 * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) (le_max_right C 0) /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set Ξ²) (f : Ξ± →ᡇ Ξ²) (H : βˆ€x, f x ∈ s) : Ξ± →ᡇ s := ⟨λx, ⟨f x, H x⟩, continuous_subtype_mk _ f.2.1, f.2.2⟩ end basics section arzela_ascoli variables [topological_space Ξ±] [compact_space Ξ±] [metric_space Ξ²] variables {f g : Ξ± →ᡇ Ξ²} {x : Ξ±} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space Ξ²] (A : set (Ξ± →ᡇ Ξ²)) (closed : is_closed A) (H : βˆ€ (x:Ξ±) (Ξ΅ > 0), βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅) : compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (Ξ» Ξ΅ Ξ΅0, _), rcases dense Ξ΅0 with βŸ¨Ξ΅β‚, Ρ₁0, Ξ΅Ξ΅β‚βŸ©, let Ξ΅β‚‚ := Ρ₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to Ξ΅. This information will be provided by the values of `u` on a sufficiently dense set tΞ±, slightly translated to fit in a finite Ξ΅β‚‚-dense set tΞ² in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to Ξ΅, one uses the control on the modulus of continuity to extend the closeness on tΞ± to closeness everywhere. -/ have Ξ΅β‚‚0 : Ξ΅β‚‚ > 0 := half_pos (half_pos Ρ₁0), have : βˆ€x:Ξ±, βˆƒU, x ∈ U ∧ is_open U ∧ βˆ€ (y z ∈ U) {f : Ξ± →ᡇ Ξ²}, f ∈ A β†’ dist (f y) (f z) < Ξ΅β‚‚ := Ξ» x, let ⟨U, nhdsU, hU⟩ := H x _ Ξ΅β‚‚0, ⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in ⟨V, xV, openV, Ξ»y z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most Ξ΅β‚‚. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_elim_finite_subcover_image compact_univ (Ξ»x _, (hU x).2.1) (Ξ»x hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tΞ±, _, ⟨_⟩, htα⟩, /- tΞ± : set Ξ±, htΞ± : univ βŠ† ⋃x ∈ tΞ±, U x -/ rcases @finite_cover_balls_of_compact Ξ² _ _ compact_univ _ Ξ΅β‚‚0 with ⟨tΞ², _, ⟨_⟩, htβ⟩, resetI, /- tΞ² : set Ξ², htΞ² : univ βŠ† ⋃y ∈ tΞ², ball y Ξ΅β‚‚ -/ /- Associate to every point `y` in the space a nearby point `F y` in tΞ² -/ choose F hF using Ξ»y, show βˆƒz∈tΞ², dist y z < Ξ΅β‚‚, by simpa using htΞ² (mem_univ y), /- F : Ξ² β†’ Ξ², hF : βˆ€ (y : Ξ²), F y ∈ tΞ² ∧ dist y (F y) < Ξ΅β‚‚ -/ /- Associate to every function a discrete approximation, mapping each point in `tΞ±` to a point in `tΞ²` close to its true image by the function. -/ refine ⟨tΞ± β†’ tΞ², by apply_instance, Ξ» f a, ⟨F (f a), (hF (f a)).1⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance Ξ΅ -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt Ρ₁0).2 (Ξ» x, _)) ΡΡ₁, have : βˆƒx', x' ∈ tΞ± ∧ x ∈ U x' := mem_bUnion_iff.1 (htΞ± (mem_univ x)), rcases this with ⟨x', x'tΞ±, hx'⟩, refine calc dist (f x) (g x) ≀ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≀ Ξ΅β‚‚ + Ξ΅β‚‚ + Ρ₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = Ρ₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ _ hx' ((hU x').1) hf }, { exact (hU x').2.2 _ _ hx' ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (Ξ» f:tΞ± β†’ tΞ², (f ⟨x', x'tα⟩ : Ξ²)) f_eq_g : _), calc dist (f x') (g x') ≀ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < Ξ΅β‚‚ + Ξ΅β‚‚ : add_lt_add (hF (f x')).2 (hF (g x')).2 ... = Ρ₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoliβ‚‚ (s : set Ξ²) (hs : compact s) (A : set (Ξ± →ᡇ Ξ²)) (closed : is_closed A) (in_s : βˆ€(f : Ξ± →ᡇ Ξ²) (x : Ξ±), f ∈ A β†’ f x ∈ s) (H : βˆ€(x:Ξ±) (Ξ΅ > 0), βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅) : compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : βˆ€x y : s, dist (x : Ξ²) y ≀ 1 * dist x y := Ξ» x y, ge_of_eq (one_mul _), let F : (Ξ± →ᡇ s) β†’ Ξ± →ᡇ Ξ² := comp coe M, refine compact_of_is_closed_subset (compact_image (_ : compact (F ⁻¹' A)) (continuous_comp M)) closed (Ξ» f hf, _), { haveI : compact_space s := compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (Ξ» x Ξ΅ Ξ΅0, bex.imp_right (Ξ» U U_nhds hU y z hy hz f hf, _) (H x Ξ΅ Ξ΅0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < Ξ΅ : hU y z hy hz (F f) hf }, { let g := cod_restrict s f (Ξ»x, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊒, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli (s : set Ξ²) (hs : compact s) (A : set (Ξ± →ᡇ Ξ²)) (in_s : βˆ€(f : Ξ± →ᡇ Ξ²) (x : Ξ±), f ∈ A β†’ f x ∈ s) (H : βˆ€(x:Ξ±) (Ξ΅ > 0), βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅) : compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoliβ‚‚ s hs (closure A) is_closed_closure (Ξ» f x hf, (mem_of_closed' (closed_of_compact _ hs)).2 $ Ξ» Ξ΅ Ξ΅0, let ⟨g, gA, dist_fg⟩ := mem_closure_iff'.1 hf Ξ΅ Ξ΅0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (Ξ» x Ξ΅ Ξ΅0, show βˆƒ U ∈ 𝓝 x, βˆ€ y z ∈ U, βˆ€ (f : Ξ± →ᡇ Ξ²), f ∈ closure A β†’ dist (f y) (f z) < Ξ΅, begin refine bex.imp_right (Ξ» U U_set hU y z hy hz f hf, _) (H x (Ξ΅/2) (half_pos Ξ΅0)), rcases mem_closure_iff'.1 hf (Ξ΅/2/2) (half_pos (half_pos Ξ΅0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := Ξ» x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≀ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < Ξ΅/2/2 + Ξ΅/2/2 + Ξ΅/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA) ... = Ξ΅ : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {Ξ± : Type u} [metric_space Ξ±] (b : ℝ β†’ ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0)) (A : set (Ξ± →ᡇ Ξ²)) (H : βˆ€(x y:Ξ±) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f x) (f y) ≀ b (dist x y)) (x:Ξ±) (Ξ΅ : ℝ) (Ξ΅0 : Ξ΅ > 0) : βˆƒU ∈ 𝓝 x, βˆ€ (y z ∈ U) (f : Ξ± →ᡇ Ξ²), f ∈ A β†’ dist (f y) (f z) < Ξ΅ := begin rcases tendsto_nhds_nhds.1 b_lim Ξ΅ Ξ΅0 with ⟨δ, Ξ΄0, hδ⟩, refine ⟨ball x (Ξ΄/2), ball_mem_nhds x (half_pos Ξ΄0), Ξ» y z hy hz f hf, _⟩, have : dist y z < Ξ΄ := calc dist y z ≀ dist y x + dist z x : dist_triangle_right _ _ _ ... < Ξ΄/2 + Ξ΄/2 : add_lt_add hy hz ... = Ξ΄ : add_halves _, calc dist (f y) (f z) ≀ b (dist y z) : H y z f hf ... ≀ abs (b (dist y z)) : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < Ξ΅ : hΞ΄ (by simpa [real.dist_eq] using this), end end arzela_ascoli section normed_group /- In this section, if Ξ² is a normed group, then we show that the space of bounded continuous functions from Ξ± to Ξ² inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space Ξ±] [normed_group Ξ²] variables {f g : Ξ± →ᡇ Ξ²} {x : Ξ±} {C : ℝ} instance : has_zero (Ξ± →ᡇ Ξ²) := ⟨const 0⟩ @[simp] lemma coe_zero : (0 : Ξ± →ᡇ Ξ²) x = 0 := rfl instance : has_norm (Ξ± →ᡇ Ξ²) := ⟨λu, dist u 0⟩ lemma norm_def : βˆ₯fβˆ₯ = dist f 0 := rfl lemma norm_coe_le_norm (x : Ξ±) : βˆ₯f xβˆ₯ ≀ βˆ₯fβˆ₯ := calc βˆ₯f xβˆ₯ = dist (f x) ((0 : Ξ± →ᡇ Ξ²) x) : by simp [dist_zero_right] ... ≀ βˆ₯fβˆ₯ : dist_coe_le_dist _ /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≀ C) : βˆ₯fβˆ₯ ≀ C ↔ βˆ€x:Ξ±, βˆ₯f xβˆ₯ ≀ C := by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0 /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (Ξ± →ᡇ Ξ²) := ⟨λf g, ⟨λx, f x + g x, continuous_add f.2.1 g.2.1, (βˆ₯fβˆ₯ + βˆ₯gβˆ₯) + (βˆ₯fβˆ₯ + βˆ₯gβˆ₯), Ξ» x y, have βˆ€x, dist (f x + g x) 0 ≀ βˆ₯fβˆ₯ + βˆ₯gβˆ₯ := Ξ»x, calc dist (f x + g x) 0 = βˆ₯f x + g xβˆ₯ : dist_zero_right _ ... ≀ βˆ₯f xβˆ₯ + βˆ₯g xβˆ₯ : norm_triangle _ _ ... ≀ βˆ₯fβˆ₯ + βˆ₯gβˆ₯ : add_le_add (norm_coe_le_norm _) (norm_coe_le_norm _), calc dist (f x + g x) (f y + g y) ≀ dist (f x + g x) 0 + dist (f y + g y) 0 : dist_triangle_right _ _ _ ... ≀ (βˆ₯fβˆ₯ + βˆ₯gβˆ₯) + (βˆ₯fβˆ₯ + βˆ₯gβˆ₯) : add_le_add (this x) (this y) ⟩⟩ /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (Ξ± →ᡇ Ξ²) := ⟨λf, ⟨λx, -f x, continuous_neg f.2.1, begin have dn : βˆ€a b : Ξ², dist (-a) (-b) = dist a b := Ξ» a b, by rw [dist_eq_norm, neg_sub_neg, ← dist_eq_norm, dist_comm], simpa only [dn] using f.2.2 end⟩⟩ @[simp] lemma coe_add : (f + g) x = f x + g x := rfl @[simp] lemma coe_neg : (-f) x = - (f x) := rfl lemma forall_coe_zero_iff_zero : (βˆ€x, f x = 0) ↔ f = 0 := ⟨@ext _ _ _ _ f 0, by rintro rfl _; refl⟩ instance : add_comm_group (Ξ± →ᡇ Ξ²) := { add_assoc := assume f g h, by ext; simp, zero_add := assume f, by ext; simp, add_zero := assume f, by ext; simp, add_left_neg := assume f, by ext; simp, add_comm := assume f g, by ext; simp, ..bounded_continuous_function.has_add, ..bounded_continuous_function.has_neg, ..bounded_continuous_function.has_zero } @[simp] lemma coe_diff : (f - g) x = f x - g x := rfl instance : normed_group (Ξ± →ᡇ Ξ²) := normed_group.of_add_dist (Ξ» _, rfl) $ Ξ» f g h, (dist_le dist_nonneg).2 $ Ξ» x, le_trans (by rw [dist_eq_norm, dist_eq_norm, coe_add, coe_add, add_sub_add_right_eq_sub]) (dist_coe_le_dist x) lemma abs_diff_coe_le_dist : norm (f x - g x) ≀ dist f g := by rw normed_group.dist_eq; exact @norm_coe_le_norm _ _ _ _ (f-g) x lemma coe_le_coe_add_dist {f g : Ξ± →ᡇ ℝ} : f x ≀ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {Ξ± : Type u} {Ξ² : Type v} [topological_space Ξ±] [normed_group Ξ²] (f : Ξ± β†’ Ξ²) (C : ℝ) (H : βˆ€x, norm (f x) ≀ C) (Hf : continuous f) : Ξ± →ᡇ Ξ² := ⟨λn, f n, ⟨Hf, ⟨C + C, Ξ» m n, calc dist (f m) (f n) ≀ dist (f m) 0 + dist (f n) 0 : dist_triangle_right _ _ _ ... = norm (f m) + norm (f n) : by simp ... ≀ C + C : add_le_add (H m) (H n)⟩⟩⟩ /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {Ξ± : Type u} {Ξ² : Type v} [topological_space Ξ±] [discrete_topology Ξ±] [normed_group Ξ²] (f : Ξ± β†’ Ξ²) (C : ℝ) (H : βˆ€x, norm (f x) ≀ C) : Ξ± →ᡇ Ξ² := of_normed_group f C H continuous_of_discrete_topology end normed_group end bounded_continuous_function
9c2564e652a56b5d297c10b1ad2a1baa3de8b906
618003631150032a5676f229d13a079ac875ff77
/src/analysis/analytic/basic.lean
22b05164e0dfd2a85ab326f25c3a1e4052303c89
[ "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
38,112
lean
/- Copyright (c) 2020 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import analysis.calculus.times_cont_diff import tactic.omega import analysis.special_functions.pow /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Ξ£ pβ‚™ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pβ‚™` is a continuous `n`-multilinear map. In general, `pβ‚™` is not unique (in two dimensions, taking `pβ‚‚ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pβ‚™`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : β„•`. * `p.radius`: the largest `r : ennreal` such that `βˆ₯p nβˆ₯ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.bound_of_lt_radius`, `p.geometric_bound_of_lt_radius`: relating the value of the radius with the growth of `βˆ₯p nβˆ₯ * r^n`. * `p.partial_sum n x`: the sum `βˆ‘_{i = 0}^{n-1} pα΅’ xⁱ`. * `p.sum x`: the sum `βˆ‘'_{i = 0}^{∞} pα΅’ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = βˆ‘'_n pβ‚™ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at π•œ f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {π•œ : Type*} [nondiscrete_normed_field π•œ] {E : Type*} [normed_group E] [normed_space π•œ E] {F : Type*} [normed_group F] [normed_space π•œ F] {G : Type*} [normed_group G] [normed_space π•œ G] open_locale topological_space classical open filter /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series /-- The radius of a formal multilinear series is the largest `r` such that the sum `Ξ£ pβ‚™ yⁿ` converges for all `βˆ₯yβˆ₯ < r`. -/ def radius (p : formal_multilinear_series π•œ E F) : ennreal := liminf at_top (Ξ» n, 1/((nnnorm (p n)) ^ (1 / (n : ℝ)) : nnreal)) /--If `βˆ₯pβ‚™βˆ₯ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (p : formal_multilinear_series π•œ E F) (C : nnreal) {r : nnreal} (h : βˆ€ (n : β„•), nnnorm (p n) * r^n ≀ C) : (r : ennreal) ≀ p.radius := begin have L : tendsto (Ξ» n : β„•, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) at_top (𝓝 ((r : ennreal) / ((C + 1)^(0 : ℝ) : nnreal))), { apply ennreal.tendsto.div tendsto_const_nhds, { simp }, { rw ennreal.tendsto_coe, apply tendsto_const_nhds.nnrpow (tendsto_const_div_at_top_nhds_0_nat 1), simp }, { simp } }, have A : βˆ€ n : β„• , 0 < n β†’ (r : ennreal) ≀ ((C + 1)^(1/(n : ℝ)) : nnreal) * (1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal)), { assume n npos, simp only [one_div_eq_inv, mul_assoc, mul_one, eq.symm ennreal.mul_div_assoc], rw [ennreal.le_div_iff_mul_le _ _, ← nnreal.pow_nat_rpow_nat_inv r npos, ← ennreal.coe_mul, ennreal.coe_le_coe, ← nnreal.mul_rpow, mul_comm], { exact nnreal.rpow_le_rpow (le_trans (h n) (le_add_right (le_refl _))) (by simp) }, { simp }, { simp } }, have B : βˆ€αΆ  (n : β„•) in at_top, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal) ≀ 1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal), { apply eventually_at_top.2 ⟨1, Ξ» n hn, _⟩, rw [ennreal.div_le_iff_le_mul, mul_comm], { apply A n hn }, { simp }, { simp } }, have D : liminf at_top (Ξ» n : β„•, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) ≀ p.radius := liminf_le_liminf B, rw liminf_eq_of_tendsto filter.at_top_ne_bot L at D, simpa using D end /-- For `r` strictly smaller than the radius of `p`, then `βˆ₯pβ‚™βˆ₯ rⁿ` is bounded. -/ lemma bound_of_lt_radius (p : formal_multilinear_series π•œ E F) {r : nnreal} (h : (r : ennreal) < p.radius) : βˆƒ (C : nnreal), βˆ€ n, nnnorm (p n) * r^n ≀ C := begin obtain ⟨N, hN⟩ : βˆƒ (N : β„•), βˆ€ n, n β‰₯ N β†’ (r : ennreal) < 1 / ↑(nnnorm (p n) ^ (1 / (n : ℝ))) := eventually.exists_forall_of_at_top (eventually_lt_of_lt_liminf h), obtain ⟨D, hD⟩ : βˆƒD, βˆ€ x ∈ (↑((finset.range N.succ).image (Ξ» i, nnnorm (p i) * r^i))), x ≀ D := finset.bdd_above _, refine ⟨max D 1, Ξ» n, _⟩, cases le_or_lt n N with hn hn, { refine le_trans _ (le_max_left D 1), apply hD, have : n ∈ finset.range N.succ := list.mem_range.mpr (nat.lt_succ_iff.mpr hn), exact finset.mem_image_of_mem _ this }, { by_cases hpn : nnnorm (p n) = 0, { simp [hpn] }, have A : nnnorm (p n) ^ (1 / (n : ℝ)) β‰  0, by simp [nnreal.rpow_eq_zero_iff, hpn], have B : r < (nnnorm (p n) ^ (1 / (n : ℝ)))⁻¹, { have := hN n (le_of_lt hn), rwa [ennreal.div_def, ← ennreal.coe_inv A, one_mul, ennreal.coe_lt_coe] at this }, rw [nnreal.lt_inv_iff_mul_lt A, mul_comm] at B, have : (nnnorm (p n) ^ (1 / (n : ℝ)) * r) ^ n ≀ 1 := pow_le_one n (zero_le (nnnorm (p n) ^ (1 / ↑n) * r)) (le_of_lt B), rw [mul_pow, one_div_eq_inv, nnreal.rpow_nat_inv_pow_nat _ (lt_of_le_of_lt (zero_le _) hn)] at this, exact le_trans this (le_max_right _ _) }, end /-- For `r` strictly smaller than the radius of `p`, then `βˆ₯pβ‚™βˆ₯ rⁿ` tends to zero exponentially. -/ lemma geometric_bound_of_lt_radius (p : formal_multilinear_series π•œ E F) {r : nnreal} (h : (r : ennreal) < p.radius) : βˆƒ a C, a < 1 ∧ βˆ€ n, nnnorm (p n) * r^n ≀ C * a^n := begin obtain ⟨t, rt, tp⟩ : βˆƒ (t : nnreal), (r : ennreal) < t ∧ (t : ennreal) < p.radius := ennreal.lt_iff_exists_nnreal_btwn.1 h, rw ennreal.coe_lt_coe at rt, have tpos : t β‰  0 := ne_of_gt (lt_of_le_of_lt (zero_le _) rt), obtain ⟨C, hC⟩ : βˆƒ (C : nnreal), βˆ€ n, nnnorm (p n) * t^n ≀ C := p.bound_of_lt_radius tp, refine ⟨r / t, C, nnreal.div_lt_one_of_lt rt, Ξ» n, _⟩, calc nnnorm (p n) * r ^ n = (nnnorm (p n) * t ^ n) * (r / t) ^ n : by { field_simp [tpos], ac_refl } ... ≀ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (zero_le _) end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series π•œ E F) : min p.radius q.radius ≀ (p + q).radius := begin refine le_of_forall_ge_of_dense (Ξ» r hr, _), cases r, { simpa using hr }, obtain ⟨Cp, hCp⟩ : βˆƒ (C : nnreal), βˆ€ n, nnnorm (p n) * r^n ≀ C := p.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_left _ _)), obtain ⟨Cq, hCq⟩ : βˆƒ (C : nnreal), βˆ€ n, nnnorm (q n) * r^n ≀ C := q.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_right _ _)), have : βˆ€ n, nnnorm ((p + q) n) * r^n ≀ Cp + Cq, { assume n, calc nnnorm (p n + q n) * r ^ n ≀ (nnnorm (p n) + nnnorm (q n)) * r ^ n : mul_le_mul_of_nonneg_right (norm_add_le (p n) (q n)) (zero_le (r ^ n)) ... ≀ Cp + Cq : by { rw add_mul, exact add_le_add (hCp n) (hCq n) } }, exact (p + q).le_radius_of_bound _ this end lemma radius_neg (p : formal_multilinear_series π•œ E F) : (-p).radius = p.radius := by simp [formal_multilinear_series.radius, nnnorm_neg] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Ξ£ pβ‚™ xⁿ`. A priori, it only behaves well when `βˆ₯xβˆ₯ < p.radius`. -/ protected def sum (p : formal_multilinear_series π•œ E F) (x : E) : F := tsum (Ξ»n:β„•, p n (Ξ»(i : fin n), x)) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Ξ£ pβ‚– xᡏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series π•œ E F) (n : β„•) (x : E) : F := (finset.range n).sum (Ξ» k, p k (Ξ»(i : fin k), x)) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series π•œ E F) (n : β„•) : continuous (p.partial_sum n) := continuous_finset_sum (finset.range n) $ Ξ» k hk, (p k).cont.comp (continuous_pi (Ξ» i, continuous_id)) end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E β†’ F} {p pf pg : formal_multilinear_series π•œ E F} {x : E} {r r' : ennreal} /-- Given a function `f : E β†’ F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = βˆ‘' pβ‚™ yⁿ` for all `βˆ₯yβˆ₯ < r`. -/ structure has_fpower_series_on_ball (f : E β†’ F) (p : formal_multilinear_series π•œ E F) (x : E) (r : ennreal) : Prop := (r_le : r ≀ p.radius) (r_pos : 0 < r) (has_sum : βˆ€ {y}, y ∈ emetric.ball (0 : E) r β†’ has_sum (Ξ»n:β„•, p n (Ξ»(i : fin n), y)) (f (x + y))) /-- Given a function `f : E β†’ F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = βˆ‘' pβ‚™ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E β†’ F) (p : formal_multilinear_series π•œ E F) (x : E) := βˆƒ r, has_fpower_series_on_ball f p x r variable (π•œ) /-- Given a function `f : E β†’ F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E β†’ F) (x : E) := βˆƒ (p : formal_multilinear_series π•œ E F), has_fpower_series_at f p x variable {π•œ} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at π•œ f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at π•œ f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≀ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, Ξ» y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := Ξ» y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases hf with ⟨rf, hrf⟩, rcases hg with ⟨rg, hrg⟩, have P : 0 < min rf rg, by simp [hrf.r_pos, hrg.r_pos], exact ⟨min rf rg, (hrf.mono P (min_le_left _ _)).add (hrg.mono P (min_le_right _ _))⟩ end lemma analytic_at.add (hf : analytic_at π•œ f x) (hg : analytic_at π•œ g x) : analytic_at π•œ (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := Ξ» y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at π•œ f x) : analytic_at π•œ (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := hf.add hg.neg lemma analytic_at.sub (hf : analytic_at π•œ f x) (hg : analytic_at π•œ g x) : analytic_at π•œ (f - g) x := hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 β†’ E) : pf 0 v = f x := begin have v_eq : v = (Ξ» i, 0), by { ext i, apply fin_zero_elim i }, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : βˆ€ i β‰  0, pf i (Ξ» j, 0) = 0, { assume i hi, have : 0 < i := bot_lt_iff_ne_bot.mpr hi, apply continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i), refl }, have A := has_sum_unique (hf.has_sum zero_mem) (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 β†’ E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : βˆƒ (a C : nnreal), a < 1 ∧ (βˆ€ y ∈ metric.ball (0 : E) r', βˆ€ n, βˆ₯f (x + y) - p.partial_sum n yβˆ₯ ≀ C * a ^ n) := begin obtain ⟨a, C, ha, hC⟩ : βˆƒ a C, a < 1 ∧ βˆ€ n, nnnorm (p n) * r' ^n ≀ C * a^n := p.geometric_bound_of_lt_radius (lt_of_lt_of_le h hf.r_le), refine ⟨a, C / (1 - a), ha, Ξ» y hy n, _⟩, have yr' : βˆ₯yβˆ₯ < r', by { rw ball_0_eq at hy, exact hy }, have : y ∈ emetric.ball (0 : E) r, { rw [emetric.mem_ball, edist_eq_coe_nnnorm], apply lt_trans _ h, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe], exact yr' }, simp only [nnreal.coe_sub (le_of_lt ha), nnreal.coe_sub, nnreal.coe_div, nnreal.coe_one], rw [← dist_eq_norm, dist_comm, dist_eq_norm, ← mul_div_right_comm], apply norm_sub_le_of_geometric_bound_of_has_sum ha _ (hf.has_sum this), assume n, calc βˆ₯(p n) (Ξ» (i : fin n), y)βˆ₯ ≀ βˆ₯p nβˆ₯ * (finset.univ.prod (Ξ» i : fin n, βˆ₯yβˆ₯)) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≀ nnnorm (p n) * r' ^ n : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left (nnreal.coe_nonneg _) (le_of_lt yr') _) (nnreal.coe_nonneg _) ... ≀ C * a ^ n : by exact_mod_cast hC n, end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (Ξ» n y, p.partial_sum n y) (Ξ» y, f (x + y)) at_top (metric.ball (0 : E) r') := begin rcases hf.uniform_geometric_approx h with ⟨a, C, ha, hC⟩, refine metric.tendsto_uniformly_on_iff.2 (Ξ» Ξ΅ Ξ΅pos, _), have L : tendsto (Ξ» n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 (a.2) ha), rw mul_zero at L, apply ((tendsto_order.1 L).2 Ξ΅ Ξ΅pos).mono (Ξ» n hn, _), assume y hy, rw dist_eq_norm, exact lt_of_le_of_lt (hC y hy n) hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (Ξ» n y, p.partial_sum n y) (Ξ» y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := mem_nhds_sets emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (Ξ» n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (Ξ» y, y - x), { ext z, simp }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (Ξ» n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (Ξ» (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (Ξ» (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := begin apply hf.tendsto_locally_uniformly_on'.continuous_on _ at_top_ne_bot, exact Ξ» n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on end lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at π•œ f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series π•œ E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := Ξ» y hy, begin rw zero_add, replace hy : (nnnorm y : ennreal) < p.radius, by { convert hy, exact (edist_eq_coe_nnnorm _).symm }, obtain ⟨a, C, ha, hC⟩ : βˆƒ a C, a < 1 ∧ βˆ€ n, nnnorm (p n) * (nnnorm y)^n ≀ C * a^n := p.geometric_bound_of_lt_radius hy, refine (summable_of_norm_bounded (Ξ» n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 a.2 ha).mul_left _) (Ξ» n, _)).has_sum, calc βˆ₯(p n) (Ξ» (i : fin n), y)βˆ₯ ≀ βˆ₯p nβˆ₯ * (finset.univ.prod (Ξ» i : fin n, βˆ₯yβˆ₯)) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≀ C * a ^ n : by exact_mod_cast hC n end } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := begin have A := h.has_sum hy, have B := (p.has_fpower_series_on_ball h.radius_pos).has_sum (lt_of_lt_of_le hy h.r_le), simpa using has_sum_unique A B end /-- The sum of a converging power series is continuous in its disk of convergence. -/ lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin by_cases h : 0 < p.radius, { exact (p.has_fpower_series_on_ball h).continuous_on }, { simp at h, simp [h, continuous_on_empty] } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \choose n k p_n y^{n-k} z^k = \sum_{k} (\sum_{n} \choose n k p_n y^{n-k}) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to `\sum_{n} \choose n k p_n y^{n-k}`. In the general case where `pβ‚™` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series variables (p : formal_multilinear_series π•œ E F) {x y : E} {r : nnreal} /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Here, we don't use the bracket notation `⟨n, s, hs⟩` in place of the argument `i` in the lambda, as this leads to a bad definition with auxiliary `_match` statements, but we will try to use pattern matching in lambdas as much as possible in the proofs below to increase readability. -/ def change_origin (x : E) : formal_multilinear_series π•œ E F := Ξ» k, tsum (Ξ»i, (p i.1).restr i.2.1 i.2.2 x : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ (E [Γ—k]β†’L[π•œ] F)) /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, first version. -/ -- Note here and below it is necessary to use `@` and provide implicit arguments using `_`, -- so that it is possible to use pattern matching in the lambda. -- Overall this seems a good trade-off in readability. lemma change_origin_summable_aux1 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((Ξ» ⟨n, s⟩, βˆ₯p nβˆ₯ * βˆ₯xβˆ₯ ^ (n - s.card) * r ^ s.card) : (Ξ£ (n : β„•), finset (fin n)) β†’ ℝ) := begin obtain ⟨a, C, ha, hC⟩ : βˆƒ a C, a < 1 ∧ βˆ€ n, nnnorm (p n) * (nnnorm x + r) ^ n ≀ C * a^n := p.geometric_bound_of_lt_radius h, let Bnnnorm : (Ξ£ (n : β„•), finset (fin n)) β†’ nnreal := Ξ» ⟨n, s⟩, nnnorm (p n) * (nnnorm x) ^ (n - s.card) * r ^ s.card, have : ((Ξ» ⟨n, s⟩, βˆ₯p nβˆ₯ * βˆ₯xβˆ₯ ^ (n - s.card) * r ^ s.card) : (Ξ£ (n : β„•), finset (fin n)) β†’ ℝ) = (Ξ» b, (Bnnnorm b : ℝ)), by { ext b, rcases b with ⟨n, s⟩, simp [Bnnnorm, nnreal.coe_pow, coe_nnnorm] }, rw [this, nnreal.summable_coe, ← ennreal.tsum_coe_ne_top_iff_summable], apply ne_of_lt, calc (βˆ‘' b, ↑(Bnnnorm b)) = (βˆ‘' n, (βˆ‘' s, ↑(Bnnnorm ⟨n, s⟩))) : by exact ennreal.tsum_sigma' _ ... ≀ (βˆ‘' n, (((nnnorm (p n) * (nnnorm x + r)^n) : nnreal) : ennreal)) : begin refine ennreal.tsum_le_tsum (Ξ» n, _), rw [tsum_fintype, ← ennreal.coe_finset_sum, ennreal.coe_le_coe], apply le_of_eq, calc finset.univ.sum (Ξ» (s : finset (fin n)), Bnnnorm ⟨n, s⟩) = finset.univ.sum (Ξ» (s : finset (fin n)), nnnorm (p n) * ((nnnorm x) ^ (n - s.card) * r ^ s.card)) : by simp [← mul_assoc] ... = nnnorm (p n) * (nnnorm x + r) ^ n : by { rw [add_comm, ← finset.mul_sum, ← fin.sum_pow_mul_eq_add_pow], congr, ext s, ring } end ... ≀ (βˆ‘' (n : β„•), (C * a ^ n : ennreal)) : tsum_le_tsum (Ξ» n, by exact_mod_cast hC n) ennreal.summable ennreal.summable ... < ⊀ : by simp [ennreal.mul_eq_top, ha, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.lt_top_iff_ne_top] end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, second version. -/ lemma change_origin_summable_aux2 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((Ξ» ⟨k, n, s, hs⟩, βˆ₯(p n).restr s hs xβˆ₯ * ↑r ^ k) : (Ξ£ (k : β„•) (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ ℝ) := begin let Ξ³ : β„• β†’ Type* := Ξ» k, (Ξ£ (n : β„•), {s : finset (fin n) // s.card = k}), let Bnorm : (Ξ£ (n : β„•), finset (fin n)) β†’ ℝ := Ξ» ⟨n, s⟩, βˆ₯p nβˆ₯ * βˆ₯xβˆ₯ ^ (n - s.card) * r ^ s.card, have SBnorm : summable Bnorm := p.change_origin_summable_aux1 h, let Anorm : (Ξ£ (n : β„•), finset (fin n)) β†’ ℝ := Ξ» ⟨n, s⟩, βˆ₯(p n).restr s rfl xβˆ₯ * r ^ s.card, have SAnorm : summable Anorm, { refine summable_of_norm_bounded _ SBnorm (Ξ» i, _), rcases i with ⟨n, s⟩, suffices H : βˆ₯(p n).restr s rfl xβˆ₯ * (r : ℝ) ^ s.card ≀ (βˆ₯p nβˆ₯ * βˆ₯xβˆ₯ ^ (n - finset.card s) * r ^ s.card), { have : βˆ₯(r: ℝ)βˆ₯ = r, by rw [real.norm_eq_abs, abs_of_nonneg (nnreal.coe_nonneg _)], simpa [Anorm, Bnorm, this] using H }, exact mul_le_mul_of_nonneg_right ((p n).norm_restr s rfl x) (pow_nonneg (nnreal.coe_nonneg _) _) }, let e : (Ξ£ (n : β„•), finset (fin n)) ≃ (Ξ£ (k : β„•) (n : β„•), {s : finset (fin n) // finset.card s = k}) := { to_fun := Ξ» ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := Ξ» ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := Ξ» ⟨n, s⟩, rfl, right_inv := Ξ» ⟨k, n, s, hs⟩, by { induction hs, refl } }, rw ← e.summable_iff, convert SAnorm, ext i, rcases i with ⟨n, s⟩, refl end /-- An auxiliary definition for `change_origin_radius`. -/ def change_origin_summable_aux_j (k : β„•) : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ (Ξ£ (k : β„•) (n : β„•), {s : finset (fin n) // finset.card s = k}) := Ξ» ⟨n, s, hs⟩, ⟨k, n, s, hs⟩ lemma change_origin_summable_aux_j_inj (k : β„•) : function.injective (change_origin_summable_aux_j k) := begin rintros ⟨_, ⟨_, _⟩⟩ ⟨_, ⟨_, _⟩⟩ a, simp only [change_origin_summable_aux_j, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff] at a, rcases a with ⟨rfl, a⟩, simpa using a, end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, third version. -/ lemma change_origin_summable_aux3 (k : β„•) (h : (nnnorm x : ennreal) < p.radius) : @summable ℝ _ _ _ (Ξ» ⟨n, s, hs⟩, βˆ₯(p n).restr s hs xβˆ₯ : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ ℝ) := begin obtain ⟨r, rpos, hr⟩ : βˆƒ (r : nnreal), 0 < r ∧ ((nnnorm x + r) : ennreal) < p.radius := ennreal.lt_iff_exists_add_pos_lt.mp h, have S : @summable ℝ _ _ _ ((Ξ» ⟨n, s, hs⟩, βˆ₯(p n).restr s hs xβˆ₯ * (r : ℝ) ^ k) : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ ℝ), { convert summable.summable_comp_of_injective (p.change_origin_summable_aux2 hr) (change_origin_summable_aux_j_inj k), -- again, cleanup that could be done by `tidy`: ext p, rcases p with ⟨_, ⟨_, _⟩⟩, refl }, have : (r : ℝ)^k β‰  0, by simp [pow_ne_zero, nnreal.coe_eq_zero, ne_of_gt rpos], apply (summable_mul_right_iff this).2, convert S, -- again, cleanup that could be done by `tidy`: ext p, rcases p with ⟨_, ⟨_, _⟩⟩, refl, end -- FIXME this causes a deterministic timeout with `-T50000` /-- The radius of convergence of `p.change_origin x` is at least `p.radius - βˆ₯xβˆ₯`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - nnnorm x ≀ (p.change_origin x).radius := begin by_cases h : p.radius ≀ nnnorm x, { have : radius p - ↑(nnnorm x) = 0 := ennreal.sub_eq_zero_of_le h, rw this, exact zero_le _ }, replace h : (nnnorm x : ennreal) < p.radius, by simpa using h, refine le_of_forall_ge_of_dense (Ξ» r hr, _), cases r, { simpa using hr }, rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, let A : (Ξ£ (k : β„•) (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ ℝ := Ξ» ⟨k, n, s, hs⟩, βˆ₯(p n).restr s hs xβˆ₯ * (r : ℝ) ^ k, have SA : summable A := p.change_origin_summable_aux2 hr, have A_nonneg : βˆ€ i, 0 ≀ A i, { rintros ⟨k, n, s, hs⟩, change 0 ≀ βˆ₯(p n).restr s hs xβˆ₯ * (r : ℝ) ^ k, refine mul_nonneg (norm_nonneg _) (pow_nonneg (nnreal.coe_nonneg _) _) }, have tsum_nonneg : 0 ≀ tsum A := tsum_nonneg A_nonneg, apply le_radius_of_bound _ (nnreal.of_real (tsum A)) (Ξ» k, _), rw [← nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_pow, coe_nnnorm, nnreal.coe_of_real _ tsum_nonneg], calc βˆ₯change_origin p x kβˆ₯ * ↑r ^ k = βˆ₯@tsum (E [Γ—k]β†’L[π•œ] F) _ _ _ (Ξ» i, (p i.1).restr i.2.1 i.2.2 x : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ (E [Γ—k]β†’L[π•œ] F))βˆ₯ * ↑r ^ k : rfl ... ≀ tsum (Ξ» i, βˆ₯(p i.1).restr i.2.1 i.2.2 xβˆ₯ : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ ℝ) * ↑r ^ k : begin apply mul_le_mul_of_nonneg_right _ (pow_nonneg (nnreal.coe_nonneg _) _), apply norm_tsum_le_tsum_norm, convert p.change_origin_summable_aux3 k h, ext a, tidy end ... = tsum (Ξ» i, βˆ₯(p i.1).restr i.2.1 i.2.2 xβˆ₯ * ↑r ^ k : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ ℝ) : by { rw tsum_mul_right, convert p.change_origin_summable_aux3 k h, tidy } ... = tsum (A ∘ change_origin_summable_aux_j k) : by { congr, tidy } ... ≀ tsum A : tsum_comp_le_tsum_of_inj SA A_nonneg (change_origin_summable_aux_j_inj k) end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variable [complete_space F] /-- The `k`-th coefficient of `p.change_origin` is the sum of a summable series. -/ lemma change_origin_has_sum (k : β„•) (h : (nnnorm x : ennreal) < p.radius) : @has_sum (E [Γ—k]β†’L[π•œ] F) _ _ _ ((Ξ» i, (p i.1).restr i.2.1 i.2.2 x) : (Ξ£ (n : β„•), {s : finset (fin n) // finset.card s = k}) β†’ (E [Γ—k]β†’L[π•œ] F)) (p.change_origin x k) := begin apply summable.has_sum, apply summable_of_summable_norm, convert p.change_origin_summable_aux3 k h, tidy end /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (nnnorm x + nnnorm y : ennreal) < p.radius) : has_sum ((Ξ»k:β„•, p.change_origin x k (Ξ» (i : fin k), y))) (p.sum (x + y)) := begin /- The series on the left is a series of series. If we order the terms differently, we get back to `p.sum (x + y)`, in which the `n`-th term is expanded by multilinearity. In the proof below, the term on the left is the sum of a series of terms `A`, the sum on the right is the sum of a series of terms `B`, and we show that they correspond to each other by reordering to conclude the proof. -/ have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, -- `A` is the terms of the series whose sum gives the series for `p.change_origin` let A : (Ξ£ (k : β„•) (n : β„•), {s : finset (fin n) // s.card = k}) β†’ F := Ξ» ⟨k, n, s, hs⟩, (p n).restr s hs x (Ξ»(i : fin k), y), -- `B` is the terms of the series whose sum gives `p (x + y)`, after expansion by multilinearity. let B : (Ξ£ (n : β„•), finset (fin n)) β†’ F := Ξ» ⟨n, s⟩, (p n).restr s rfl x (Ξ» (i : fin s.card), y), let Bnorm : (Ξ£ (n : β„•), finset (fin n)) β†’ ℝ := Ξ» ⟨n, s⟩, βˆ₯p nβˆ₯ * βˆ₯xβˆ₯ ^ (n - s.card) * βˆ₯yβˆ₯ ^ s.card, have SBnorm : summable Bnorm, by convert p.change_origin_summable_aux1 h, have SB : summable B, { refine summable_of_norm_bounded _ SBnorm _, rintros ⟨n, s⟩, calc βˆ₯(p n).restr s rfl x (Ξ» (i : fin s.card), y)βˆ₯ ≀ βˆ₯(p n).restr s rfl xβˆ₯ * βˆ₯yβˆ₯ ^ s.card : begin convert ((p n).restr s rfl x).le_op_norm (Ξ» (i : fin s.card), y), simp [(finset.prod_const (βˆ₯yβˆ₯))], end ... ≀ (βˆ₯p nβˆ₯ * βˆ₯xβˆ₯ ^ (n - s.card)) * βˆ₯yβˆ₯ ^ s.card : mul_le_mul_of_nonneg_right ((p n).norm_restr _ _ _) (pow_nonneg (norm_nonneg _) _) }, -- Check that indeed the sum of `B` is `p (x + y)`. have has_sum_B : has_sum B (p.sum (x + y)), { have K1 : βˆ€ n, has_sum (Ξ» (s : finset (fin n)), B ⟨n, s⟩) (p n (Ξ» (i : fin n), x + y)), { assume n, have : (p n) (Ξ» (i : fin n), y + x) = finset.univ.sum (Ξ» (s : finset (fin n)), p n (finset.piecewise s (Ξ» (i : fin n), y) (Ξ» (i : fin n), x))) := (p n).map_add_univ (Ξ» i, y) (Ξ» i, x), simp [add_comm y x] at this, rw this, exact has_sum_fintype _ }, have K2 : has_sum (Ξ» (n : β„•), (p n) (Ξ» (i : fin n), x + y)) (p.sum (x + y)), { have : x + y ∈ emetric.ball (0 : E) p.radius, { apply lt_of_le_of_lt _ h, rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le x y }, simpa using (p.has_fpower_series_on_ball radius_pos).has_sum this }, exact has_sum.sigma_of_has_sum K2 K1 SB }, -- Deduce that the sum of `A` is also `p (x + y)`, as the terms `A` and `B` are the same up to -- reordering have has_sum_A : has_sum A (p.sum (x + y)), { let e : (Ξ£ (n : β„•), finset (fin n)) ≃ (Ξ£ (k : β„•) (n : β„•), {s : finset (fin n) // finset.card s = k}) := { to_fun := Ξ» ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := Ξ» ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := Ξ» ⟨n, s⟩, rfl, right_inv := Ξ» ⟨k, n, s, hs⟩, by { induction hs, refl } }, have : A ∘ e = B, by { ext x, cases x, refl }, rw ← e.has_sum_iff, convert has_sum_B }, -- Summing `A ⟨k, c⟩` with fixed `k` and varying `c` is exactly the `k`-th term in the series -- defining `p.change_origin`, by definition have J : βˆ€k, has_sum (Ξ» c, A ⟨k, c⟩) (p.change_origin x k (Ξ»(i : fin k), y)), { assume k, have : (nnnorm x : ennreal) < radius p := lt_of_le_of_lt (le_add_right (le_refl _)) h, convert continuous_multilinear_map.has_sum_eval (p.change_origin_has_sum k this) (Ξ»(i : fin k), y), ext i, tidy }, exact has_sum_A.sigma J end end formal_multilinear_series section variables [complete_space F] {f : E β†’ F} {p : formal_multilinear_series π•œ E F} {x y : E} {r : ennreal} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (nnnorm y : ennreal) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - nnnorm y) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := begin assume z hz, have A : (nnnorm y : ennreal) + nnnorm z < r, { have : edist z 0 < r - ↑(nnnorm y) := hz, rwa [edist_eq_coe_nnnorm, ennreal.lt_sub_iff_add_lt, add_comm] at this }, convert p.change_origin_eval (lt_of_lt_of_le A hf.r_le), have : y + z ∈ emetric.ball (0 : E) r := calc edist (y + z) 0 ≀ ↑(nnnorm y) + ↑(nnnorm z) : by { rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le y z } ... < r : A, simpa only [add_assoc] using hf.sum this end } lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at π•œ f y := begin have : (nnnorm (y - x) : ennreal) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (π•œ f) lemma is_open_analytic_at : is_open {x | analytic_at π•œ f x} := begin rw is_open_iff_forall_mem_open, assume x hx, rcases hx with ⟨p, r, hr⟩, refine ⟨emetric.ball x r, Ξ» y hy, hr.analytic_at_of_mem hy, emetric.is_open_ball, _⟩, simp only [edist_self, emetric.mem_ball, hr.r_pos] end variables {π•œ f} end
4c69f52aaf1402660243313a8e36acf28f72901b
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/e14.lean
c70cb9e1990d0467c585920294a876c3d8186f8c
[ "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
878
lean
prelude inductive nat : Type := zero : nat, succ : nat β†’ nat namespace nat end nat open nat inductive list (A : Type) : Type := nil {} : list A, cons : A β†’ list A β†’ list A definition nil := @list.nil definition cons := @list.cons check nil check nil.{1} check @nil.{1} nat check @nil nat check cons nat.zero nil inductive vector (A : Type) : nat β†’ Type := vnil {} : vector A zero, vcons : forall {n : nat}, A β†’ vector A n β†’ vector A (succ n) namespace vector end vector open vector check vcons zero vnil constant n : nat check vcons n vnil check vector.rec definition vector_to_list {A : Type} {n : nat} (v : vector A n) : list A := vector.rec (@nil A) (fun (n : nat) (a : A) (v : vector A n) (l : list A), cons a l) v attribute vector_to_list [coercion] constant f : forall {A : Type}, list A β†’ nat check f (cons zero nil) check f (vcons zero vnil)
2791fb7bdaf1fee06885508d055fc11efb87e8c8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/precissues.lean
078cde74478d24ea402d4f56f50eee1dca29c5d9
[ "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
692
lean
#check id fun x => x -- should work #check 0 def f (x : Nat) (g : Nat β†’ Nat) := g x #check f 1 fun x => x -- should fail #check 0 #check f 1 (fun x => x) #check id have : True := ⟨⟩; this -- should fail #check id let x := 10; x #check 1 #check id (have : True := ⟨⟩; this) #check 0 = have : Nat := 1; this #check 0 = let x := 0; x variable (p q r : Prop) macro_rules | `(Β¬ $p) => `(Not $p) #check p ↔ Β¬ q #check True = Β¬ False #check p ∧ Β¬q #check Β¬p ∧ q #check Β¬p ↔ q #check Β¬(p = q) #check Β¬ p = q #check id Β¬p #check Nat β†’ βˆ€ (a : Nat), a = a macro "foo!" x:term : term => `($x + 1) #check id foo! 10 -- error, `foo! x` precedence is leadPrec
2f043f5eaaa7e23d71aa9da8a40c5afbaa020afe
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/back_chaining4.lean
0cd02cec1bca4007f12d8876860d77741ca4577b
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,171
lean
-- Backward chaining with hypotheses constants {P Q R S T U : Prop} constants (Huq : U β†’ Q) (Hur : U β†’ R) (Hus : U β†’ S) (Hut : U β†’ T) attribute [intro] Huq Hur Hus Hut open tactic definition lemma4 : (P β†’ Q) β†’ (Q β†’ R) β†’ (R β†’ S) β†’ (S β†’ T) β†’ P β†’ T := by do H1 ← intro `H1, H2 ← intro `H2, H3 ← intro `H3, H4 ← intro `H4, H5 ← intro `H5, /- Construct lemma set manually -/ lemmas ← mk_back_lemmas, trace "lemmas for target: ", target >>= back_lemmas_find lemmas >>= trace >> trace "-----", trace "lemmas for H3 body: ", infer_type H3 >>= (Ξ» t, back_lemmas_find lemmas (expr.binding_body t)) >>= trace >> trace "-----", lemmas ← back_lemmas_insert lemmas H1, lemmas ← back_lemmas_insert lemmas H2, lemmas ← back_lemmas_insert lemmas H3, lemmas ← back_lemmas_insert lemmas H4, lemmas ← back_lemmas_insert lemmas H5, trace "lemmas for H3 body (after update): ", infer_type H3 >>= (Ξ» t, back_lemmas_find lemmas (expr.binding_body t)) >>= trace >> trace "-----", /- Execute backward_chaining_core using hand-crafted lemma set -/ backward_chaining_core reducible tt 10 skip failed lemmas
8faac02ef9becc5cdfe760f56f22d85b6a4066c4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/category/UniformSpace.lean
226cd5660816557c2fa0b36ba7dcaa52589610b0
[ "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
7,335
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Patrick Massot, Scott Morrison -/ import category_theory.adjunction.reflective import category_theory.concrete_category.unbundled_hom import category_theory.monad.limits import topology.category.Top.basic import topology.uniform_space.completion /-! # The category of uniform spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We construct the category of uniform spaces, show that the complete separated uniform spaces form a reflective subcategory, and hence possess all limits that uniform spaces do. TODO: show that uniform spaces actually have all limits! -/ universes u open category_theory /-- A (bundled) uniform space. -/ def UniformSpace : Type (u+1) := bundled uniform_space namespace UniformSpace /-- The information required to build morphisms for `UniformSpace`. -/ instance : unbundled_hom @uniform_continuous := ⟨@uniform_continuous_id, @uniform_continuous.comp⟩ attribute [derive [large_category, concrete_category]] UniformSpace instance : has_coe_to_sort UniformSpace Type* := bundled.has_coe_to_sort instance (x : UniformSpace) : uniform_space x := x.str /-- Construct a bundled `UniformSpace` from the underlying type and the typeclass. -/ def of (Ξ± : Type u) [uniform_space Ξ±] : UniformSpace := ⟨α⟩ instance : inhabited UniformSpace := ⟨UniformSpace.of empty⟩ @[simp] lemma coe_of (X : Type u) [uniform_space X] : (of X : Type u) = X := rfl instance (X Y : UniformSpace) : has_coe_to_fun (X ⟢ Y) (Ξ» _, X β†’ Y) := ⟨category_theory.functor.map (forget UniformSpace)⟩ @[simp] lemma coe_comp {X Y Z : UniformSpace} (f : X ⟢ Y) (g : Y ⟢ Z) : (f ≫ g : X β†’ Z) = g ∘ f := rfl @[simp] lemma coe_id (X : UniformSpace) : (πŸ™ X : X β†’ X) = id := rfl @[simp] lemma coe_mk {X Y : UniformSpace} (f : X β†’ Y) (hf : uniform_continuous f) : ((⟨f, hf⟩ : X ⟢ Y) : X β†’ Y) = f := rfl lemma hom_ext {X Y : UniformSpace} {f g : X ⟢ Y} : (f : X β†’ Y) = g β†’ f = g := subtype.eq /-- The forgetful functor from uniform spaces to topological spaces. -/ instance has_forget_to_Top : has_forgetβ‚‚ UniformSpace.{u} Top.{u} := { forgetβ‚‚ := { obj := Ξ» X, Top.of X, map := Ξ» X Y f, { to_fun := f, continuous_to_fun := uniform_continuous.continuous f.property }, }, } end UniformSpace /-- A (bundled) complete separated uniform space. -/ structure CpltSepUniformSpace := (Ξ± : Type u) [is_uniform_space : uniform_space Ξ±] [is_complete_space : complete_space Ξ±] [is_separated : separated_space Ξ±] namespace CpltSepUniformSpace instance : has_coe_to_sort CpltSepUniformSpace (Type u) := ⟨CpltSepUniformSpace.α⟩ attribute [instance] is_uniform_space is_complete_space is_separated /-- The function forgetting that a complete separated uniform spaces is complete and separated. -/ def to_UniformSpace (X : CpltSepUniformSpace) : UniformSpace := UniformSpace.of X instance complete_space (X : CpltSepUniformSpace) : complete_space ((to_UniformSpace X).Ξ±) := CpltSepUniformSpace.is_complete_space X instance separated_space (X : CpltSepUniformSpace) : separated_space ((to_UniformSpace X).Ξ±) := CpltSepUniformSpace.is_separated X /-- Construct a bundled `UniformSpace` from the underlying type and the appropriate typeclasses. -/ def of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] : CpltSepUniformSpace := ⟨X⟩ @[simp] lemma coe_of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] : (of X : Type u) = X := rfl instance : inhabited CpltSepUniformSpace := begin haveI : separated_space empty := separated_iff_t2.mpr (by apply_instance), exact ⟨CpltSepUniformSpace.of empty⟩ end /-- The category instance on `CpltSepUniformSpace`. -/ instance category : large_category CpltSepUniformSpace := induced_category.category to_UniformSpace /-- The concrete category instance on `CpltSepUniformSpace`. -/ instance concrete_category : concrete_category CpltSepUniformSpace := induced_category.concrete_category to_UniformSpace instance has_forget_to_UniformSpace : has_forgetβ‚‚ CpltSepUniformSpace UniformSpace := induced_category.has_forgetβ‚‚ to_UniformSpace end CpltSepUniformSpace namespace UniformSpace open uniform_space open CpltSepUniformSpace /-- The functor turning uniform spaces into complete separated uniform spaces. -/ noncomputable def completion_functor : UniformSpace β₯€ CpltSepUniformSpace := { obj := Ξ» X, CpltSepUniformSpace.of (completion X), map := Ξ» X Y f, ⟨completion.map f.1, completion.uniform_continuous_map⟩, map_id' := Ξ» X, subtype.eq completion.map_id, map_comp' := Ξ» X Y Z f g, subtype.eq (completion.map_comp g.property f.property).symm, }. /-- The inclusion of a uniform space into its completion. -/ def completion_hom (X : UniformSpace) : X ⟢ (forgetβ‚‚ CpltSepUniformSpace UniformSpace).obj (completion_functor.obj X) := { val := (coe : X β†’ completion X), property := completion.uniform_continuous_coe X } @[simp] lemma completion_hom_val (X : UniformSpace) (x) : (completion_hom X) x = (x : completion X) := rfl /-- The mate of a morphism from a `UniformSpace` to a `CpltSepUniformSpace`. -/ noncomputable def extension_hom {X : UniformSpace} {Y : CpltSepUniformSpace} (f : X ⟢ (forgetβ‚‚ CpltSepUniformSpace UniformSpace).obj Y) : completion_functor.obj X ⟢ Y := { val := completion.extension f, property := completion.uniform_continuous_extension } @[simp] lemma extension_hom_val {X : UniformSpace} {Y : CpltSepUniformSpace} (f : X ⟢ (forgetβ‚‚ _ _).obj Y) (x) : (extension_hom f) x = completion.extension f x := rfl. @[simp] lemma extension_comp_coe {X : UniformSpace} {Y : CpltSepUniformSpace} (f : to_UniformSpace (CpltSepUniformSpace.of (completion X)) ⟢ to_UniformSpace Y) : extension_hom (completion_hom X ≫ f) = f := by { apply subtype.eq, funext x, exact congr_fun (completion.extension_comp_coe f.property) x } /-- The completion functor is left adjoint to the forgetful functor. -/ noncomputable def adj : completion_functor ⊣ forgetβ‚‚ CpltSepUniformSpace UniformSpace := adjunction.mk_of_hom_equiv { hom_equiv := Ξ» X Y, { to_fun := Ξ» f, completion_hom X ≫ f, inv_fun := Ξ» f, extension_hom f, left_inv := Ξ» f, by { dsimp, erw extension_comp_coe }, right_inv := Ξ» f, begin apply subtype.eq, funext x, cases f, exact @completion.extension_coe _ _ _ _ _ (CpltSepUniformSpace.separated_space _) f_property _ end }, hom_equiv_naturality_left_symm' := Ξ» X X' Y f g, begin apply hom_ext, funext x, dsimp, erw [coe_comp, ←completion.extension_map], refl, exact g.property, exact f.property, end } noncomputable instance : is_right_adjoint (forgetβ‚‚ CpltSepUniformSpace UniformSpace) := ⟨completion_functor, adj⟩ noncomputable instance : reflective (forgetβ‚‚ CpltSepUniformSpace UniformSpace) := {} open category_theory.limits -- TODO Once someone defines `has_limits UniformSpace`, turn this into an instance. example [has_limits.{u} UniformSpace.{u}] : has_limits.{u} CpltSepUniformSpace.{u} := has_limits_of_reflective $ forgetβ‚‚ CpltSepUniformSpace UniformSpace.{u} end UniformSpace
71b8600279614101e6f254e613b4a7edcc006e88
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/geometry/manifold/basic_smooth_bundle.lean
bbad592e2d01f0d164556245c4d4f0d83c4f2161
[ "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
32,858
lean
/- Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import topology.topological_fiber_bundle geometry.manifold.smooth_manifold_with_corners /-! # Basic smooth bundles In general, a smooth bundle is a bundle over a smooth manifold, whose fiber is a manifold, and for which the coordinate changes are smooth. In this definition, there are charts involved at several places: in the manifold structure of the base, in the manifold structure of the fibers, and in the local trivializations. This makes it a complicated object in general. There is however a specific situation where things are much simpler: when the fiber is a vector space (no need for charts for the fibers), and when the local trivializations of the bundle and the charts of the base coincide. Then everything is expressed in terms of the charts of the base, making for a much simpler overall structure, which is easier to manipulate formally. Most vector bundles that naturally occur in differential geometry are of this form: the tangent bundle, the cotangent bundle, differential forms (used to define de Rham cohomology) and the bundle of Riemannian metrics. Therefore, it is worth defining a specific constructor for this kind of bundle, that we call basic smooth bundles. A basic smooth bundle is thus a smooth bundle over a smooth manifold whose fiber is a vector space, and which is trivial in the coordinate charts of the base. (We recall that in our notion of manifold there is a distinguished atlas, which does not need to be maximal: we require the triviality above this specific atlas). It can be constructed from a basic smooth bundled core, defined below, specifying the changes in the fiber when one goes from one coordinate chart to another one. We do not require that this changes in fiber are linear, but only diffeomorphisms. ## Main definitions * `basic_smooth_bundle_core I M F`: assuming that `M` is a smooth manifold over the model with corners `I` on `(π•œ, E, H)`, and `F` is a normed vector space over `π•œ`, this structure registers, for each pair of charts of `M`, a smooth change of coordinates on `F`. This is the core structure from which one will build a smooth bundle with fiber `F` over `M`. Let `Z` be a basic smooth bundle core over `M` with fiber `F`. We define `Z.to_topological_fiber_bundle_core`, the (topological) fiber bundle core associated to `Z`. From it, we get a space `Z.to_topological_fiber_bundle_core.total_space` (which as a Type is just `M Γ— F`), with the fiber bundle topology. It inherits a manifold structure (where the charts are in bijection with the charts of the basis). We show that this manifold is smooth. Then we use this machinery to construct the tangent bundle of a smooth manifold. * `tangent_bundle_core I M`: the basic smooth bundle core associated to a smooth manifold `M` over a model with corners `I`. * `tangent_bundle I M` : the total space of `tangent_bundle_core I M`. It is itself a smooth manifold over the model with corners `I.tangent`, the product of `I` and the trivial model with corners on `E`. * `tangent_space I x` : the tangent space to `M` at `x` * `tangent_bundle.proj I M`: the projection from the tangent bundle to the base manifold ## Implementation notes In the definition of a basic smooth bundle core, we do not require that the coordinate changes of the fibers are linear map, only that they are diffeomorphisms. Therefore, the fibers of the resulting fiber bundle do not inherit a vector space structure (as an algebraic object) in general. As the fiber, as a type, is just `F`, one can still always register the vector space structure, but it does not make sense to do so (i.e., it will not lead to any useful theorem) unless this structure is canonical, i.e., the coordinate changes are linear maps. For instance, we register the vector space structure on the fibers of the tangent bundle. However, we do not register the normed space structure coming from that of `F` (as it is not canonical, and we also want to keep the possibility to add a Riemannian structure on the manifold later on without having two competing normed space instances on the tangent spaces). We require `F` to be a normed space, and not just a topological vector space, as we want to talk about smooth functions on `F`. The notion of derivative requires a norm to be defined. ## TODO construct the cotangent bundle, and the bundles of differential forms. They should follow functorially from the description of the tangent bundle as a basic smooth bundle. ## Tags Smooth fiber bundle, vector bundle, tangent space, tangent bundle -/ noncomputable theory universe u open topological_space set /-- Core structure used to create a smooth bundle above `M` (a manifold over the model with corner `I`) with fiber the normed vector space `F` over `π•œ`, which is trivial in the chart domains of `M`. This structure registers the changes in the fibers when one changes coordinate charts in the base. We do not require the change of coordinates of the fibers to be linear, only smooth. Therefore, the fibers of the resulting bundle will not inherit a canonical vector space structure in general. -/ structure basic_smooth_bundle_core {π•œ : Type*} [nondiscrete_normed_field π•œ] {E : Type*} [normed_group E] [normed_space π•œ E] {H : Type*} [topological_space H] (I : model_with_corners π•œ E H) (M : Type*) [topological_space M] [manifold H M] [smooth_manifold_with_corners I M] (F : Type*) [normed_group F] [normed_space π•œ F] := (coord_change : atlas H M β†’ atlas H M β†’ H β†’ F β†’ F) (coord_change_self : βˆ€ i : atlas H M, βˆ€ x ∈ i.1.target, βˆ€ v, coord_change i i x v = v) (coord_change_comp : βˆ€ i j k : atlas H M, βˆ€ x ∈ ((i.1.symm.trans j.1).trans (j.1.symm.trans k.1)).source, βˆ€ v, (coord_change j k ((i.1.symm.trans j.1).to_fun x)) (coord_change i j x v) = coord_change i k x v) (coord_change_smooth : βˆ€ i j : atlas H M, times_cont_diff_on π•œ ⊀ (Ξ»p : E Γ— F, coord_change i j (I.inv_fun p.1) p.2) ((I.to_fun '' (i.1.symm.trans j.1).source).prod (univ : set F))) namespace basic_smooth_bundle_core variables {π•œ : Type*} [nondiscrete_normed_field π•œ] {E : Type*} [normed_group E] [normed_space π•œ E] {H : Type*} [topological_space H] {I : model_with_corners π•œ E H} {M : Type*} [topological_space M] [manifold H M] [smooth_manifold_with_corners I M] {F : Type*} [normed_group F] [normed_space π•œ F] (Z : basic_smooth_bundle_core I M F) /-- Fiber bundle core associated to a basic smooth bundle core -/ def to_topological_fiber_bundle_core : topological_fiber_bundle_core (atlas H M) M F := { base_set := Ξ»i, i.1.source, is_open_base_set := Ξ»i, i.1.open_source, index_at := Ξ»x, ⟨chart_at H x, chart_mem_atlas H x⟩, mem_base_set_at := Ξ»x, mem_chart_source H x, coord_change := Ξ»i j x v, Z.coord_change i j (i.1.to_fun x) v, coord_change_self := Ξ»i x hx v, Z.coord_change_self i (i.1.to_fun x) (i.1.map_source hx) v, coord_change_comp := Ξ»i j k x ⟨⟨hx1, hx2⟩, hx3⟩ v, begin have := Z.coord_change_comp i j k (i.1.to_fun x) _ v, convert this using 2, { simp [hx1] }, { simp [local_equiv.trans_source, hx1, hx2, hx3, i.1.map_source, j.1.map_source] } end, coord_change_continuous := Ξ»i j, begin have A : continuous_on (Ξ»p : E Γ— F, Z.coord_change i j (I.inv_fun p.1) p.2) ((I.to_fun '' (i.1.symm.trans j.1).source).prod (univ : set F)) := (Z.coord_change_smooth i j).continuous_on, have B : continuous_on (Ξ»x : M, I.to_fun (i.1.to_fun x)) i.1.source := I.continuous_to_fun.comp_continuous_on i.1.continuous_to_fun, have C : continuous_on (Ξ»p : M Γ— F, (⟨I.to_fun (i.1.to_fun p.1), p.2⟩ : E Γ— F)) (i.1.source.prod univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact B.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, have C' : continuous_on (Ξ»p : M Γ— F, (⟨I.to_fun (i.1.to_fun p.1), p.2⟩ : E Γ— F)) ((i.1.source ∩ j.1.source).prod univ) := continuous_on.mono C (prod_mono (inter_subset_left _ _) (subset.refl _)), have D : (i.1.source ∩ j.1.source).prod univ βŠ† (Ξ» (p : M Γ— F), (I.to_fun (i.1.to_fun p.1), p.2)) ⁻¹' ((I.to_fun '' (i.1.symm.trans j.1).source).prod univ), { rintros ⟨x, v⟩ hx, simp at hx, simp [mem_image_of_mem, local_equiv.trans_source, hx] }, convert continuous_on.comp A C' D, ext p, simp end } @[simp] lemma base_set (i : atlas H M) : Z.to_topological_fiber_bundle_core.base_set i = i.1.source := rfl /-- Local chart for the total space of a basic smooth bundle -/ def chart {e : local_homeomorph M H} (he : e ∈ atlas H M) : local_homeomorph (Z.to_topological_fiber_bundle_core.total_space) (H Γ— F) := (Z.to_topological_fiber_bundle_core.local_triv ⟨e, he⟩).trans (local_homeomorph.prod e (local_homeomorph.refl F)) @[simp] lemma chart_source (e : local_homeomorph M H) (he : e ∈ atlas H M) : (Z.chart he).source = Z.to_topological_fiber_bundle_core.proj ⁻¹' e.source := by { ext p, simp [chart, local_equiv.trans_source] } @[simp] lemma chart_target (e : local_homeomorph M H) (he : e ∈ atlas H M) : (Z.chart he).target = e.target.prod univ := begin simp only [chart, local_equiv.trans_target, local_homeomorph.prod_to_local_equiv, id.def, local_equiv.refl_inv_fun, local_homeomorph.trans_to_local_equiv, local_equiv.refl_target, local_homeomorph.refl_local_equiv, local_equiv.prod_target, local_homeomorph.prod_inv_fun], ext p, split; simp [e.map_target] {contextual := tt} end /-- The total space of a basic smooth bundle is endowed with a manifold structure, where the charts are in bijection with the charts of the basis. -/ instance to_manifold : manifold (H Γ— F) Z.to_topological_fiber_bundle_core.total_space := { atlas := ⋃(e : local_homeomorph M H) (he : e ∈ atlas H M), {Z.chart he}, chart_at := Ξ»p, Z.chart (chart_mem_atlas H p.1), mem_chart_source := Ξ»p, by simp [mem_chart_source], chart_mem_atlas := Ξ»p, begin simp only [mem_Union, mem_singleton_iff, chart_mem_atlas], exact ⟨chart_at H p.1, chart_mem_atlas H p.1, rfl⟩ end } lemma mem_atlas_iff (f : local_homeomorph Z.to_topological_fiber_bundle_core.total_space (H Γ— F)) : f ∈ atlas (H Γ— F) Z.to_topological_fiber_bundle_core.total_space ↔ βˆƒ(e : local_homeomorph M H) (he : e ∈ atlas H M), f = Z.chart he := by simp [atlas, manifold.atlas] @[simp] lemma mem_chart_source_iff (p q : Z.to_topological_fiber_bundle_core.total_space) : p ∈ (chart_at (H Γ— F) q).source ↔ p.1 ∈ (chart_at H q.1).source := by simp [chart_at, manifold.chart_at] @[simp] lemma mem_chart_target_iff (p : H Γ— F) (q : Z.to_topological_fiber_bundle_core.total_space) : p ∈ (chart_at (H Γ— F) q).target ↔ p.1 ∈ (chart_at H q.1).target := by simp [chart_at, manifold.chart_at] @[simp] lemma chart_at_to_fun_fst (p q : Z.to_topological_fiber_bundle_core.total_space) : ((chart_at (H Γ— F) q).to_fun p).1 = (chart_at H q.1).to_fun p.1 := rfl @[simp] lemma chart_at_inv_fun_fst (p : H Γ— F) (q : Z.to_topological_fiber_bundle_core.total_space) : ((chart_at (H Γ— F) q).inv_fun p).1 = (chart_at H q.1).inv_fun p.1 := rfl /-- Smooth manifold structure on the total space of a basic smooth bundle -/ instance to_smooth_manifold : smooth_manifold_with_corners (I.prod (model_with_corners_self π•œ F)) Z.to_topological_fiber_bundle_core.total_space := begin /- We have to check that the charts belong to the smooth groupoid, i.e., they are smooth on their source, and their inverses are smooth on the target. Since both objects are of the same kind, it suffices to prove the first statement in A below, and then glue back the pieces at the end. -/ let J := model_with_corners.to_local_equiv (I.prod (model_with_corners_self π•œ F)), have A : βˆ€ (e e' : local_homeomorph M H) (he : e ∈ atlas H M) (he' : e' ∈ atlas H M), times_cont_diff_on π•œ ⊀ (J.to_fun ∘ ((Z.chart he).symm.trans (Z.chart he')).to_fun ∘ J.inv_fun) (J.inv_fun ⁻¹' ((Z.chart he).symm.trans (Z.chart he')).source ∩ range J.to_fun), { assume e e' he he', have : J.inv_fun ⁻¹' ((chart Z he).symm.trans (chart Z he')).source ∩ range J.to_fun = (I.inv_fun ⁻¹' (e.symm.trans e').source ∩ range I.to_fun).prod univ, { have : range (Ξ» (p : H Γ— F), (I.to_fun (p.fst), id p.snd)) = (range I.to_fun).prod (range (id : F β†’ F)) := prod_range_range_eq.symm, simp at this, ext p, simp [-mem_range, J, local_equiv.trans_source, chart, model_with_corners.prod, local_equiv.trans_target, this], split, { tauto }, { exact λ⟨⟨hx1, hx2⟩, hx3⟩, ⟨⟨⟨hx1, e.map_target hx1⟩, hx2⟩, hx3⟩ } }, rw this, -- check separately that the two components of the coordinate change are smooth apply times_cont_diff_on.prod, show times_cont_diff_on π•œ ⊀ (Ξ» (p : E Γ— F), (I.to_fun ∘ e'.to_fun ∘ e.inv_fun ∘ I.inv_fun) p.1) ((I.inv_fun ⁻¹' (e.symm.trans e').source ∩ range I.to_fun).prod (univ : set F)), { -- the coordinate change on the base is just a coordinate change for `M`, smooth since -- `M` is smooth have A : times_cont_diff_on π•œ ⊀ (I.to_fun ∘ (e.symm.trans e').to_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (e.symm.trans e').source ∩ range I.to_fun) := (has_groupoid.compatible (times_cont_diff_groupoid ⊀ I) he he').1, have B : times_cont_diff_on π•œ ⊀ (Ξ»p : E Γ— F, p.1) ((I.inv_fun ⁻¹' (e.symm.trans e').source ∩ range I.to_fun).prod univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp A B (prod_subset_preimage_fst _ _) }, show times_cont_diff_on π•œ ⊀ (Ξ» (p : E Γ— F), Z.coord_change ⟨chart_at H (e.inv_fun (I.inv_fun p.1)), _⟩ ⟨e', he'⟩ ((chart_at H (e.inv_fun (I.inv_fun p.1))).to_fun (e.inv_fun (I.inv_fun p.1))) (Z.coord_change ⟨e, he⟩ ⟨chart_at H (e.inv_fun (I.inv_fun p.1)), _⟩ (e.to_fun (e.inv_fun (I.inv_fun p.1))) p.2)) ((I.inv_fun ⁻¹' (e.symm.trans e').source ∩ range I.to_fun).prod (univ : set F)), { /- The coordinate change in the fiber is more complicated as its definition involves the reference chart chosen at each point. However, it appears with its inverse, so using the cocycle property one can get rid of it, and then conclude using the smoothness of the cocycle as given in the definition of basic smooth bundles. -/ have := Z.coord_change_smooth ⟨e, he⟩ ⟨e', he'⟩, rw model_with_corners.image at this, apply times_cont_diff_on.congr this, rintros ⟨x, v⟩ hx, simp [local_equiv.trans_source] at hx, let f := chart_at H (e.inv_fun (I.inv_fun x)), have A : I.inv_fun x ∈ ((e.symm.trans f).trans (f.symm.trans e')).source, by simp [local_equiv.trans_source, hx.1.1, hx.1.2, mem_chart_source, f.map_source], rw e.right_inv hx.1.1, have := Z.coord_change_comp ⟨e, he⟩ ⟨f, chart_mem_atlas _ _⟩ ⟨e', he'⟩ (I.inv_fun x) A v, simpa using this } }, haveI : has_groupoid Z.to_topological_fiber_bundle_core.total_space (times_cont_diff_groupoid ⊀ (I.prod (model_with_corners_self π•œ F))) := begin split, assume eβ‚€ eβ‚€' heβ‚€ heβ‚€', rcases (Z.mem_atlas_iff _).1 heβ‚€ with ⟨e, he, rfl⟩, rcases (Z.mem_atlas_iff _).1 heβ‚€' with ⟨e', he', rfl⟩, rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid], exact ⟨A e e' he he', A e' e he' he⟩ end, constructor end end basic_smooth_bundle_core section tangent_bundle variables {π•œ : Type*} [nondiscrete_normed_field π•œ] {E : Type*} [normed_group E] [normed_space π•œ E] {H : Type*} [topological_space H] (I : model_with_corners π•œ E H) (M : Type*) [topological_space M] [manifold H M] [smooth_manifold_with_corners I M] set_option class.instance_max_depth 50 /-- Basic smooth bundle core version of the tangent bundle of a smooth manifold `M` modelled over a model with corners `I` on `(E, H)`. The fibers are equal to `E`, and the coordinate change in the fiber corresponds to the derivative of the coordinate change in `M`. -/ def tangent_bundle_core : basic_smooth_bundle_core I M E := { coord_change := Ξ»i j x v, (fderiv_within π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (range I.to_fun) (I.to_fun x) : E β†’ E) v, coord_change_smooth := Ξ»i j, begin /- To check that the coordinate change of the bundle is smooth, one should just use the smoothness of the charts, and thus the smoothness of their derivatives. -/ rw model_with_corners.image, have A : times_cont_diff_on π•œ ⊀ (I.to_fun ∘ (i.1.symm.trans j.1).to_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun) := (has_groupoid.compatible (times_cont_diff_groupoid ⊀ I) i.2 j.2).1, have B : unique_diff_on π•œ (I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun), { rw inter_comm, apply I.unique_diff.inter (I.continuous_inv_fun _ (local_homeomorph.open_source _)) }, have C : times_cont_diff_on π•œ ⊀ (Ξ» (p : E Γ— E), (fderiv_within π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun) p.1 : E β†’ E) p.2) ((I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun).prod univ) := times_cont_diff_on_fderiv_within_apply A B le_top, have D : βˆ€ x ∈ (I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun), fderiv_within π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (range I.to_fun) x = fderiv_within π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun) x, { assume x hx, have N : I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∈ nhds x := I.continuous_inv_fun.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) hx.1), symmetry, rw inter_comm, exact fderiv_within_inter N (I.unique_diff _ hx.2) }, apply times_cont_diff_on.congr C, rintros ⟨x, v⟩ hx, have E : x ∈ I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun, by simpa using hx, have : I.to_fun (I.inv_fun x) = x, by simp [E.2], dsimp, rw [this, D x E], refl end, coord_change_self := Ξ»i x hx v, begin /- Locally, a self-change of coordinate is just the identity, thus its derivative is the identity. One just needs to write this carefully, paying attention to the sets where the functions are defined. -/ have A : I.inv_fun ⁻¹' (i.1.symm.trans i.1).source ∩ range I.to_fun ∈ nhds_within (I.to_fun x) (range I.to_fun), { rw inter_comm, apply inter_mem_nhds_within, apply I.continuous_inv_fun.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simp [hx, local_equiv.trans_source, i.1.map_target] }, have B : βˆ€αΆ  y in nhds_within (I.to_fun x) (range I.to_fun), (I.to_fun ∘ i.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) y = (id : E β†’ E) y, { apply filter.mem_sets_of_superset A, assume y hy, rw ← model_with_corners.image at hy, rcases hy with ⟨z, hz⟩, simp [local_equiv.trans_source] at hz, simp [hz.2.symm, hz.1] }, have C : fderiv_within π•œ (I.to_fun ∘ i.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (range I.to_fun) (I.to_fun x) = fderiv_within π•œ (id : E β†’ E) (range I.to_fun) (I.to_fun x) := fderiv_within_congr_of_mem_nhds_within (I.unique_diff _ (mem_range_self _)) B (by simp [hx]), rw fderiv_within_id (I.unique_diff _ (mem_range_self _)) at C, rw C, refl end, coord_change_comp := Ξ»i j u x hx, begin /- The cocycle property is just the fact that the derivative of a composition is the product of the derivatives. One needs however to check that all the functions one considers are smooth, and to pay attention to the domains where these functions are defined, making this proof a little bit cumbersome although there is nothing complicated here. -/ have M : I.to_fun x ∈ (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) := ⟨by simpa using hx, mem_range_self _⟩, have U : unique_diff_within_at π•œ (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x), { have : unique_diff_on π•œ (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun), { rw inter_comm, exact I.unique_diff.inter (I.continuous_inv_fun _ (local_homeomorph.open_source _)) }, exact this _ M }, have A : fderiv_within π•œ ((I.to_fun ∘ u.1.to_fun ∘ j.1.inv_fun ∘ I.inv_fun) ∘ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun)) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x) = (fderiv_within π•œ (I.to_fun ∘ u.1.to_fun ∘ j.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (j.1.symm.trans u.1).source ∩ range I.to_fun) ((I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.to_fun x))).comp (fderiv_within π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x)), { apply fderiv_within.comp _ _ _ _ U, show differentiable_within_at π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x), { have A : times_cont_diff_on π•œ ⊀ (I.to_fun ∘ (i.1.symm.trans j.1).to_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (i.1.symm.trans j.1).source ∩ range I.to_fun) := (has_groupoid.compatible (times_cont_diff_groupoid ⊀ I) i.2 j.2).1, have B : differentiable_on π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun), { apply (A.differentiable_on (le_top)).mono, have : ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source βŠ† (i.1.symm.trans j.1).source := inter_subset_left _ _, exact inter_subset_inter (preimage_mono this) (subset.refl (range I.to_fun)) }, apply B, simpa [mem_inter_iff, -mem_image, -mem_range, mem_range_self] using hx }, show differentiable_within_at π•œ (I.to_fun ∘ u.1.to_fun ∘ j.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (j.1.symm.trans u.1).source ∩ range I.to_fun) ((I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.to_fun x)), { have A : times_cont_diff_on π•œ ⊀ (I.to_fun ∘ (j.1.symm.trans u.1).to_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (j.1.symm.trans u.1).source ∩ range I.to_fun) := (has_groupoid.compatible (times_cont_diff_groupoid ⊀ I) j.2 u.2).1, apply A.differentiable_on (le_top), rw [local_homeomorph.trans_source] at hx, simp [mem_inter_iff, -mem_image, -mem_range, mem_range_self], exact hx.2 }, show (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) βŠ† (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) ⁻¹' (I.inv_fun ⁻¹' (j.1.symm.trans u.1).source ∩ range I.to_fun), { assume y hy, simp [-mem_range, local_equiv.trans_source] at hy, rw [local_equiv.left_inv] at hy, { simp [-mem_range, mem_range_self, hy, local_equiv.trans_source] }, { exact hy.1.1.2 } } }, have B : fderiv_within π•œ ((I.to_fun ∘ u.1.to_fun ∘ j.1.inv_fun ∘ I.inv_fun) ∘ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun)) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x) = fderiv_within π•œ (I.to_fun ∘ u.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x), { have E : βˆ€ y ∈ (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun), ((I.to_fun ∘ u.1.to_fun ∘ j.1.inv_fun ∘ I.inv_fun) ∘ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun)) y = (I.to_fun ∘ u.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) y, { assume y hy, simp only [function.comp_app, model_with_corners_left_inv], rw [j.1.left_inv], exact hy.1.1.2 }, exact fderiv_within_congr U E (E _ M) }, have C : fderiv_within π•œ (I.to_fun ∘ u.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x) = fderiv_within π•œ (I.to_fun ∘ u.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (range I.to_fun) (I.to_fun x), { rw inter_comm, apply fderiv_within_inter _ (I.unique_diff _ (mem_range_self _)), apply I.continuous_inv_fun.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simpa using hx }, have D : fderiv_within π•œ (I.to_fun ∘ u.1.to_fun ∘ j.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' (j.1.symm.trans u.1).source ∩ range I.to_fun) ((I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.to_fun x)) = fderiv_within π•œ (I.to_fun ∘ u.1.to_fun ∘ j.1.inv_fun ∘ I.inv_fun) (range I.to_fun) ((I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.to_fun x)), { rw inter_comm, apply fderiv_within_inter _ (I.unique_diff _ (mem_range_self _)), apply I.continuous_inv_fun.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), rw [local_homeomorph.trans_source] at hx, simp [mem_inter_iff, -mem_image, -mem_range, mem_range_self], exact hx.2 }, have E : fderiv_within π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I.to_fun) (I.to_fun x) = (fderiv_within π•œ (I.to_fun ∘ j.1.to_fun ∘ i.1.inv_fun ∘ I.inv_fun) (range I.to_fun) (I.to_fun x)), { rw inter_comm, apply fderiv_within_inter _ (I.unique_diff _ (mem_range_self _)), apply I.continuous_inv_fun.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simpa using hx }, rw [B, C, D, E] at A, rw A, assume v, simp, unfold_coes, simp end } /-- The tangent bundle to a smooth manifold, as a plain type. -/ def tangent_bundle := (tangent_bundle_core I M).to_topological_fiber_bundle_core.total_space /-- The projection from the tangent bundle of a smooth manifold to the manifold. As the tangent bundle is represented internally as a product type, the notation `p.1` also works for the projection of the point `p`. -/ def tangent_bundle.proj : tangent_bundle I M β†’ M := (tangent_bundle_core I M).to_topological_fiber_bundle_core.proj variable {M} /-- The tangent space at a point of the manifold `M`. It is just `E`. -/ def tangent_space (x : M) : Type* := (tangent_bundle_core I M).to_topological_fiber_bundle_core.fiber x section tangent_bundle_instances /- In general, the definition of tangent_bundle and tangent_space are not reducible, so that type class inference does not pick wrong instances. In this section, we record the right instances for them, noting in particular that the tangent bundle is a smooth manifold. -/ variable (M) local attribute [reducible] tangent_bundle instance : topological_space (tangent_bundle I M) := by apply_instance instance : manifold (H Γ— E) (tangent_bundle I M) := by apply_instance instance : smooth_manifold_with_corners I.tangent (tangent_bundle I M) := by apply_instance local attribute [reducible] tangent_space topological_fiber_bundle_core.fiber /- When `topological_fiber_bundle_core.fiber` is reducible, then `topological_fiber_bundle_core.topological_space_fiber` can be applied to prove that any space is a topological space, with several unknown metavariables. This is a bad instance, that we disable.-/ local attribute [instance, priority 0] topological_fiber_bundle_core.topological_space_fiber variables {M} (x : M) instance : topological_module π•œ (tangent_space I x) := by apply_instance instance : topological_space (tangent_space I x) := by apply_instance instance : add_comm_group (tangent_space I x) := by apply_instance instance : topological_add_group (tangent_space I x) := by apply_instance instance : vector_space π•œ (tangent_space I x) := by apply_instance end tangent_bundle_instances variable (M) /-- The tangent bundle projection on the basis is a continuous map. -/ lemma tangent_bundle_proj_continuous : continuous (tangent_bundle.proj I M) := topological_fiber_bundle_core.continuous_proj _ /-- The tangent bundle projection on the basis is an open map. -/ lemma tangent_bundle_proj_open : is_open_map (tangent_bundle.proj I M) := topological_fiber_bundle_core.is_open_map_proj _ /-- In the tangent bundle to the model space, the charts are just the identity-/ @[simp] lemma tangent_bundle_model_space_chart_at (p : tangent_bundle I H) : (chart_at (H Γ— E) p).to_local_equiv = local_equiv.refl (H Γ— E) := begin have A : βˆ€ x_fst, fderiv_within π•œ (I.to_fun ∘ I.inv_fun) (range I.to_fun) (I.to_fun x_fst) = continuous_linear_map.id, { assume x_fst, have : fderiv_within π•œ (I.to_fun ∘ I.inv_fun) (range I.to_fun) (I.to_fun x_fst) = fderiv_within π•œ id (range I.to_fun) (I.to_fun x_fst), { refine fderiv_within_congr (I.unique_diff _ (mem_range_self _)) (Ξ»y hy, _) (by simp), exact model_with_corners_right_inv _ hy }, rwa fderiv_within_id (I.unique_diff _ (mem_range_self _)) at this }, ext x : 1, show (chart_at (H Γ— E) p).to_fun x = (local_equiv.refl (H Γ— E)).to_fun x, { cases x, simp [chart_at, manifold.chart_at, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv', basic_smooth_bundle_core.to_topological_fiber_bundle_core, tangent_bundle_core], erw [local_equiv.refl_to_fun, local_equiv.refl_inv_fun, A], refl }, show βˆ€ x, ((chart_at (H Γ— E) p).to_local_equiv).inv_fun x = (local_equiv.refl (H Γ— E)).inv_fun x, { rintros ⟨x_fst, x_snd⟩, simp [chart_at, manifold.chart_at, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv', basic_smooth_bundle_core.to_topological_fiber_bundle_core, tangent_bundle_core], erw [local_equiv.refl_to_fun, local_equiv.refl_inv_fun, A], refl }, show ((chart_at (H Γ— E) p).to_local_equiv).source = (local_equiv.refl (H Γ— E)).source, by simp [chart_at, manifold.chart_at, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv', basic_smooth_bundle_core.to_topological_fiber_bundle_core, tangent_bundle_core, local_equiv.trans_source] end variable (H) /-- In the tangent bundle to the model space, the topology is the product topology, i.e., the bundle is trivial -/ lemma tangent_bundle_model_space_topology_eq_prod : tangent_bundle.topological_space I H = prod.topological_space := begin ext o, let x : tangent_bundle I H := (I.inv_fun (0 : E), (0 : E)), let e := chart_at (H Γ— E) x, have e_source : e.source = univ, by { simp [e], refl }, have e_target : e.target = univ, by { simp [e], refl }, let e' := e.to_homeomorph_of_source_eq_univ_target_eq_univ e_source e_target, split, { assume ho, have := e'.continuous_inv_fun o ho, simpa [e', tangent_bundle_model_space_chart_at] }, { assume ho, have := e'.continuous_to_fun o ho, simpa [e', tangent_bundle_model_space_chart_at] } end end tangent_bundle
1d3920cfd1ec157ace4d629393dac2f60780d0b9
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/topology/metric_space/gromov_hausdorff_realized.lean
abf3a26ecb0609e5af02813e4138910823ca0695
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,919
lean
/- Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: SΓ©bastien GouΓ«zel Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance noncomputable theory open_locale classical open_locale topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union Ξ± βŠ• Ξ² of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (Ξ± : Type u) (Ξ² : Type v) [metric_space Ξ±] [compact_space Ξ±] [nonempty Ξ±] [metric_space Ξ²] [compact_space Ξ²] [nonempty Ξ²] @[reducible] private def prod_space_fun : Type* := ((Ξ± βŠ• Ξ²) Γ— (Ξ± βŠ• Ξ²)) β†’ ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((Ξ± βŠ• Ξ²) Γ— (Ξ± βŠ• Ξ²)) ℝ private def max_var : nnreal := 2 * ⟨diam (univ : set Ξ±), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set Ξ²), diam_nonneg⟩ private lemma one_le_max_var : 1 ≀ max_var Ξ± Ξ² := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≀ 2 * diam (univ : set Ξ±) + 1 + 2 * diam (univ : set Ξ²) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg, diam_nonneg]; norm_num /-- The set of functions on Ξ± βŠ• Ξ² that are candidates distances to realize the minimum of the Hausdorff distances between Ξ± and Ξ² in a coupling -/ def candidates : set (prod_space_fun Ξ± Ξ²) := {f | (((((βˆ€x y : Ξ±, f (sum.inl x, sum.inl y) = dist x y) ∧ (βˆ€x y : Ξ², f (sum.inr x, sum.inr y) = dist x y)) ∧ (βˆ€x y, f (x, y) = f (y, x))) ∧ (βˆ€x y z, f (x, z) ≀ f (x, y) + f (y, z))) ∧ (βˆ€x, f (x, x) = 0)) ∧ (βˆ€x y, f (x, y) ≀ max_var Ξ± Ξ²) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb Ξ± Ξ²) := {f : Cb Ξ± Ξ² | f.val ∈ candidates Ξ± Ξ²} end definitions --section section constructions variables {Ξ± : Type u} {Ξ² : Type v} [metric_space Ξ±] [compact_space Ξ±] [nonempty Ξ±] [metric_space Ξ²] [compact_space Ξ²] [nonempty Ξ²] {f : prod_space_fun Ξ± Ξ²} {x y z t : Ξ± βŠ• Ξ²} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≀ max_var Ξ± Ξ² := calc dist x y ≀ diam (univ : set (Ξ± βŠ• Ξ²)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set Ξ±) βˆͺ inr '' (univ : set Ξ²)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≀ diam (inl '' (univ : set Ξ±)) + dist (inl (default Ξ±)) (inr (default Ξ²)) + diam (inr '' (univ : set Ξ²)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set Ξ±) + (dist (default Ξ±) (default Ξ±) + 1 + dist (default Ξ²) (default Ξ²)) + diam (univ : set Ξ²) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set Ξ±) + 1 + 1 * diam (univ : set Ξ²) : by simp ... ≀ 2 * diam (univ : set Ξ±) + 1 + 2 * diam (univ : set Ξ²) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates Ξ± Ξ²) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates Ξ± Ξ²) : f (x, z) ≀ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates Ξ± Ξ²) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates Ξ± Ξ²) : 0 ≀ f (x, y) := begin have : 0 ≀ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≀ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates Ξ± Ξ²) (x y: Ξ±) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates Ξ± Ξ²) (x y : Ξ²) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates Ξ± Ξ²) : f (x, y) ≀ max_var Ξ± Ξ² := fA.2 x y /-- candidates are bounded by max_var Ξ± Ξ² -/ private lemma candidates_dist_bound (fA : f ∈ candidates Ξ± Ξ²) : βˆ€ {x y : Ξ± βŠ• Ξ²}, f (x, y) ≀ max_var Ξ± Ξ² * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq Ξ± Ξ², refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≀ max_var Ξ± Ξ² * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var Ξ± Ξ²) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≀ max_var Ξ± Ξ² : candidates_le_max_var fA ... = max_var Ξ± Ξ² * 1 : by simp ... ≀ max_var Ξ± Ξ² * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var Ξ± Ξ²)) | (inr x) (inl y) := calc f (inr x, inl y) ≀ max_var Ξ± Ξ² : candidates_le_max_var fA ... = max_var Ξ± Ξ² * 1 : by simp ... ≀ max_var Ξ± Ξ² * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var Ξ± Ξ²)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq Ξ± Ξ², refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≀ max_var Ξ± Ξ² * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var Ξ± Ξ²) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates Ξ± Ξ²) : f (x, y) - f (z, t) ≀ 2 * max_var Ξ± Ξ² * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≀ f (x, t) + f (t, y) - f (z, t) : add_le_add_right (candidates_triangle fA) _ ... ≀ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : add_le_add_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg] ... ≀ max_var Ξ± Ξ² * dist x z + max_var Ξ± Ξ² * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≀ max_var Ξ± Ξ² * max (dist x z) (dist t y) + max_var Ξ± Ξ² * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var Ξ± Ξ²)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var Ξ± Ξ²)), end ... = 2 * max_var Ξ± Ξ² * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var Ξ± Ξ² * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates Ξ± Ξ²) : lipschitz_with (2 * max_var Ξ± Ξ²) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw real.dist_eq, apply abs_le_of_le_of_neg_le, { exact candidates_lipschitz_aux fA }, { have : -(f (x, y) - f (z, t)) = f (z, t) - f (x, y), by ring, rw [this, dist_comm], exact candidates_lipschitz_aux fA } end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun Ξ± Ξ²) (fA : f ∈ candidates Ξ± Ξ²) : Cb Ξ± Ξ² := bounded_continuous_function.mk_of_compact f (candidates_lipschitz fA).continuous lemma candidates_b_of_candidates_mem (f : prod_space_fun Ξ± Ξ²) (fA : f ∈ candidates Ξ± Ξ²) : candidates_b_of_candidates f fA ∈ candidates_b Ξ± Ξ² := fA /-- The distance on Ξ± βŠ• Ξ² is a candidate -/ private lemma dist_mem_candidates : (Ξ»p : (Ξ± βŠ• Ξ²) Γ— (Ξ± βŠ• Ξ²), dist p.1 p.2) ∈ candidates Ξ± Ξ² := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (Ξ»a y z, dist_triangle_left _ _ _) <|> exact (Ξ»x y, by refl) <|> exact (Ξ»x y, max_var_bound) } end def candidates_b_dist (Ξ± : Type u) (Ξ² : Type v) [metric_space Ξ±] [compact_space Ξ±] [inhabited Ξ±] [metric_space Ξ²] [compact_space Ξ²] [inhabited Ξ²] : Cb Ξ± Ξ² := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist Ξ± Ξ² ∈ candidates_b Ξ± Ξ² := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b Ξ± Ξ²).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness -/ private lemma closed_candidates_b : is_closed (candidates_b Ξ± Ξ²) := begin have I1 : βˆ€x y, is_closed {f : Cb Ξ± Ξ² | f (inl x, inl y) = dist x y} := Ξ»x y, is_closed_eq continuous_evalx continuous_const, have I2 : βˆ€x y, is_closed {f : Cb Ξ± Ξ² | f (inr x, inr y) = dist x y } := Ξ»x y, is_closed_eq continuous_evalx continuous_const, have I3 : βˆ€x y, is_closed {f : Cb Ξ± Ξ² | f (x, y) = f (y, x)} := Ξ»x y, is_closed_eq continuous_evalx continuous_evalx, have I4 : βˆ€x y z, is_closed {f : Cb Ξ± Ξ² | f (x, z) ≀ f (x, y) + f (y, z)} := Ξ»x y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : βˆ€x, is_closed {f : Cb Ξ± Ξ² | f (x, x) = 0} := Ξ»x, is_closed_eq continuous_evalx continuous_const, have I6 : βˆ€x y, is_closed {f : Cb Ξ± Ξ² | f (x, y) ≀ max_var Ξ± Ξ²} := Ξ»x y, is_closed_le continuous_evalx continuous_const, have : candidates_b Ξ± Ξ² = (β‹‚x y, {f : Cb Ξ± Ξ² | f ((@inl Ξ± Ξ² x), (@inl Ξ± Ξ² y)) = dist x y}) ∩ (β‹‚x y, {f : Cb Ξ± Ξ² | f ((@inr Ξ± Ξ² x), (@inr Ξ± Ξ² y)) = dist x y}) ∩ (β‹‚x y, {f : Cb Ξ± Ξ² | f (x, y) = f (y, x)}) ∩ (β‹‚x y z, {f : Cb Ξ± Ξ² | f (x, z) ≀ f (x, y) + f (y, z)}) ∩ (β‹‚x, {f : Cb Ξ± Ξ² | f (x, x) = 0}) ∩ (β‹‚x y, {f : Cb Ξ± Ξ² | f (x, y) ≀ max_var Ξ± Ξ²}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows -/ private lemma compact_candidates_b : compact (candidates_b Ξ± Ξ²) := begin refine arzela_ascoliβ‚‚ (Icc 0 (max_var Ξ± Ξ²)) compact_Icc (candidates_b Ξ± Ξ²) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (Ξ»t, 2 * max_var Ξ± Ξ² * t) _ _ _, { have : tendsto (Ξ» (t : ℝ), 2 * (max_var Ξ± Ξ² : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var Ξ± Ξ² * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb Ξ± Ξ²) := max (supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², f (inl x, inr y)))) (supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, f (inl x, inr y)))) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb Ξ± Ξ²} (C : ℝ) {x : Ξ±} : bdd_below (range (Ξ» (y : Ξ²), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (Ξ»i, add_le_add_right ((Ξ»x, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb Ξ± Ξ²) (C : ℝ) : bdd_above (range (Ξ» (x : Ξ±), infi (Ξ»y:Ξ², f (inl x, inr y) + C))) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (Ξ»x, _)⟩, calc infi (Ξ»y:Ξ², f (inl x, inr y) + C) ≀ f (inl x, inr (default Ξ²)) + C : cinfi_le (HD_below_aux1 C) ... ≀ Cf + C : add_le_add ((Ξ»x, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb Ξ± Ξ²} (C : ℝ) {y : Ξ²} : bdd_below (range (Ξ» (x : Ξ±), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (Ξ»i, add_le_add_right ((Ξ»x, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb Ξ± Ξ²) (C : ℝ) : bdd_above (range (Ξ» (y : Ξ²), infi (Ξ»x:Ξ±, f (inl x, inr y) + C))) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (Ξ»y, _)⟩, calc infi (Ξ»x:Ξ±, f (inl x, inr y) + C) ≀ f (inl (default Ξ±), inr y) + C : cinfi_le (HD_below_aux2 C) ... ≀ Cf + C : add_le_add ((Ξ»x, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist Ξ± Ξ²) ≀ diam (univ : set Ξ±) + 1 + diam (univ : set Ξ²) := begin refine max_le (csupr_le (Ξ»x, _)) (csupr_le (Ξ»y, _)), { have A : infi (Ξ»y:Ξ², candidates_b_dist Ξ± Ξ² (inl x, inr y)) ≀ candidates_b_dist Ξ± Ξ² (inl x, inr (default Ξ²)) := cinfi_le (by simpa using HD_below_aux1 0), have B : dist (inl x) (inr (default Ξ²)) ≀ diam (univ : set Ξ±) + 1 + diam (univ : set Ξ²) := calc dist (inl x) (inr (default Ξ²)) = dist x (default Ξ±) + 1 + dist (default Ξ²) (default Ξ²) : rfl ... ≀ diam (univ : set Ξ±) + 1 + diam (univ : set Ξ²) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : infi (Ξ»x:Ξ±, candidates_b_dist Ξ± Ξ² (inl x, inr y)) ≀ candidates_b_dist Ξ± Ξ² (inl (default Ξ±), inr y) := cinfi_le (by simpa using HD_below_aux2 0), have B : dist (inl (default Ξ±)) (inr y) ≀ diam (univ : set Ξ±) + 1 + diam (univ : set Ξ²) := calc dist (inl (default Ξ±)) (inr y) = dist (default Ξ±) (default Ξ±) + 1 + dist (default Ξ²) y : rfl ... ≀ diam (univ : set Ξ±) + 1 + diam (univ : set Ξ²) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb Ξ± Ξ²) : supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², f (inl x, inr y))) ≀ supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², g (inl x, inr y))) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : βˆ€x, cg ≀ g x := Ξ»x, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : βˆ€x, cf ≀ f x := Ξ»x, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², f (inl x, inr y))) ≀ supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², g (inl x, inr y) + dist f g)) := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (Ξ»x, cinfi_le_cinfi ⟨cf, forall_range_iff.2(Ξ»i, Hcf _)⟩ (Ξ»y, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : βˆ€x, infi (Ξ»y:Ξ², g (inl x, inr y)) + dist f g = infi ((Ξ»z, z + dist f g) ∘ (Ξ»y:Ξ², (g (inl x, inr y)))), { assume x, refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (Ξ» (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { show bdd_below (range (Ξ» (y : Ξ²), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(Ξ»i, Hcg _)⟩ } }, have E2 : supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², g (inl x, inr y))) + dist f g = supr ((Ξ»z, z + dist f g) ∘ (Ξ»x:Ξ±, infi (Ξ»y:Ξ², g (inl x, inr y)))), { refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (Ξ» (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb Ξ± Ξ²) : supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, f (inl x, inr y))) ≀ supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, g (inl x, inr y))) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : βˆ€x, cg ≀ g x := Ξ»x, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : βˆ€x, cf ≀ f x := Ξ»x, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, f (inl x, inr y))) ≀ supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, g (inl x, inr y) + dist f g)) := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (Ξ»y, cinfi_le_cinfi ⟨cf, forall_range_iff.2(Ξ»i, Hcf _)⟩ (Ξ»y, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : βˆ€y, infi (Ξ»x:Ξ±, g (inl x, inr y)) + dist f g = infi ((Ξ»z, z + dist f g) ∘ (Ξ»x:Ξ±, (g (inl x, inr y)))), { assume y, refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (Ξ» (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { show bdd_below (range (Ξ»x:Ξ±, g (inl x, inr y))), from ⟨cg, forall_range_iff.2(Ξ»i, Hcg _)⟩ } }, have E2 : supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, g (inl x, inr y))) + dist f g = supr ((Ξ»z, z + dist f g) ∘ (Ξ»y:Ξ², infi (Ξ»x:Ξ±, g (inl x, inr y)))), { refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (Ξ» (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux3 (f g : Cb Ξ± Ξ²) : HD f ≀ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb Ξ± Ξ² β†’ ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (Ξ± : Type u) (Ξ² : Type v) [metric_space Ξ±] [compact_space Ξ±] [nonempty Ξ±] [metric_space Ξ²] [compact_space Ξ²] [nonempty Ξ²] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : βˆƒf ∈ candidates_b Ξ± Ξ², βˆ€g ∈ candidates_b Ξ± Ξ², HD f ≀ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb Ξ± Ξ² := classical.some (exists_minimizer Ξ± Ξ²) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist Ξ± Ξ² ∈ candidates_b Ξ± Ξ² := by cases (classical.some_spec (exists_minimizer Ξ± Ξ²)); assumption private lemma HD_optimal_GH_dist_le (g : Cb Ξ± Ξ²) (hg : g ∈ candidates_b Ξ± Ξ²) : HD (optimal_GH_dist Ξ± Ξ²) ≀ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer Ξ± Ξ²) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on Ξ± βŠ• Ξ², on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : premetric_space (Ξ± βŠ• Ξ²) := { dist := Ξ»p q, optimal_GH_dist Ξ± Ξ² (p, q), dist_self := Ξ»x, candidates_refl (optimal_GH_dist_mem_candidates_b Ξ± Ξ²), dist_comm := Ξ»x y, candidates_symm (optimal_GH_dist_mem_candidates_b Ξ± Ξ²), dist_triangle := Ξ»x y z, candidates_triangle (optimal_GH_dist_mem_candidates_b Ξ± Ξ²) } local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid /-- A metric space which realizes the optimal coupling between Ξ± and Ξ² -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := premetric.metric_quot (Ξ± βŠ• Ξ²) /-- Injection of Ξ± in the optimal coupling between Ξ± and Ξ² -/ def optimal_GH_injl (x : Ξ±) : optimal_GH_coupling Ξ± Ξ² := ⟦inl x⟧ /-- The injection of Ξ± in the optimal coupling between Ξ± and Ξ² is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl Ξ± Ξ²) := begin refine isometry_emetric_iff_metric.2 (Ξ»x y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b Ξ± Ξ²) _ _, end /-- Injection of Ξ² in the optimal coupling between Ξ± and Ξ² -/ def optimal_GH_injr (y : Ξ²) : optimal_GH_coupling Ξ± Ξ² := ⟦inr y⟧ /-- The injection of Ξ² in the optimal coupling between Ξ± and Ξ² is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr Ξ± Ξ²) := begin refine isometry_emetric_iff_metric.2 (Ξ»x y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b Ξ± Ξ²) _ _, end /-- The optimal coupling between two compact spaces Ξ± and Ξ² is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling Ξ± Ξ²) := ⟨begin have : (univ : set (optimal_GH_coupling Ξ± Ξ²)) = (optimal_GH_injl Ξ± Ξ² '' univ) βˆͺ (optimal_GH_injr Ξ± Ξ² '' univ), { refine subset.antisymm (Ξ»xc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl Ξ± Ξ² x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr Ξ± Ξ² x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl Ξ± Ξ²).continuous).union (compact_univ.image (isometry_optimal_GH_injr Ξ± Ξ²).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b Ξ± Ξ²) : Hausdorff_dist (range (optimal_GH_injl Ξ± Ξ²)) (range (optimal_GH_injr Ξ± Ξ²)) ≀ HD f := begin refine le_trans (le_of_forall_le_of_dense (Ξ»r hr, _)) (HD_optimal_GH_dist_le Ξ± Ξ² f h), have A : βˆ€ x ∈ range (optimal_GH_injl Ξ± Ξ²), βˆƒ y ∈ range (optimal_GH_injr Ξ± Ξ²), dist x y ≀ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², optimal_GH_dist Ξ± Ξ² (inl x, inr y))) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : infi (Ξ»y:Ξ², optimal_GH_dist Ξ± Ξ² (inl z, inr y)) ≀ supr (Ξ»x:Ξ±, infi (Ξ»y:Ξ², optimal_GH_dist Ξ± Ξ² (inl x, inr y))) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : infi (Ξ»y:Ξ², optimal_GH_dist Ξ± Ξ² (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr Ξ± Ξ² z', mem_range_self _], have : (optimal_GH_dist Ξ± Ξ²) (inl z, inr z') ≀ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty Ξ± with ⟨xΞ±, _⟩, have : optimal_GH_injl Ξ± Ξ² xΞ± ∈ range (optimal_GH_injl Ξ± Ξ²) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, optimal_GH_dist Ξ± Ξ² (inl x, inr y))) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : infi (Ξ»x:Ξ±, optimal_GH_dist Ξ± Ξ² (inl x, inr z)) ≀ supr (Ξ»y:Ξ², infi (Ξ»x:Ξ±, optimal_GH_dist Ξ± Ξ² (inl x, inr y))) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : infi (Ξ»x:Ξ±, optimal_GH_dist Ξ± Ξ² (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl Ξ± Ξ² z', mem_range_self _], have : (optimal_GH_dist Ξ± Ξ²) (inl z', inr z) ≀ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
f1cf6c328cea0d8c96d1a50828fd8305ef122b90
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/Extra.lean
3d4851f5366f51da6d824dd475fb3dcbf1bf0249
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
23,109
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.App import Lean.Elab.BuiltinNotation /-! # Auxiliary elaboration functions: AKA custom elaborators -/ namespace Lean.Elab.Term open Meta private def getMonadForIn (expectedType? : Option Expr) : TermElabM Expr := do match expectedType? with | none => throwError "invalid 'for_in%' notation, expected type is not available" | some expectedType => match (← isTypeApp? expectedType) with | some (m, _) => return m | none => throwError "invalid 'for_in%' notation, expected type is not of of the form `M Ξ±`{indentExpr expectedType}" private def throwForInFailure (forInInstance : Expr) : TermElabM Expr := throwError "failed to synthesize instance for 'for_in%' notation{indentExpr forInInstance}" @[builtin_term_elab forInMacro] def elabForIn : TermElab := fun stx expectedType? => do match stx with | `(for_in% $col $init $body) => match (← isLocalIdent? col) with | none => elabTerm (← `(let col := $col; for_in% col $init $body)) expectedType? | some colFVar => tryPostponeIfNoneOrMVar expectedType? let m ← getMonadForIn expectedType? let colType ← inferType colFVar let elemType ← mkFreshExprMVar (mkSort (mkLevelSucc (← mkFreshLevelMVar))) let forInInstance ← try mkAppM ``ForIn #[m, colType, elemType] catch _ => tryPostpone; throwError "failed to construct 'ForIn' instance for collection{indentExpr colType}\nand monad{indentExpr m}" match (← trySynthInstance forInInstance) with | .some inst => let forInFn ← mkConst ``forIn elabAppArgs forInFn (namedArgs := #[{ name := `m, val := Arg.expr m}, { name := `Ξ±, val := Arg.expr elemType }, { name := `self, val := Arg.expr inst }]) (args := #[Arg.stx col, Arg.stx init, Arg.stx body]) (expectedType? := expectedType?) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) | .undef => tryPostpone; throwForInFailure forInInstance | .none => throwForInFailure forInInstance | _ => throwUnsupportedSyntax @[builtin_term_elab forInMacro'] def elabForIn' : TermElab := fun stx expectedType? => do match stx with | `(for_in'% $col $init $body) => match (← isLocalIdent? col) with | none => elabTerm (← `(let col := $col; for_in'% col $init $body)) expectedType? | some colFVar => tryPostponeIfNoneOrMVar expectedType? let m ← getMonadForIn expectedType? let colType ← inferType colFVar let elemType ← mkFreshExprMVar (mkSort (mkLevelSucc (← mkFreshLevelMVar))) let forInInstance ← try let memType ← mkFreshExprMVar (← mkAppM ``Membership #[elemType, colType]) mkAppM ``ForIn' #[m, colType, elemType, memType] catch _ => tryPostpone; throwError "failed to construct `ForIn'` instance for collection{indentExpr colType}\nand monad{indentExpr m}" match (← trySynthInstance forInInstance) with | .some inst => let forInFn ← mkConst ``forIn' elabAppArgs forInFn (namedArgs := #[{ name := `m, val := Arg.expr m}, { name := `Ξ±, val := Arg.expr elemType}, { name := `self, val := Arg.expr inst }]) (args := #[Arg.expr colFVar, Arg.stx init, Arg.stx body]) (expectedType? := expectedType?) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) | .undef => tryPostpone; throwForInFailure forInInstance | .none => throwForInFailure forInInstance | _ => throwUnsupportedSyntax namespace Op /-! The elaborator for `binop%`, `binop_lazy%`, and `unop%` terms. It works as follows: 1- Expand macros. 2- Convert `Syntax` object corresponding to the `binop%` (`binop_lazy%` and `unop%`) term into a `Tree`. The `toTree` method visits nested `binop%` (`binop_lazy%` and `unop%`) terms and parentheses. 3- Synthesize pending metavariables without applying default instances and using the `(mayPostpone := true)`. 4- Tries to compute a maximal type for the tree computed at step 2. We say a type Ξ± is smaller than type Ξ² if there is a (nondependent) coercion from Ξ± to Ξ². We are currently ignoring the case we may have cycles in the coercion graph. If there are "uncomparable" types Ξ± and Ξ² in the tree, we skip the next step. We say two types are "uncomparable" if there isn't a coercion between them. Note that two types may be "uncomparable" because some typing information may still be missing. 5- We traverse the tree and inject coercions to the "maximal" type when needed. Recall that the coercions are expanded eagerly by the elaborator. Properties: a) Given `n : Nat` and `i : Nat`, it can successfully elaborate `n + i` and `i + n`. Recall that Lean 3 fails on the former. b) The coercions are inserted in the "leaves" like in Lean 3. c) There are no coercions "hidden" inside instances, and we can elaborate ``` axiom Int.add_comm (i j : Int) : i + j = j + i example (n : Nat) (i : Int) : n + i = i + n := by rw [Int.add_comm] ``` Recall that the `rw` tactic used to fail because our old `binop%` elaborator would hide coercions inside of a `HAdd` instance. Remarks: In the new `binop%` and related elaborators the decision whether a coercion will be inserted or not is made at `binop%` elaboration time. This was not the case in the old elaborator. For example, an instance, such as `HAdd Int ?m ?n`, could be created when executing the `binop%` elaborator, and only resolved much later. We try to minimize this problem by synthesizing pending metavariables at step 3. For types containing heterogeneous operators (e.g., matrix multiplication), step 4 will fail and we will skip coercion insertion. For example, `x : Matrix Real 5 4` and `y : Matrix Real 4 8`, there is no coercion `Matrix Real 5 4` from `Matrix Real 4 8` and vice-versa, but `x * y` is elaborated successfully and has type `Matrix Real 5 8`. -/ private inductive Tree where /-- Leaf of the tree. We store the `infoTrees` generated when elaborating `val`. These trees become subtrees of the infotree nodes generated for `op` nodes. -/ | term (ref : Syntax) (infoTrees : PersistentArray InfoTree) (val : Expr) /-- `ref` is the original syntax that expanded into `binop%`. `macroName` is the `macro_rule` that produce the expansion. We store this information here to make sure "go to definition" behaves similarly to notation defined without using `binop%` helper elaborator. -/ | binop (ref : Syntax) (macroName : Name) (lazy : Bool) (f : Expr) (lhs rhs : Tree) /-- `ref` is the original syntax that expanded into `unop%`. `macroName` is the `macro_rule` that produce the expansion. We store this information here to make sure "go to definition" behaves similarly to notation defined without using `unop%` helper elaborator. -/ | unop (ref : Syntax) (macroName : Name) (f : Expr) (arg : Tree) private partial def toTree (s : Syntax) : TermElabM Tree := do /- Remark: ew used to use `expandMacros` here, but this is a bad idiom because we do not record the macro expansion information in the info tree. We now manually expand the notation in the `go` function, and save the macro declaration names in the `op` nodes. -/ let result ← go s synthesizeSyntheticMVars (mayPostpone := true) return result where go (s : Syntax) := do match s with | `(binop% $f $lhs $rhs) => processBinOp (lazy := false) s .anonymous f lhs rhs | `(binop_lazy% $f $lhs $rhs) => processBinOp (lazy := true) s .anonymous f lhs rhs | `(unop% $f $arg) => processUnOp s .anonymous f arg | `(($e)) => if hasCDot e then processLeaf s else go e | _ => match (← liftMacroM <| expandMacroImpl? (← getEnv) s) with | some (macroName, s?) => let s' ← liftMacroM <| liftExcept s? match s' with | `(binop% $f $lhs $rhs) => processBinOp (lazy := false) s macroName f lhs rhs | `(binop_lazy% $f $lhs $rhs) => processBinOp (lazy := true) s macroName f lhs rhs | `(unop% $f $arg) => processUnOp s .anonymous f arg | _ => processLeaf s | none => processLeaf s processBinOp (ref : Syntax) (declName : Name) (f lhs rhs : Syntax) (lazy : Bool) := do let some f ← resolveId? f | throwUnknownConstant f.getId return .binop (lazy := lazy) ref declName f (← go lhs) (← go rhs) processUnOp (ref : Syntax) (declName : Name) (f arg : Syntax) := do let some f ← resolveId? f | throwUnknownConstant f.getId return .unop ref declName f (← go arg) processLeaf (s : Syntax) := do let e ← elabTerm s none let info ← getResetInfoTrees return .term s info e -- Auxiliary function used at `analyze` private def hasCoe (fromType toType : Expr) : TermElabM Bool := do if (← getEnv).contains ``CoeT then withLocalDeclD `x fromType fun x => do match ← coerceSimple? x toType with | .some _ => return true | .none => return false | .undef => return false -- TODO: should we do something smarter here? else return false private structure AnalyzeResult where max? : Option Expr := none hasUncomparable : Bool := false -- `true` if there are two types `Ξ±` and `Ξ²` where we don't have coercions in any direction. private def isUnknow : Expr β†’ Bool | .mvar .. => true | .app f _ => isUnknow f | .letE _ _ _ b _ => isUnknow b | .mdata _ b => isUnknow b | _ => false private def analyze (t : Tree) (expectedType? : Option Expr) : TermElabM AnalyzeResult := do let max? ← match expectedType? with | none => pure none | some expectedType => let expectedType ← instantiateMVars expectedType if isUnknow expectedType then pure none else pure (some expectedType) (go t *> get).run' { max? } where go (t : Tree) : StateRefT AnalyzeResult TermElabM Unit := do unless (← get).hasUncomparable do match t with | .binop _ _ _ _ lhs rhs => go lhs; go rhs | .unop _ _ _ arg => go arg | .term _ _ val => let type ← instantiateMVars (← inferType val) unless isUnknow type do match (← get).max? with | none => modify fun s => { s with max? := type } | some max => unless (← withNewMCtxDepth <| isDefEqGuarded max type) do if (← hasCoe type max) then return () else if (← hasCoe max type) then modify fun s => { s with max? := type } else trace[Elab.binop] "uncomparable types: {max}, {type}" modify fun s => { s with hasUncomparable := true } private def mkBinOp (f : Expr) (lhs rhs : Expr) : TermElabM Expr := do elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) private def mkUnOp (f : Expr) (arg : Expr) : TermElabM Expr := do elabAppArgs f #[] #[Arg.expr arg] (expectedType? := none) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) private def toExprCore (t : Tree) : TermElabM Expr := do match t with | .term _ trees e => modifyInfoState (fun s => { s with trees := s.trees ++ trees }); return e | .binop ref macroName true f lhs rhs => withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo macroName ref) do mkBinOp f (← toExprCore lhs) (← mkFunUnit (← toExprCore rhs)) | .binop ref macroName false f lhs rhs => withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo macroName ref) do mkBinOp f (← toExprCore lhs) (← toExprCore rhs) | .unop ref macroName f arg => withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo macroName ref) do mkUnOp f (← toExprCore arg) /-- Auxiliary function to decide whether we should coerce `f`'s argument to `maxType` or not. - `f` is a binary operator. - `lhs == true` (`lhs == false`) if are trying to coerce the left-argument (right-argument). This function assumes `f` is a heterogeneous operator (e.g., `HAdd.hAdd`, `HMul.hMul`, etc). It returns true IF - `f` is a constant of the form `Cls.op` where `Cls` is a class name, and - `maxType` is of the form `C ...` where `C` is a constant, and - There are more than one default instance. That is, it assumes the class `Cls` for the heterogeneous operator `f`, and always has the monomorphic instance. (e.g., for `HAdd`, we have `instance [Add Ξ±] : HAdd Ξ± Ξ± Ξ±`), and - If `lhs == true`, then there is a default instance of the form `Cls _ (C ..) _`, and - If `lhs == false`, then there is a default instance of the form `Cls (C ..) _ _`. The motivation is to support default instances such as ``` @[default_instance high] instance [Mul Ξ±] : HMul Ξ± (Array Ξ±) (Array Ξ±) where hMul a as := as.map (a * Β·) #eval 2 * #[3, 4, 5] ``` If the type of an argument is unknown we should not coerce it to `maxType` because it would prevent the default instance above from being even tried. -/ private def hasHeterogeneousDefaultInstances (f : Expr) (maxType : Expr) (lhs : Bool) : MetaM Bool := do let .const fName .. := f | return false let .const typeName .. := maxType.getAppFn | return false let className := fName.getPrefix let defInstances ← getDefaultInstances className if defInstances.length ≀ 1 then return false for (instName, _) in defInstances do if let .app (.app (.app _heteroClass lhsType) rhsType) _resultType := (← getConstInfo instName).type.getForallBody then if lhs && rhsType.isAppOf typeName then return true if !lhs && lhsType.isAppOf typeName then return true return false /-- Return `true` if polymorphic function `f` has a homogenous instance of `maxType`. The coercions to `maxType` only makes sense if such instance exists. For example, suppose `maxType` is `Int`, and `f` is `HPow.hPow`. Then, adding coercions to `maxType` only make sense if we have an instance `HPow Int Int Int`. -/ private def hasHomogeneousInstance (f : Expr) (maxType : Expr) : MetaM Bool := do let .const fName .. := f | return false let className := fName.getPrefix try let inst ← mkAppM className #[maxType, maxType, maxType] return (← trySynthInstance inst) matches .some _ catch _ => return false mutual /-- Try to coerce elements in the `t` to `maxType` when needed. If the type of an element in `t` is unknown we only coerce it to `maxType` if `maxType` does not have heterogeneous default instances. This extra check is approximated by `hasHeterogeneousDefaultInstances`. Remark: If `maxType` does not implement heterogeneous default instances, we do want to assign unknown types `?m` to `maxType` because it produces better type information propagation. Our test suite has many tests that would break if we don't do this. For example, consider the term ``` eq_of_isEqvAux a b hsz (i+1) (Nat.succ_le_of_lt h) heqv.2 ``` `Nat.succ_le_of_lt h` type depends on `i+1`, but `i+1` only reduces to `Nat.succ i` if we know that `1` is a `Nat`. There are several other examples like that in our test suite, and one can find them by just replacing the `← hasHeterogeneousDefaultInstances f maxType lhs` test with `true` Remark: if `hasHeterogeneousDefaultInstances` implementation is not good enough we should refine it in the future. -/ private partial def applyCoe (t : Tree) (maxType : Expr) (isPred : Bool) : TermElabM Tree := do go t none false isPred where go (t : Tree) (f? : Option Expr) (lhs : Bool) (isPred : Bool) : TermElabM Tree := do match t with | .binop ref macroName lazy f lhs rhs => /- We only keep applying coercions to `maxType` if `f` is predicate or `f` has a homogenous instance with `maxType`. See `hasHomogeneousInstance` for additional details. Remark: We assume `binrel%` elaborator is only used with homogenous predicates. -/ if (← pure isPred <||> hasHomogeneousInstance f maxType) then return .binop ref macroName lazy f (← go lhs f true false) (← go rhs f false false) else let r ← withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo macroName ref) do mkBinOp f (← toExpr lhs none) (← toExpr rhs none) let infoTrees ← getResetInfoTrees return .term ref infoTrees r | .unop ref macroName f arg => return .unop ref macroName f (← go arg none false false) | .term ref trees e => let type ← instantiateMVars (← inferType e) trace[Elab.binop] "visiting {e} : {type} =?= {maxType}" if isUnknow type then if let some f := f? then if (← hasHeterogeneousDefaultInstances f maxType lhs) then -- See comment at `hasHeterogeneousDefaultInstances` return t if (← isDefEqGuarded maxType type) then return t else trace[Elab.binop] "added coercion: {e} : {type} => {maxType}" withRef ref <| return .term ref trees (← mkCoe maxType e) private partial def toExpr (tree : Tree) (expectedType? : Option Expr) : TermElabM Expr := do let r ← analyze tree expectedType? trace[Elab.binop] "hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}" if r.hasUncomparable || r.max?.isNone then let result ← toExprCore tree ensureHasType expectedType? result else let result ← toExprCore (← applyCoe tree r.max?.get! (isPred := false)) trace[Elab.binop] "result: {result}" ensureHasType expectedType? result end def elabOp : TermElab := fun stx expectedType? => do toExpr (← toTree stx) expectedType? @[builtin_term_elab binop] def elabBinOp : TermElab := elabOp @[builtin_term_elab binop_lazy] def elabBinOpLazy : TermElab := elabOp @[builtin_term_elab unop] def elabUnOp : TermElab := elabOp /-- Elaboration functionf for `binrel%` and `binrel_no_prop%` notations. We use the infrastructure for `binop%` to make sure we propagate information between the left and right hand sides of a binary relation. Recall that the `binrel_no_prop%` notation is used for relations such as `==` which do not support `Prop`, but we still want to be able to write `(5 > 2) == (2 > 1)`. -/ def elabBinRelCore (noProp : Bool) (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← resolveId? stx[1]) with | some f => withSynthesizeLight do /- We used to use `withSynthesize (mayPostpone := true)` here instead of `withSynthesizeLight` here. Recall that `withSynthesizeLight` is equivalent to `withSynthesize (mayPostpone := true) (synthesizeDefault := false)`. It seems too much to apply default instances at binary relations. For example, we cannot elaborate ``` def as : List Int := [-1, 2, 0, -3, 4] #eval as.map fun a => ite (a β‰₯ 0) [a] [] ``` The problem is that when elaborating `a β‰₯ 0` we don't know yet that `a` is an `Int`. Then, by applying default instances, we apply the default instance to `0` that forces it to become an `Int`, and Lean infers that `a` has type `Nat`. Then, later we get a type error because `as` is `List Int` instead of `List Nat`. This behavior is quite counterintuitive since if we avoid this elaborator by writing ``` def as : List Int := [-1, 2, 0, -3, 4] #eval as.map fun a => ite (GE.ge a 0) [a] [] ``` everything works. However, there is a drawback of using `withSynthesizeLight` instead of `withSynthesize (mayPostpone := true)`. The following cannot be elaborated ``` have : (0 == 1) = false := rfl ``` We get a type error at `rfl`. `0 == 1` only reduces to `false` after we have applied the default instances that force the numeral to be `Nat`. We claim this is defensible behavior because the same happens if we do not use this elaborator. ``` have : (BEq.beq 0 1) = false := rfl ``` We can improve this failure in the future by applying default instances before reporting a type mismatch. -/ let lhs ← withRef stx[2] <| toTree stx[2] let rhs ← withRef stx[3] <| toTree stx[3] let tree := .binop (lazy := false) stx .anonymous f lhs rhs let r ← analyze tree none trace[Elab.binrel] "hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}" if r.hasUncomparable || r.max?.isNone then -- Use default elaboration strategy + `toBoolIfNecessary` let lhs ← toExprCore lhs let rhs ← toExprCore rhs let lhs ← toBoolIfNecessary lhs let rhs ← toBoolIfNecessary rhs let lhsType ← inferType lhs let rhs ← ensureHasType lhsType rhs elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType? (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) else let mut maxType := r.max?.get! /- If `noProp == true` and `maxType` is `Prop`, then set `maxType := Bool`. `See toBoolIfNecessary` -/ if noProp then if (← withNewMCtxDepth <| isDefEq maxType (mkSort levelZero)) then maxType := Lean.mkConst ``Bool let result ← toExprCore (← applyCoe tree maxType (isPred := true)) trace[Elab.binrel] "result: {result}" return result | none => throwUnknownConstant stx[1].getId where /-- If `noProp == true` and `e` has type `Prop`, then coerce it to `Bool`. -/ toBoolIfNecessary (e : Expr) : TermElabM Expr := do if noProp then -- We use `withNewMCtxDepth` to make sure metavariables are not assigned if (← withNewMCtxDepth <| isDefEq (← inferType e) (mkSort levelZero)) then return (← ensureHasType (Lean.mkConst ``Bool) e) return e @[builtin_term_elab binrel] def elabBinRel : TermElab := elabBinRelCore false @[builtin_term_elab binrel_no_prop] def elabBinRelNoProp : TermElab := elabBinRelCore true @[builtin_term_elab defaultOrOfNonempty] def elabDefaultOrNonempty : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | none => throwError "invalid 'default_or_ofNonempty%', expected type is not known" | some expectedType => try mkDefault expectedType catch ex => try mkOfNonempty expectedType catch _ => if stx[1].isNone then throw ex else -- It is in the context of an `unsafe` constant. We can use sorry instead. -- Another option is to make a recursive application since it is unsafe. mkSorry expectedType false builtin_initialize registerTraceClass `Elab.binop registerTraceClass `Elab.binrel end Op end Lean.Elab.Term
b8472e1513561bbdddef524c0819b926aee8e2da
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep_2/Tools/function_space.lean
85b4cb2beb1e7e3993d22934d0bf3e6ddfebeda7
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
1,672
lean
import .finite_dimensional_lemma open linear_map is_basis open_locale big_operators universe variables v w namespace classical_basis --- TODO :: a quoi sert le namespace : smul_ite est dΓ©jΓ  dans mathlib il vaut repΓ©rer oΓΉ je l'utilise dans mon histoire ! --- /-- Definition of classical basis of `X β†’ R`. `Ξ΅ x = Ξ» y, if x = y then 1 else 0`. -/ def Ξ΅ {R : Type v}[comm_ring R]{X : Type w}(x : X) [fintype X] [decidable_eq X] : (X β†’ R) := Ξ» y : X, if x = y then 1 else 0 variables {R : Type v} [comm_ring R] {X : Type w} [fintype X] [decidable_eq X] lemma epsilon_eq (x : X) : Ξ΅ x x = (1 : R) := by unfold Ξ΅; simp @[simp]lemma epsilon_ne ( x y : X)(HYP : Β¬ y = x) : Ξ΅ x y = (0 : R) := --- y'a t'il mieux ? une directe ite ? begin unfold Ξ΅, split_ifs, {rw h at HYP, trivial}, {exact rfl}, end @[simp]lemma smul_ite (Ο† : X β†’ R) ( y : X) : (Ξ» (x : X), Ο† x β€’ (Ξ΅ x y)) = (Ξ» x : X, if y = x then Ο† x else 0) := begin funext, unfold Ξ΅, change _ * _ = _, erw mul_ite, rw [mul_one,mul_zero], exact if_congr eq_comm rfl rfl, end lemma gen (Ο† : X β†’ R) : Ο† = βˆ‘ x , Ο† x β€’ (Ξ΅ x) := begin funext y, -- simp, rw finset.sum_apply, -- unfold Ξ΅, simp, conv_rhs { apply_congr,skip, rw Ξ΅, simp, }, erw finset.sum_ite_eq',simp, end @[simp]lemma classical_basis : is_basis R (Ξ» x : X, (Ξ΅ x : X β†’ R)) := begin split, {apply linear_independent_finite, intros Ο† hyp t, rw ← (gen Ο†) at hyp, rw hyp,exact rfl }, {apply gen_finite, exact Ξ» Ο†, ⟨ Ο†, gen Ο†βŸ©} end end classical_basis
0f81eaa4d0d9932fe7cbd449aa96713e557e5af2
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/matrix.lean
5ef07aca86ded3be73405646e09c056c789b4767
[ "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
2,007
lean
/- Helper classes for Lean 3 users -/ class One (Ξ± : Type u) where one : Ξ± instance [OfNat Ξ± (nat_lit 1)] : One Ξ± where one := 1 instance [One Ξ±] : OfNat Ξ± (nat_lit 1) where ofNat := One.one class Zero (Ξ± : Type u) where zero : Ξ± instance [OfNat Ξ± (nat_lit 0)] : Zero Ξ± where zero := 0 instance [Zero Ξ±] : OfNat Ξ± (nat_lit 0) where ofNat := Zero.zero /- Simple Matrix -/ def Matrix (m n : Nat) (Ξ± : Type u) : Type u := Fin m β†’ Fin n β†’ Ξ± namespace Matrix /- Scoped notation for accessing values stored in matrices. -/ scoped syntax:max term noWs "[" term ", " term "]" : term macro_rules | `($x[$i, $j]) => `($x $i $j) def dotProduct [Mul Ξ±] [Add Ξ±] [Zero Ξ±] (u v : Fin m β†’ Ξ±) : Ξ± := loop m (Nat.le_refl ..) Zero.zero where loop (i : Nat) (h : i ≀ m) (acc : Ξ±) : Ξ± := match i, h with | 0, h => acc | i+1, h => have : i < m := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h loop i (Nat.le_of_lt this) (acc + u ⟨i, this⟩ * v ⟨i, this⟩) instance [Zero Ξ±] : Zero (Matrix m n Ξ±) where zero _ _ := 0 instance [Add Ξ±] : Add (Matrix m n Ξ±) where add x y i j := x[i, j] + y[i, j] instance [Mul Ξ±] [Add Ξ±] [Zero Ξ±] : HMul (Matrix m n Ξ±) (Matrix n p Ξ±) (Matrix m p Ξ±) where hMul x y i j := dotProduct (x[i, Β·]) (y[Β·, j]) instance [Mul Ξ±] : HMul Ξ± (Matrix m n Ξ±) (Matrix m n Ξ±) where hMul c x i j := c * x[i, j] end Matrix def m1 : Matrix 2 2 Int := fun i j => #[#[1, 2], #[3, 4]][i][j] def m2 : Matrix 2 2 Int := fun i j => #[#[5, 6], #[7, 8]][i][j] open Matrix -- activate .[.,.] notation #eval (m1*m2)[0, 0] -- 19 #eval (m1*m2)[0, 1] -- 22 #eval (m1*m2)[1, 0] -- 43 #eval (m1*m2)[1, 1] -- 50 def v := -2 #eval (v*m1*m2)[0, 0] -- -38 def ex1 (a b : Nat) (x : Matrix 10 20 Nat) (y : Matrix 20 10 Nat) (z : Matrix 10 10 Nat) : Matrix 10 10 Nat := a * x * y + b * z def ex2 (a b : Nat) (x : Matrix m n Nat) (y : Matrix n m Nat) (z : Matrix m m Nat) : Matrix m m Nat := a * x * y + b * z
570b90c3565f9ed0986a259183c250acc61c4e6d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/list/sections.lean
0f92a76a1b3f8300d51c78b120a187150fcf71b4
[]
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
814
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.forall2 import Mathlib.PostPort universes u v namespace Mathlib namespace list /- sections -/ theorem mem_sections {Ξ± : Type u} {L : List (List Ξ±)} {f : List Ξ±} : f ∈ sections L ↔ forallβ‚‚ has_mem.mem f L := sorry theorem mem_sections_length {Ξ± : Type u} {L : List (List Ξ±)} {f : List Ξ±} (h : f ∈ sections L) : length f = length L := forallβ‚‚_length_eq (iff.mp mem_sections h) theorem rel_sections {Ξ± : Type u} {Ξ² : Type v} {r : Ξ± β†’ Ξ² β†’ Prop} : relator.lift_fun (forallβ‚‚ (forallβ‚‚ r)) (forallβ‚‚ (forallβ‚‚ r)) sections sections := sorry
ce7fae8b4f7d76cda0873574e8c5561c812f5e7f
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tactic9.lean
3f721190a3de148625a04b3a98dcd0141c9c64a8
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
204
lean
(* import("tactic.lua") *) definition f(a : Bool) : Bool := not a. theorem T (a b : Bool) : a \/ b β†’ (f b) β†’ a := _. disj_hyp unfold f exact absurd done print environment 1.
34f9f0959f8ffb9b0269379e07a2c98e20314613
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Module/colimits.lean
1bc29635f615ede9a85ba485a9c066f9856ccefa
[ "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
11,770
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.basic import category_theory.concrete_category.elementwise /-! # The category of R-modules has all colimits. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. Note that finite colimits can already be obtained from the instance `abelian (Module R)`. TODO: In fact, in `Module R` there is a much nicer model of colimits as quotients of finitely supported functions, and we really should implement this as well (or instead). -/ universes u v w open category_theory open category_theory.limits variables {R : Type u} [ring R] -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. namespace Module.colimits /-! We build the colimit of a diagram in `Module` by constructing the free group on the disjoint union of all the abelian groups in the diagram, then taking the quotient by the abelian group laws within each abelian group, and the identifications given by the morphisms in the diagram. -/ variables {J : Type w} [category.{v} J] (F : J β₯€ Module.{max u v w} R) /-- An inductive type representing all module expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Ξ  (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | neg : prequotient β†’ prequotient | add : prequotient β†’ prequotient β†’ prequotient | smul : R β†’ prequotient β†’ prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the module laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F β†’ prequotient F β†’ Prop -- Make it an equivalence relation: | refl : Ξ  (x), relation x x | symm : Ξ  (x y) (h : relation x y), relation y x | trans : Ξ  (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Ξ  (j j' : J) (f : j ⟢ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Ξ  (j), relation (of j 0) zero | neg : Ξ  (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Ξ  (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) | smul : Ξ  (j) (s) (x : F.obj j), relation (of j (s β€’ x)) (smul s (of j x)) -- Then one relation per argument of each operation | neg_1 : Ξ  (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Ξ  (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Ξ  (x y y') (r : relation y y'), relation (add x y) (add x y') | smul_1 : Ξ  (s) (x x') (r : relation x x'), relation (smul s x) (smul s x') -- And one relation per axiom | zero_add : Ξ  (x), relation (add zero x) x | add_zero : Ξ  (x), relation (add x zero) x | add_left_neg : Ξ  (x), relation (add (neg x) x) zero | add_comm : Ξ  (x y), relation (add x y) (add y x) | add_assoc : Ξ  (x y z), relation (add (add x y) z) (add x (add y z)) | one_smul : Ξ  (x), relation (smul 1 x) x | mul_smul : Ξ  (s t) (x), relation (smul (s * t) x) (smul s (smul t x)) | smul_add : Ξ  (s) (x y), relation (smul s (add x y)) (add (smul s x) (smul s y)) | smul_zero : Ξ  (s), relation (smul s zero) zero | add_smul : Ξ  (s t) (x), relation (smul (s + t) x) (add (smul s x) (smul t x)) | zero_smul : Ξ  (x), relation (smul 0 x) zero /-- The setoid corresponding to module expressions modulo module relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `Module R`. -/ @[derive inhabited] def colimit_type : Type (max u v w) := quotient (colimit_setoid F) instance : add_comm_group (colimit_type F) := { zero := begin exact quot.mk _ zero end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) β†’ (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, zero_add := Ξ» x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := Ξ» x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, add_left_neg := Ξ» x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := Ξ» x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, add_assoc := Ξ» x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, } instance : module R (colimit_type F) := { smul := Ξ» s, begin fapply @quot.lift, { intro x, exact quot.mk _ (smul s x) }, { intros x x' r, apply quot.sound, exact relation.smul_1 s _ _ r }, end, one_smul := Ξ» x, begin induction x, dsimp, apply quot.sound, apply relation.one_smul, refl, end, mul_smul := Ξ» s t x, begin induction x, dsimp, apply quot.sound, apply relation.mul_smul, refl, end, smul_add := Ξ» s x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.smul_add, refl, refl, end, smul_zero := Ξ» s, begin apply quot.sound, apply relation.smul_zero, end, add_smul := Ξ» s t x, begin induction x, dsimp, apply quot.sound, apply relation.add_smul, refl, end, zero_smul := Ξ» x, begin induction x, dsimp, apply quot.sound, apply relation.zero_smul, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl @[simp] lemma quot_smul (s x) : quot.mk setoid.r (smul s x) = (s β€’ (quot.mk setoid.r x) : colimit_type F) := rfl /-- The bundled module giving the colimit of a diagram. -/ def colimit : Module R := Module.of R (colimit_type F) /-- The function from a given module in the diagram to the colimit module. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The group homomorphism from a given module in the diagram to the colimit module. -/ def cocone_morphism (j : J) : F.obj j ⟢ colimit F := { to_fun := cocone_fun F j, map_smul' := by { intros, apply quot.sound, apply relation.smul, }, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟢ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟢ j') (x : F.obj j) : (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit module. -/ def colimit_cocone : cocone F := { X := colimit F, ΞΉ := { app := cocone_morphism F } }. /-- The function from the free module on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F β†’ s.X | (of j x) := (s.ΞΉ.app j) x | zero := 0 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y | (smul s x) := s β€’ (desc_fun_lift x) /-- The function from the colimit module to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F β†’ s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- neg { simp, }, -- add { simp, }, -- smul, { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- smul_1 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- add_assoc { rw add_assoc, }, -- one_smul { rw one_smul, }, -- mul_smul { rw mul_smul, }, -- smul_add { rw smul_add, }, -- smul_zero { rw smul_zero, }, -- add_smul { rw add_smul, }, -- zero_smul { rw zero_smul, }, } end /-- The group homomorphism from the colimit module to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟢ s.X := { to_fun := desc_fun F s, map_smul' := Ξ» s x, by { induction x; refl, }, map_add' := Ξ» x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_cocone_is_colimit : is_colimit (colimit_cocone F) := { desc := Ξ» s, desc_morphism F s, uniq' := Ξ» s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (Ξ» f : F.obj x_j ⟢ s.X, (f : F.obj x_j β†’ s.X)) (w x_j)) x_x, erw w', refl, }, { simp *, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_Module : has_colimits (Module.{max v u} R) := { has_colimits_of_shape := Ξ» J π’₯, by exactI { has_colimit := Ξ» F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } instance has_colimits_of_size_Module : has_colimits_of_size.{v} (Module.{max v u} R) := has_colimits_of_size_shrink _ instance has_colimits_of_size_zero_Module : has_colimits_of_size.{0} (Module.{max v u} R) := @has_colimits_of_size_shrink.{0} (Module.{max v u} R) _ Module.colimits.has_colimits_Module -- We manually add a `has_colimits` instance with universe parameters swapped, for otherwise -- the instance is not found by typeclass search. instance has_colimits_Module' (R : Type u) [ring R] : has_colimits (Module.{max u v} R) := Module.colimits.has_colimits_Module.{u v} -- We manually add a `has_colimits` instance with equal universe parameters, for otherwise -- the instance is not found by typeclass search. instance has_colimits_Module'' (R : Type u) [ring R] : has_colimits (Module.{u} R) := Module.colimits.has_colimits_Module.{u u} -- Sanity checks, just to make sure typeclass search can find the instances we want. example (R : Type u) [ring R] : has_colimits (Module.{max v u} R) := infer_instance example (R : Type u) [ring R] : has_colimits (Module.{max u v} R) := infer_instance example (R : Type u) [ring R] : has_colimits (Module.{u} R) := infer_instance end Module.colimits
a07df026e01ce92259a7613fb2c4c752e2205a65
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/data/fin/ops.lean
cedd5223223857f538b808e4cd8853f5d4183b38
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,763
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat init.data.fin.basic namespace fin open nat variable {n : nat} def of_nat {n : nat} (a : nat) : fin (succ n) := ⟨a % succ n, nat.mod_lt _ (nat.zero_lt_succ _)⟩ private lemma mlt {n b : nat} : βˆ€ {a}, n > a β†’ b % n < n | 0 h := nat.mod_lt _ h | (a+1) h := have n > 0, from lt.trans (nat.zero_lt_succ _) h, nat.mod_lt _ this protected def add : fin n β†’ fin n β†’ fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + b) % n, mlt h⟩ protected def mul : fin n β†’ fin n β†’ fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a * b) % n, mlt h⟩ private lemma sublt {a b n : nat} (h : a < n) : a - b < n := lt_of_le_of_lt (nat.sub_le a b) h protected def sub : fin n β†’ fin n β†’ fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a - b, sublt h⟩ private lemma modlt {a b n : nat} (h₁ : a < n) (hβ‚‚ : b < n) : a % b < n := begin cases b with b, {simp [mod_zero], assumption}, {assert h : a % (succ b) < succ b, apply nat.mod_lt _ (nat.zero_lt_succ _), exact lt.trans h hβ‚‚} end protected def mod : fin n β†’ fin n β†’ fin n | ⟨a, hβ‚βŸ© ⟨b, hβ‚‚βŸ© := ⟨a % b, modlt h₁ hβ‚‚βŸ© private lemma divlt {a b n : nat} (h : a < n) : a / b < n := lt_of_le_of_lt (nat.div_le_self a b) h protected def div : fin n β†’ fin n β†’ fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a / b, divlt h⟩ protected def lt : fin n β†’ fin n β†’ Prop | ⟨a, _⟩ ⟨b, _⟩ := a < b protected def le : fin n β†’ fin n β†’ Prop | ⟨a, _⟩ ⟨b, _⟩ := a ≀ b instance : has_zero (fin (succ n)) := ⟨of_nat 0⟩ instance : has_one (fin (succ n)) := ⟨of_nat 1⟩ instance : has_add (fin n) := ⟨fin.add⟩ instance : has_sub (fin n) := ⟨fin.sub⟩ instance : has_mul (fin n) := ⟨fin.mul⟩ instance : has_mod (fin n) := ⟨fin.mod⟩ instance : has_div (fin n) := ⟨fin.div⟩ instance : has_lt (fin n) := ⟨fin.lt⟩ instance : has_le (fin n) := ⟨fin.le⟩ instance decidable_lt : βˆ€ (a b : fin n), decidable (a < b) | ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_lt instance decidable_le : βˆ€ (a b : fin n), decidable (a ≀ b) | ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_le lemma add_def (a b : fin n) : (a + b).val = (a.val + b.val) % n := show (fin.add a b).val = (a.val + b.val) % n, from by cases a; cases b; simp [fin.add] lemma mul_def (a b : fin n) : (a * b).val = (a.val * b.val) % n := show (fin.mul a b).val = (a.val * b.val) % n, from by cases a; cases b; simp [fin.mul] lemma sub_def (a b : fin n) : (a - b).val = a.val - b.val := show (fin.sub a b).val = a.val - b.val, from by cases a; cases b; simp [fin.sub] lemma mod_def (a b : fin n) : (a % b).val = a.val % b.val := show (fin.mod a b).val = a.val % b.val, from by cases a; cases b; simp [fin.mod] lemma div_def (a b : fin n) : (a / b).val = a.val / b.val := show (fin.div a b).val = a.val / b.val, from by cases a; cases b; simp [fin.div] lemma lt_def (a b : fin n) : (a < b) = (a.val < b.val) := show (fin.lt a b) = (a.val < b.val), from by cases a; cases b; simp [fin.lt] lemma le_def (a b : fin n) : (a ≀ b) = (a.val ≀ b.val) := show (fin.le a b) = (a.val ≀ b.val), from by cases a; cases b; simp [fin.le] lemma val_zero : (0 : fin (succ n)).val = 0 := begin unfold has_zero.zero of_nat, dsimp, rw zero_mod end def pred {n : nat} : βˆ€ i : fin (succ n), i β‰  0 β†’ fin n | ⟨a, hβ‚βŸ© hβ‚‚ := ⟨a.pred, begin assert this : a β‰  0, { note aux₁ := vne_of_ne hβ‚‚, dsimp at aux₁, rw val_zero at aux₁, exact aux₁ }, exact nat.pred_lt_pred this (nat.succ_ne_zero n) h₁ end⟩ end fin
156f03a7c4687b3b40102212e1df5e742a0ea6a8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/quadratic_form/real.lean
f3ae98248de69a0371f166a30dfb86059d954114
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,478
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Kexing Ying, Eric Wieser -/ import linear_algebra.quadratic_form.isometry import analysis.special_functions.pow.real import data.real.sign /-! # Real quadratic forms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Sylvester's law of inertia `equivalent_one_neg_one_weighted_sum_squared`: A real quadratic form is equivalent to a weighted sum of squares with the weights being Β±1 or 0. When the real quadratic form is nondegerate we can take the weights to be Β±1, as in `equivalent_one_zero_neg_one_weighted_sum_squared`. -/ namespace quadratic_form open_locale big_operators open real finset variables {ΞΉ : Type*} [fintype ΞΉ] /-- The isometry between a weighted sum of squares with weights `u` on the (non-zero) real numbers and the weighted sum of squares with weights `sign ∘ u`. -/ noncomputable def isometry_sign_weighted_sum_squares [decidable_eq ΞΉ] (w : ΞΉ β†’ ℝ) : isometry (weighted_sum_squares ℝ w) (weighted_sum_squares ℝ (sign ∘ w)) := begin let u := Ξ» i, if h : w i = 0 then (1 : ℝˣ) else units.mk0 (w i) h, have hu' : βˆ€ i : ΞΉ, (sign (u i) * u i) ^ - (1 / 2 : ℝ) β‰  0, { intro i, refine (ne_of_lt (real.rpow_pos_of_pos (sign_mul_pos_of_ne_zero _ $ units.ne_zero _) _)).symm}, convert ((weighted_sum_squares ℝ w).isometry_basis_repr ((pi.basis_fun ℝ ΞΉ).units_smul (Ξ» i, (is_unit_iff_ne_zero.2 $ hu' i).unit))), ext1 v, rw [basis_repr_apply, weighted_sum_squares_apply, weighted_sum_squares_apply], refine sum_congr rfl (Ξ» j hj, _), have hsum : (βˆ‘ (i : ΞΉ), v i β€’ ((is_unit_iff_ne_zero.2 $ hu' i).unit : ℝ) β€’ (pi.basis_fun ℝ ΞΉ) i) j = v j β€’ (sign (u j) * u j) ^ - (1 / 2 : ℝ), { rw [finset.sum_apply, sum_eq_single j, pi.basis_fun_apply, is_unit.unit_spec, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_same, smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_one], intros i _ hij, rw [pi.basis_fun_apply, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_noteq hij.symm, pi.zero_apply, smul_eq_mul, smul_eq_mul, mul_zero, mul_zero], intro hj', exact false.elim (hj' hj) }, simp_rw basis.units_smul_apply, erw [hsum], simp only [u, function.comp, smul_eq_mul], split_ifs, { simp only [h, zero_smul, zero_mul, real.sign_zero] }, have hwu : w j = u j, { simp only [u, dif_neg h, units.coe_mk0] }, simp only [hwu, units.coe_mk0], suffices : (u j : ℝ).sign * v j * v j = (sign (u j) * u j) ^ - (1 / 2 : ℝ) * (sign (u j) * u j) ^ - (1 / 2 : ℝ) * u j * v j * v j, { erw [← mul_assoc, this], ring }, rw [← real.rpow_add (sign_mul_pos_of_ne_zero _ $ units.ne_zero _), show - (1 / 2 : ℝ) + - (1 / 2) = -1, by ring, real.rpow_neg_one, mul_inv, inv_sign, mul_assoc (sign (u j)) (u j)⁻¹, inv_mul_cancel (units.ne_zero _), mul_one], apply_instance end /-- **Sylvester's law of inertia**: A nondegenerate real quadratic form is equivalent to a weighted sum of squares with the weights being Β±1. -/ theorem equivalent_one_neg_one_weighted_sum_squared {M : Type*} [add_comm_group M] [module ℝ M] [finite_dimensional ℝ M] (Q : quadratic_form ℝ M) (hQ : (associated Q).nondegenerate) : βˆƒ w : fin (finite_dimensional.finrank ℝ M) β†’ ℝ, (βˆ€ i, w i = -1 ∨ w i = 1) ∧ equivalent Q (weighted_sum_squares ℝ w) := let ⟨w, ⟨hwβ‚βŸ©βŸ© := Q.equivalent_weighted_sum_squares_units_of_nondegenerate' hQ in ⟨sign ∘ coe ∘ w, Ξ» i, sign_apply_eq_of_ne_zero (w i) (w i).ne_zero, ⟨hw₁.trans (isometry_sign_weighted_sum_squares (coe ∘ w))⟩⟩ /-- **Sylvester's law of inertia**: A real quadratic form is equivalent to a weighted sum of squares with the weights being Β±1 or 0. -/ theorem equivalent_one_zero_neg_one_weighted_sum_squared {M : Type*} [add_comm_group M] [module ℝ M] [finite_dimensional ℝ M] (Q : quadratic_form ℝ M) : βˆƒ w : fin (finite_dimensional.finrank ℝ M) β†’ ℝ, (βˆ€ i, w i = -1 ∨ w i = 0 ∨ w i = 1) ∧ equivalent Q (weighted_sum_squares ℝ w) := let ⟨w, ⟨hwβ‚βŸ©βŸ© := Q.equivalent_weighted_sum_squares in ⟨sign ∘ coe ∘ w, Ξ» i, sign_apply_eq (w i), ⟨hw₁.trans (isometry_sign_weighted_sum_squares w)⟩⟩ end quadratic_form
25ec0ee297a5e3be752ae296807596512a36e557
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/setoid.lean
61e4b3407dbcb91bb541a947720750655ca34889
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
896
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 -/ prelude import init.relation universe variables u structure [class] setoid (A : Type u) := (r : A β†’ A β†’ Prop) (iseqv : equivalence r) namespace setoid infix ` β‰ˆ ` := setoid.r variable {A : Type u} variable [s : setoid A] include s attribute [refl] theorem refl (a : A) : a β‰ˆ a := match setoid.iseqv A with | ⟨H_refl, H_symm, H_trans⟩ := H_refl a end attribute [symm] theorem symm {a b : A} (Hab : a β‰ˆ b) : b β‰ˆ a := match setoid.iseqv A with | ⟨H_refl, H_symm, H_trans⟩ := H_symm Hab end attribute [trans] theorem trans {a b c : A} (Hab : a β‰ˆ b) (Hbc : b β‰ˆ c) : a β‰ˆ c := match setoid.iseqv A with | ⟨H_refl, H_symm, H_trans⟩ := H_trans Hab Hbc end end setoid
d518ded93e2672b6ad360c456129c243ee3b2781
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/isomorphism.lean
8d3cea33103aae4b54d8dc75a7096b9effe27a84
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
15,293
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor /-! # Isomorphisms This file defines isomorphisms between objects of a category. ## Main definitions - `structure iso` : a bundled isomorphism between two objects of a category; - `class is_iso` : an unbundled version of `iso`; note that `is_iso f` is a `Prop`, and only asserts the existence of an inverse. Of course, this inverse is unique, so it doesn't cost us much to use choice to retrieve it. - `inv f`, for the inverse of a morphism with `[is_iso f]` - `as_iso` : convert from `is_iso` to `iso` (noncomputable); - `of_iso` : convert from `iso` to `is_iso`; - standard operations on isomorphisms (composition, inverse etc) ## Notations - `X β‰… Y` : same as `iso X Y`; - `Ξ± β‰ͺ≫ Ξ²` : composition of two isomorphisms; it is called `iso.trans` ## Tags category, category theory, isomorphism -/ universes v u -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory open category /-- An isomorphism (a.k.a. an invertible morphism) between two objects of a category. The inverse morphism is bundled. See also `category_theory.core` for the category with the same objects and isomorphisms playing the role of morphisms. See <https://stacks.math.columbia.edu/tag/0017>. -/ structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟢ Y) (inv : Y ⟢ X) (hom_inv_id' : hom ≫ inv = πŸ™ X . obviously) (inv_hom_id' : inv ≫ hom = πŸ™ Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp, reassoc] iso.hom_inv_id iso.inv_hom_id infixr ` β‰… `:10 := iso -- type as \cong or \iso variables {C : Type u} [category.{v} C] variables {X Y Z : C} namespace iso @[ext] lemma ext ⦃α Ξ² : X β‰… Y⦄ (w : Ξ±.hom = Ξ².hom) : Ξ± = Ξ² := suffices Ξ±.inv = Ξ².inv, by cases Ξ±; cases Ξ²; cc, calc Ξ±.inv = Ξ±.inv ≫ (Ξ².hom ≫ Ξ².inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (Ξ±.inv ≫ Ξ±.hom) ≫ Ξ².inv : by rw [category.assoc, ←w] ... = Ξ².inv : by rw [iso.inv_hom_id, category.id_comp] /-- Inverse isomorphism. -/ @[symm] def symm (I : X β‰… Y) : Y β‰… X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (Ξ± : X β‰… Y) : Ξ±.symm.hom = Ξ±.inv := rfl @[simp] lemma symm_inv (Ξ± : X β‰… Y) : Ξ±.symm.inv = Ξ±.hom := rfl @[simp] lemma symm_mk {X Y : C} (hom : X ⟢ Y) (inv : Y ⟢ X) (hom_inv_id) (inv_hom_id) : iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} = {hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl @[simp] lemma symm_symm_eq {X Y : C} (Ξ± : X β‰… Y) : Ξ±.symm.symm = Ξ± := by cases Ξ±; refl @[simp] lemma symm_eq_iff {X Y : C} {Ξ± Ξ² : X β‰… Y} : Ξ±.symm = Ξ².symm ↔ Ξ± = Ξ² := ⟨λ h, symm_symm_eq Ξ± β–Έ symm_symm_eq Ξ² β–Έ congr_arg symm h, congr_arg symm⟩ /-- Identity isomorphism. -/ @[refl, simps] def refl (X : C) : X β‰… X := { hom := πŸ™ X, inv := πŸ™ X } instance : inhabited (X β‰… X) := ⟨iso.refl X⟩ @[simp] lemma refl_symm (X : C) : (iso.refl X).symm = iso.refl X := rfl /-- Composition of two isomorphisms -/ @[trans, simps] def trans (Ξ± : X β‰… Y) (Ξ² : Y β‰… Z) : X β‰… Z := { hom := Ξ±.hom ≫ Ξ².hom, inv := Ξ².inv ≫ Ξ±.inv } infixr ` β‰ͺ≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_mk {X Y Z : C} (hom : X ⟢ Y) (inv : Y ⟢ X) (hom_inv_id) (inv_hom_id) (hom' : Y ⟢ Z) (inv' : Z ⟢ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') : iso.trans {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} {hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} = { hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} := rfl @[simp] lemma trans_symm (Ξ± : X β‰… Y) (Ξ² : Y β‰… Z) : (Ξ± β‰ͺ≫ Ξ²).symm = Ξ².symm β‰ͺ≫ Ξ±.symm := rfl @[simp] lemma trans_assoc {Z' : C} (Ξ± : X β‰… Y) (Ξ² : Y β‰… Z) (Ξ³ : Z β‰… Z') : (Ξ± β‰ͺ≫ Ξ²) β‰ͺ≫ Ξ³ = Ξ± β‰ͺ≫ Ξ² β‰ͺ≫ Ξ³ := by ext; simp only [trans_hom, category.assoc] @[simp] lemma refl_trans (Ξ± : X β‰… Y) : (iso.refl X) β‰ͺ≫ Ξ± = Ξ± := by ext; apply category.id_comp @[simp] lemma trans_refl (Ξ± : X β‰… Y) : Ξ± β‰ͺ≫ (iso.refl Y) = Ξ± := by ext; apply category.comp_id @[simp] lemma symm_self_id (Ξ± : X β‰… Y) : Ξ±.symm β‰ͺ≫ Ξ± = iso.refl Y := ext Ξ±.inv_hom_id @[simp] lemma self_symm_id (Ξ± : X β‰… Y) : Ξ± β‰ͺ≫ Ξ±.symm = iso.refl X := ext Ξ±.hom_inv_id @[simp] lemma symm_self_id_assoc (Ξ± : X β‰… Y) (Ξ² : Y β‰… Z) : Ξ±.symm β‰ͺ≫ Ξ± β‰ͺ≫ Ξ² = Ξ² := by rw [← trans_assoc, symm_self_id, refl_trans] @[simp] lemma self_symm_id_assoc (Ξ± : X β‰… Y) (Ξ² : X β‰… Z) : Ξ± β‰ͺ≫ Ξ±.symm β‰ͺ≫ Ξ² = Ξ² := by rw [← trans_assoc, self_symm_id, refl_trans] lemma inv_comp_eq (Ξ± : X β‰… Y) {f : X ⟢ Z} {g : Y ⟢ Z} : Ξ±.inv ≫ f = g ↔ f = Ξ±.hom ≫ g := ⟨λ H, by simp [H.symm], Ξ» H, by simp [H]⟩ lemma eq_inv_comp (Ξ± : X β‰… Y) {f : X ⟢ Z} {g : Y ⟢ Z} : g = Ξ±.inv ≫ f ↔ Ξ±.hom ≫ g = f := (inv_comp_eq Ξ±.symm).symm lemma comp_inv_eq (Ξ± : X β‰… Y) {f : Z ⟢ Y} {g : Z ⟢ X} : f ≫ Ξ±.inv = g ↔ f = g ≫ Ξ±.hom := ⟨λ H, by simp [H.symm], Ξ» H, by simp [H]⟩ lemma eq_comp_inv (Ξ± : X β‰… Y) {f : Z ⟢ Y} {g : Z ⟢ X} : g = f ≫ Ξ±.inv ↔ g ≫ Ξ±.hom = f := (comp_inv_eq Ξ±.symm).symm lemma inv_eq_inv (f g : X β‰… Y) : f.inv = g.inv ↔ f.hom = g.hom := have βˆ€{X Y : C} (f g : X β‰… Y), f.hom = g.hom β†’ f.inv = g.inv, from Ξ» X Y f g h, by rw [ext h], ⟨this f.symm g.symm, this f g⟩ lemma hom_comp_eq_id (Ξ± : X β‰… Y) {f : Y ⟢ X} : Ξ±.hom ≫ f = πŸ™ X ↔ f = Ξ±.inv := by rw [←eq_inv_comp, comp_id] lemma comp_hom_eq_id (Ξ± : X β‰… Y) {f : Y ⟢ X} : f ≫ Ξ±.hom = πŸ™ Y ↔ f = Ξ±.inv := by rw [←eq_comp_inv, id_comp] lemma hom_eq_inv (Ξ± : X β‰… Y) (Ξ² : Y β‰… X) : Ξ±.hom = Ξ².inv ↔ Ξ².hom = Ξ±.inv := by { erw [inv_eq_inv Ξ±.symm Ξ², eq_comm], refl } end iso /-- `is_iso` typeclass expressing that a morphism is invertible. -/ class is_iso (f : X ⟢ Y) : Prop := (out : βˆƒ inv : Y ⟢ X, f ≫ inv = πŸ™ X ∧ inv ≫ f = πŸ™ Y) /-- The inverse of a morphism `f` when we have `[is_iso f]`. -/ noncomputable def inv (f : X ⟢ Y) [I : is_iso f] := classical.some I.1 namespace is_iso @[simp, reassoc] lemma hom_inv_id (f : X ⟢ Y) [I : is_iso f] : f ≫ inv f = πŸ™ X := (classical.some_spec I.1).left @[simp, reassoc] lemma inv_hom_id (f : X ⟢ Y) [I : is_iso f] : inv f ≫ f = πŸ™ Y := (classical.some_spec I.1).right end is_iso open is_iso /-- Reinterpret a morphism `f` with an `is_iso f` instance as an `iso`. -/ noncomputable def as_iso (f : X ⟢ Y) [h : is_iso f] : X β‰… Y := ⟨f, inv f, hom_inv_id f, inv_hom_id f⟩ @[simp] lemma as_iso_hom (f : X ⟢ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟢ Y) [is_iso f] : (as_iso f).inv = inv f := rfl namespace is_iso @[priority 100] -- see Note [lower instance priority] instance epi_of_iso (f : X ⟢ Y) [is_iso f] : epi f := { left_cancellation := Ξ» Z g h w, -- This is an interesting test case for better rewrite automation. by rw [← is_iso.inv_hom_id_assoc f g, w, is_iso.inv_hom_id_assoc f h] } @[priority 100] -- see Note [lower instance priority] instance mono_of_iso (f : X ⟢ Y) [is_iso f] : mono f := { right_cancellation := Ξ» Z g h w, by rw [← category.comp_id g, ← category.comp_id h, ← is_iso.hom_inv_id f, ← category.assoc, w, ← category.assoc] } @[ext] lemma inv_eq_of_hom_inv_id {f : X ⟢ Y} [is_iso f] {g : Y ⟢ X} (hom_inv_id : f ≫ g = πŸ™ X) : inv f = g := begin apply (cancel_epi f).mp, simp [hom_inv_id], end lemma inv_eq_of_inv_hom_id {f : X ⟢ Y} [is_iso f] {g : Y ⟢ X} (inv_hom_id : g ≫ f = πŸ™ Y) : inv f = g := begin apply (cancel_mono f).mp, simp [inv_hom_id], end @[ext] lemma eq_inv_of_hom_inv_id {f : X ⟢ Y} [is_iso f] {g : Y ⟢ X} (hom_inv_id : f ≫ g = πŸ™ X) : g = inv f := (inv_eq_of_hom_inv_id hom_inv_id).symm lemma eq_inv_of_inv_hom_id {f : X ⟢ Y} [is_iso f] {g : Y ⟢ X} (inv_hom_id : g ≫ f = πŸ™ Y) : g = inv f := (inv_eq_of_inv_hom_id inv_hom_id).symm instance id (X : C) : is_iso (πŸ™ X) := βŸ¨βŸ¨πŸ™ X, by simp⟩⟩ instance of_iso (f : X β‰… Y) : is_iso f.hom := ⟨⟨f.inv, by simp⟩⟩ instance of_iso_inv (f : X β‰… Y) : is_iso f.inv := is_iso.of_iso f.symm variables {f g : X ⟢ Y} {h : Y ⟢ Z} instance inv_is_iso [is_iso f] : is_iso (inv f) := is_iso.of_iso_inv (as_iso f) /- The following instance has lower priority for the following reason: Suppose we are given `f : X β‰… Y` with `X Y : Type u`. Without the lower priority, typeclass inference cannot deduce `is_iso f.hom` because `f.hom` is defeq to `(Ξ» x, x) ≫ f.hom`, triggering a loop. -/ @[priority 900] instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := is_iso.of_iso $ (as_iso f) β‰ͺ≫ (as_iso h) @[simp] lemma inv_id : inv (πŸ™ X) = πŸ™ X := by { ext, simp, } @[simp] lemma inv_comp [is_iso f] [is_iso h] : inv (f ≫ h) = inv h ≫ inv f := by { ext, simp, } @[simp] lemma inv_inv [is_iso f] : inv (inv f) = f := by { ext, simp, } @[simp] lemma iso.inv_inv (f : X β‰… Y) : inv (f.inv) = f.hom := by { ext, simp, } @[simp] lemma iso.inv_hom (f : X β‰… Y) : inv (f.hom) = f.inv := by { ext, simp, } @[simp] lemma inv_comp_eq (Ξ± : X ⟢ Y) [is_iso Ξ±] {f : X ⟢ Z} {g : Y ⟢ Z} : inv Ξ± ≫ f = g ↔ f = Ξ± ≫ g := (as_iso Ξ±).inv_comp_eq @[simp] lemma eq_inv_comp (Ξ± : X ⟢ Y) [is_iso Ξ±] {f : X ⟢ Z} {g : Y ⟢ Z} : g = inv Ξ± ≫ f ↔ Ξ± ≫ g = f := (as_iso Ξ±).eq_inv_comp @[simp] lemma comp_inv_eq (Ξ± : X ⟢ Y) [is_iso Ξ±] {f : Z ⟢ Y} {g : Z ⟢ X} : f ≫ inv Ξ± = g ↔ f = g ≫ Ξ± := (as_iso Ξ±).comp_inv_eq @[simp] lemma eq_comp_inv (Ξ± : X ⟢ Y) [is_iso Ξ±] {f : Z ⟢ Y} {g : Z ⟢ X} : g = f ≫ inv Ξ± ↔ g ≫ Ξ± = f := (as_iso Ξ±).eq_comp_inv lemma of_is_iso_comp_left {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [is_iso f] [is_iso (f ≫ g)] : is_iso g := by { rw [← id_comp g, ← inv_hom_id f, assoc], apply_instance, } lemma of_is_iso_comp_right {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [is_iso g] [is_iso (f ≫ g)] : is_iso f := by { rw [← comp_id f, ← hom_inv_id g, ← assoc], apply_instance, } lemma of_is_iso_fac_left {X Y Z : C} {f : X ⟢ Y} {g : Y ⟢ Z} {h : X ⟢ Z} [is_iso f] [hh : is_iso h] (w : f ≫ g = h) : is_iso g := by { rw ← w at hh, haveI := hh, exact of_is_iso_comp_left f g, } lemma of_is_iso_fac_right {X Y Z : C} {f : X ⟢ Y} {g : Y ⟢ Z} {h : X ⟢ Z} [is_iso g] [hh : is_iso h] (w : f ≫ g = h) : is_iso f := by { rw ← w at hh, haveI := hh, exact of_is_iso_comp_right f g, } end is_iso open is_iso lemma eq_of_inv_eq_inv {f g : X ⟢ Y} [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := begin apply (cancel_epi (inv f)).1, erw [inv_hom_id, p, inv_hom_id], end lemma is_iso.inv_eq_inv {f g : X ⟢ Y} [is_iso f] [is_iso g] : inv f = inv g ↔ f = g := iso.inv_eq_inv (as_iso f) (as_iso g) lemma hom_comp_eq_id (g : X ⟢ Y) [is_iso g] {f : Y ⟢ X} : g ≫ f = πŸ™ X ↔ f = inv g := (as_iso g).hom_comp_eq_id lemma comp_hom_eq_id (g : X ⟢ Y) [is_iso g] {f : Y ⟢ X} : f ≫ g = πŸ™ Y ↔ f = inv g := (as_iso g).comp_hom_eq_id namespace iso @[ext] lemma inv_ext {f : X β‰… Y} {g : Y ⟢ X} (hom_inv_id : f.hom ≫ g = πŸ™ X) : f.inv = g := begin apply (cancel_epi f.hom).mp, simp [hom_inv_id], end @[ext] lemma inv_ext' {f : X β‰… Y} {g : Y ⟢ X} (hom_inv_id : f.hom ≫ g = πŸ™ X) : g = f.inv := by { symmetry, ext, assumption, } /-! All these cancellation lemmas can be solved by `simp [cancel_mono]` (or `simp [cancel_epi]`), but with the current design `cancel_mono` is not a good `simp` lemma, because it generates a typeclass search. When we can see syntactically that a morphism is a `mono` or an `epi` because it came from an isomorphism, it's fine to do the cancellation via `simp`. In the longer term, it might be worth exploring making `mono` and `epi` structures, rather than typeclasses, with coercions back to `X ⟢ Y`. Presumably we could write `X β†ͺ Y` and `X β†  Y`. -/ @[simp] lemma cancel_iso_hom_left {X Y Z : C} (f : X β‰… Y) (g g' : Y ⟢ Z) : f.hom ≫ g = f.hom ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_inv_left {X Y Z : C} (f : Y β‰… X) (g g' : Y ⟢ Z) : f.inv ≫ g = f.inv ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_hom_right {X Y Z : C} (f f' : X ⟢ Y) (g : Y β‰… Z) : f ≫ g.hom = f' ≫ g.hom ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_iso_inv_right {X Y Z : C} (f f' : X ⟢ Y) (g : Z β‰… Y) : f ≫ g.inv = f' ≫ g.inv ↔ f = f' := by simp only [cancel_mono] /- Unfortunately cancelling an isomorphism from the right of a chain of compositions is awkward. We would need separate lemmas for each chain length (worse: for each pair of chain lengths). We provide two more lemmas, for case of three morphisms, because this actually comes up in practice, but then stop. -/ @[simp] lemma cancel_iso_hom_right_assoc {W X X' Y Z : C} (f : W ⟢ X) (g : X ⟢ Y) (f' : W ⟢ X') (g' : X' ⟢ Y) (h : Y β‰… Z) : f ≫ g ≫ h.hom = f' ≫ g' ≫ h.hom ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_iso_inv_right_assoc {W X X' Y Z : C} (f : W ⟢ X) (g : X ⟢ Y) (f' : W ⟢ X') (g' : X' ⟢ Y) (h : Z β‰… Y) : f ≫ g ≫ h.inv = f' ≫ g' ≫ h.inv ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end iso namespace functor universes u₁ v₁ uβ‚‚ vβ‚‚ variables {D : Type uβ‚‚} variables [category.{vβ‚‚} D] /-- A functor `F : C β₯€ D` sends isomorphisms `i : X β‰… Y` to isomorphisms `F.obj X β‰… F.obj Y` -/ @[simps] def map_iso (F : C β₯€ D) {X Y : C} (i : X β‰… Y) : F.obj X β‰… F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma map_iso_symm (F : C β₯€ D) {X Y : C} (i : X β‰… Y) : F.map_iso i.symm = (F.map_iso i).symm := rfl @[simp] lemma map_iso_trans (F : C β₯€ D) {X Y Z : C} (i : X β‰… Y) (j : Y β‰… Z) : F.map_iso (i β‰ͺ≫ j) = (F.map_iso i) β‰ͺ≫ (F.map_iso j) := by ext; apply functor.map_comp @[simp] lemma map_iso_refl (F : C β₯€ D) (X : C) : F.map_iso (iso.refl X) = iso.refl (F.obj X) := iso.ext $ F.map_id X instance map_is_iso (F : C β₯€ D) (f : X ⟢ Y) [is_iso f] : is_iso (F.map f) := is_iso.of_iso $ F.map_iso (as_iso f) @[simp] lemma map_inv (F : C β₯€ D) {X Y : C} (f : X ⟢ Y) [is_iso f] : F.map (inv f) = inv (F.map f) := by { ext, simp [←F.map_comp], } lemma map_hom_inv (F : C β₯€ D) {X Y : C} (f : X ⟢ Y) [is_iso f] : F.map f ≫ F.map (inv f) = πŸ™ (F.obj X) := by simp lemma map_inv_hom (F : C β₯€ D) {X Y : C} (f : X ⟢ Y) [is_iso f] : F.map (inv f) ≫ F.map f = πŸ™ (F.obj Y) := by simp end functor end category_theory
c863cc63841b8580f44b12463483d789fc70b6f1
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/metric_space/hausdorff_distance.lean
1f431cd2059a10c06bc2df955b0e06950052463a
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
32,470
lean
/- Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: SΓ©bastien GouΓ«zel -/ import topology.metric_space.isometry topology.instances.ennreal topology.metric_space.lipschitz /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist`. -/ noncomputable theory open_locale classical universes u v w open classical lattice set function topological_space filter namespace emetric section inf_edist open_locale ennreal variables {Ξ± : Type u} {Ξ² : Type v} [emetric_space Ξ±] [emetric_space Ξ²] {x y : Ξ±} {s t : set Ξ±} {Ξ¦ : Ξ± β†’ Ξ²} /-- The minimal edistance of a point to a set -/ def inf_edist (x : Ξ±) (s : set Ξ±) : ennreal := Inf ((edist x) '' s) @[simp] lemma inf_edist_empty : inf_edist x βˆ… = ∞ := by unfold inf_edist; simp /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s βˆͺ t) = inf_edist x s βŠ“ inf_edist x t := by simp [inf_edist, image_union, Inf_union] /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := by simp [inf_edist] /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≀ edist x y := Inf_le ((mem_image _ _ _).2 ⟨y, h, by refl⟩) /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := le_zero_iff_eq.1 $ @edist_self _ _ x β–Έ inf_edist_le_edist_of_mem h /-- The edist is monotonous with respect to inclusion -/ lemma inf_edist_le_inf_edist_of_subset (h : s βŠ† t) : inf_edist x t ≀ inf_edist x s := Inf_le_Inf (image_subset _ h) /-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/ lemma exists_edist_lt_of_inf_edist_lt {r : ennreal} (h : inf_edist x s < r) : βˆƒy∈s, edist x y < r := let ⟨t, ⟨ht, tr⟩⟩ := Inf_lt_iff.1 h in let ⟨y, ⟨ys, hy⟩⟩ := (mem_image _ _ _).1 ht in ⟨y, ys, by rwa ← hy at tr⟩ /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≀ inf_edist y s + edist x y := begin have : βˆ€z ∈ s, Inf (edist x '' s) ≀ edist y z + edist x y := Ξ»z hz, calc Inf (edist x '' s) ≀ edist x z : Inf_le ((mem_image _ _ _).2 ⟨z, hz, by refl⟩) ... ≀ edist x y + edist y z : edist_triangle _ _ _ ... = edist y z + edist x y : add_comm _ _, have : (Ξ»z, z + edist x y) (Inf (edist y '' s)) = Inf ((Ξ»z, z + edist x y) '' (edist y '' s)), { refine Inf_of_continuous _ _ (by simp), { exact continuous_id.add continuous_const }, { assume a b h, simp, apply add_le_add_right' h }}, simp only [inf_edist] at this, rw [inf_edist, inf_edist, this, ← image_comp], simpa only [and_imp, function.comp_app, lattice.le_Inf_iff, exists_imp_distrib, ball_image_iff] end /-- The edist to a set depends continuously on the point -/ lemma continuous_inf_edist : continuous (Ξ»x, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _, refine ennreal.le_of_forall_epsilon_le (λΡ Ξ΅pos h, _), have Ξ΅pos' : (0 : ennreal) < Ξ΅ := by simpa, have : inf_edist x (closure s) < inf_edist x (closure s) + Ξ΅/2 := ennreal.lt_add_right h (ennreal.half_pos Ξ΅pos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩, -- y : Ξ±, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑Ρ / 2 rcases emetric.mem_closure_iff.1 ycs (Ξ΅/2) (ennreal.half_pos Ξ΅pos') with ⟨z, zs, dyz⟩, -- z : Ξ±, zs : z ∈ s, dyz : edist y z < ↑Ρ / 2 calc inf_edist x s ≀ edist x z : inf_edist_le_edist_of_mem zs ... ≀ edist x y + edist y z : edist_triangle _ _ _ ... ≀ (inf_edist x (closure s) + Ξ΅ / 2) + (Ξ΅/2) : add_le_add' (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑Ρ : by simp [ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h, Ξ»h, emetric.mem_closure_iff.2 $ λΡ Ξ΅pos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_ind_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact closure_eq_iff_is_closed.2 h end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΞ¦ : isometry Ξ¦) : inf_edist (Ξ¦ x) (Ξ¦ '' t) = inf_edist x t := begin simp only [inf_edist], apply congr_arg, ext b, split, { assume hb, rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', hΞ¦ x z], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← hΞ¦ x y], exact mem_image_of_mem _ (mem_image_of_mem _ hy) } end end inf_edist --section /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ def Hausdorff_edist {Ξ± : Type u} [emetric_space Ξ±] (s t : set Ξ±) : ennreal := Sup ((Ξ»x, inf_edist x t) '' s) βŠ” Sup ((Ξ»x, inf_edist x s) '' t) lemma Hausdorff_edist_def {Ξ± : Type u} [emetric_space Ξ±] (s t : set Ξ±) : Hausdorff_edist s t = Sup ((Ξ»x, inf_edist x t) '' s) βŠ” Sup ((Ξ»x, inf_edist x s) '' t) := rfl attribute [irreducible] Hausdorff_edist section Hausdorff_edist open_locale ennreal variables {Ξ± : Type u} {Ξ² : Type v} [emetric_space Ξ±] [emetric_space Ξ²] {x y : Ξ±} {s t u : set Ξ±} {Ξ¦ : Ξ± β†’ Ξ²} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin erw [Hausdorff_edist_def, lattice.sup_idem, ← le_bot_iff], apply Sup_le _, simp [le_bot_iff, inf_edist_zero_of_mem] {contextual := tt}, end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ennreal} (H1 : βˆ€x ∈ s, inf_edist x t ≀ r) (H2 : βˆ€x ∈ t, inf_edist x s ≀ r) : Hausdorff_edist s t ≀ r := begin simp only [Hausdorff_edist, -mem_image, set.ball_image_iff, lattice.Sup_le_iff, lattice.sup_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ennreal} (H1 : βˆ€x ∈ s, βˆƒy ∈ t, edist x y ≀ r) (H2 : βˆ€x ∈ t, βˆƒy ∈ s, edist x y ≀ r) : Hausdorff_edist s t ≀ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≀ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans (le_Sup _) le_sup_left, exact mem_image_of_mem _ h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ennreal} (h : x ∈ s) (H : Hausdorff_edist s t < r) : βˆƒy∈t, edist x y < r := exists_edist_lt_of_inf_edist_lt $ calc inf_edist x t ≀ Sup ((Ξ»x, inf_edist x t) '' s) : le_Sup (mem_image_of_mem _ h) ... ≀ Sup ((Ξ»x, inf_edist x t) '' s) βŠ” Sup ((Ξ»x, inf_edist x s) '' t) : le_sup_left ... < r : by rwa Hausdorff_edist_def at H /-- The distance from `x` to `s`or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≀ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_epsilon_le $ λΡ Ξ΅pos h, begin have Ξ΅pos' : (0 : ennreal) < Ξ΅ := by simpa, have : inf_edist x s < inf_edist x s + Ξ΅/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1 (ennreal.half_pos Ξ΅pos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩, -- y : Ξ±, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑Ρ / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + Ξ΅/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2 (ennreal.half_pos Ξ΅pos'), rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : Ξ±, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑Ρ / 2 calc inf_edist x t ≀ edist x z : inf_edist_le_edist_of_mem zt ... ≀ edist x y + edist y z : edist_triangle _ _ _ ... ≀ (inf_edist x s + Ξ΅/2) + (Hausdorff_edist s t + Ξ΅/2) : add_le_add' (le_of_lt dxy) (le_of_lt dyz) ... = inf_edist x s + Hausdorff_edist s t + Ξ΅ : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Ξ¦) : Hausdorff_edist (Ξ¦ '' s) (Ξ¦ '' t) = Hausdorff_edist s t := begin unfold Hausdorff_edist, congr, { ext b, split, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', inf_edist_image h], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← inf_edist_image h], exact mem_image_of_mem _ (mem_image_of_mem _ hy) }}, { ext b, split, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', inf_edist_image h], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← inf_edist_image h], exact mem_image_of_mem _ (mem_image_of_mem _ hy) }} end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≀ diam (s βˆͺ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { exact Ξ»z hz, ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact Ξ»z hz, ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≀ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [and_imp, set.mem_image, lattice.Sup_le_iff, exists_imp_distrib, lattice.sup_le_iff, -mem_image, set.ball_image_iff], split, show βˆ€x ∈ s, inf_edist x u ≀ Hausdorff_edist s t + Hausdorff_edist t u, from Ξ»x xs, calc inf_edist x u ≀ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≀ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xs), show βˆ€x ∈ u, inf_edist x s ≀ Hausdorff_edist s t + Hausdorff_edist t u, from Ξ»x xu, calc inf_edist x s ≀ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≀ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xu) ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := begin erw ← le_bot_iff, simp only [Hausdorff_edist, inf_edist_closure, -le_zero_iff_eq, and_imp, set.mem_image, lattice.Sup_le_iff, exists_imp_distrib, lattice.sup_le_iff, set.ball_image_iff, ennreal.bot_eq_zero, -mem_image], simp only [inf_edist_zero_of_mem, mem_closure_iff_inf_edist_zero, le_refl, and_self, forall_true_iff] {contextual := tt} end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≀ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≀ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closureβ‚‚ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := ⟨begin assume h, refine subset.antisymm _ _, { have : s βŠ† closure t := Ξ»x xs, mem_closure_iff_inf_edist_zero.2 $ begin erw ← le_bot_iff, have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ t xs, rwa h at this, end, by rw ← @closure_closure _ _ t; exact closure_mono this }, { have : t βŠ† closure s := Ξ»x xt, mem_closure_iff_inf_edist_zero.2 $ begin erw ← le_bot_iff, have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ s xt, rw Hausdorff_edist_comm at h, rwa h at this, end, by rw ← @closure_closure _ _ s; exact closure_mono this } end, Ξ»h, by rw [← Hausdorff_edist_closure, h, Hausdorff_edist_self]⟩ /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_eq_iff_is_closed.2 hs, closure_eq_iff_is_closed.2 ht] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s βˆ… = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x βˆ… ≀ Hausdorff_edist s βˆ… := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t β‰  ⊀) : t.nonempty := t.eq_empty_or_nonempty.elim (Ξ» ht, (fin $ ht.symm β–Έ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t β‰  ⊀) : s = βˆ… ∧ t = βˆ… ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-Now, we turn to the same notions in metric spaces. To avoid the difficulties related to Inf and Sup on ℝ (which is only conditionnally complete), we use the notions in ennreal formulated in terms of the edistance, and coerce them to ℝ. Then their properties follow readily from the corresponding properties in ennreal, modulo some tedious rewriting of inequalities from one to the other -/ namespace metric section variables {Ξ± : Type u} {Ξ² : Type v} [metric_space Ξ±] [metric_space Ξ²] {s t u : set Ξ±} {x y : Ξ±} {Ξ¦ : Ξ± β†’ Ξ²} open emetric /-- The minimal distance of a point to a set -/ def inf_dist (x : Ξ±) (s : set Ξ±) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≀ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ennreal) -/ @[simp] lemma inf_dist_empty : inf_dist x βˆ… = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s β‰  ⊀ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≀ edist x y : inf_edist_le_edist_of_mem hy ... < ⊀ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≀ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s βŠ† t) (hs : s.nonempty) : inf_dist x t ≀ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_le_inf_edist_of_subset h end /-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/ lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s.nonempty) : βˆƒy∈s, dist x y < r := begin have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h, have : inf_edist x s < ennreal.of_real r, { rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h, simp }, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy, exact ⟨y, ys, hy⟩, end /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≀ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { by simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { apply inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (Ξ»x, inf_dist x s) := lipschitz_with.of_le_add $ Ξ» x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ lemma uniform_continuous_inf_dist_pt : uniform_continuous (Ξ»x, inf_dist x s) := (lipschitz_inf_dist_pt s).uniform_continuous /-- The minimal distance to a set is continuous in point -/ lemma continuous_inf_dist_pt : continuous (Ξ»x, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma mem_iff_inf_dist_zero_of_closed (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := begin have := @mem_closure_iff_inf_dist_zero _ _ s x hs, rwa closure_eq_iff_is_closed.2 h at this end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΞ¦ : isometry Ξ¦) : inf_dist (Ξ¦ x) (Ξ¦ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΞ¦] /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set Ξ±) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≀ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t β‰  ⊀ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≀ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≀ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≀ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt this (by simp [lt_top_iff_ne_top])) end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s βˆ… = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist βˆ… s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : r β‰₯ 0) (H1 : βˆ€x ∈ s, inf_dist x t ≀ r) (H2 : βˆ€x ∈ t, inf_dist x s ≀ r) : Hausdorff_dist s t ≀ r := begin by_cases h1 : Hausdorff_edist s t = ⊀, by rwa [Hausdorff_dist, h1, ennreal.top_to_real], cases s.eq_empty_or_nonempty with hs hs, by rwa [hs, Hausdorff_dist_empty'], cases t.eq_empty_or_nonempty with ht ht, by rwa [ht, Hausdorff_dist_empty], have : Hausdorff_edist s t ≀ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≀ r) (H1 : βˆ€x ∈ s, βˆƒy ∈ t, dist x y ≀ r) (H2 : βˆ€x ∈ t, βˆƒy ∈ s, dist x y ≀ r) : Hausdorff_dist s t ≀ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≀ diam (s βˆͺ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact Ξ»z hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact Ξ»z hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t β‰  ⊀) : inf_dist x t ≀ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t β‰  ⊀) : βˆƒy∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t β‰  ⊀) : βˆƒx∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t β‰  ⊀) : inf_dist x t ≀ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Ξ¦) : Hausdorff_dist (Ξ¦ '' s) (Ξ¦ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t β‰  ⊀) : Hausdorff_dist s u ≀ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊀, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≀ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊀ := calc Hausdorff_edist t u ≀ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊀ : by simp [ennreal.add_lt_top]; simp [ennreal.lt_top_iff_ne_top, h, fin], rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin (lt_top_iff_ne_top.1 Dtu), ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u β‰  ⊀) : Hausdorff_dist s u ≀ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≀ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closureβ‚‚ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t β‰  ⊀) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t β‰  ⊀) : Hausdorff_dist s t = 0 ↔ s = t := by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section end metric --namespace
ea6dae68b824f05f2fa8b0837b7a57d3101448f4
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/mynat/extra_pow.lean
7531ad579a481cc13c0a9f22a24974817660c648
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
3,847
lean
-- vim: ts=2 sw=0 sts=-1 et ai tw=70 import .basic import .le import .lt namespace hidden namespace mynat variables {m n k p a b c: mynat} theorem lt_to_mul: 1 < k β†’ n β‰  0 β†’ n < n * k := (Ξ» h1k hnn0, lt_mul hnn0 h1k) theorem lt_rhs_nonzero: m < n β†’ n β‰  0 := begin assume hmn hn0, rw hn0 at hmn, from lt_nzero hmn, end theorem pow_gt_1: 1 < a β†’ 1 < a ^ succ n := begin assume h1a, induction n, { from h1a, }, { rw pow_succ, from lt_comb_mul h1a n_ih, }, end -- maybe should be done better than this theorem pow_gt_1_converse: 1 < a ^ succ n β†’ 1 < a := begin cases a, { simp, assume h, from h, }, { cases a, { simp, assume h, from h, }, { assume _, apply @lt_add _ _ 1, from zero_lt_succ, }, }, end theorem exp_nonzero: a β‰  0 β†’ a ^ n β‰  0 := begin assume han0 hexp0, induction n with n_n n_ih, { cases hexp0, }, { rw pow_succ at hexp0, from n_ih (mul_integral han0 hexp0), }, end theorem exp_monotone: 1 < a β†’ n < m β†’ a ^ n < a ^ m := begin assume h1a hnm, cases (lt_iff_succ_le.mp hnm) with d hd, rw [hd, succ_add, ←add_succ, pow_add], have han0: a β‰  0, { assume ha0, rw ha0 at h1a, from lt_nzero h1a, }, from lt_to_mul (pow_gt_1 h1a) (exp_nonzero han0), end theorem lt_impl_neq: m < n β†’ m β‰  n := begin assume hmltn hmeqn, rw hmeqn at hmltn, from lt_nrefl hmltn, end theorem pow_cancel_left: -- aka, "taking base-a logs" 1 < a β†’ a ^ n = a ^ m β†’ n = m := begin wlog_le m n, { assume h1a hanam, symmetry, from hsymm h1a hanam.symm, }, { assume h1a haman, cases (le_iff_lt_or_eq.mp hle) with hlt heq, { exfalso, from lt_impl_neq (exp_monotone h1a hlt) haman, }, { assumption, }, }, end theorem pow_monotone: 1 < a β†’ n β‰  0 β†’ a < b β†’ a ^ n < b ^ n := begin assume h1a hnn0 hab, cases n, { contradiction, }, { clear hnn0, induction n with n hn, { assumption, }, { conv { congr, rw pow_succ, skip, rw pow_succ, }, from lt_comb_mul hab hn, }, }, end theorem pow_monotone_nonstrict: a ≀ b β†’ a ^ n ≀ b ^ n := begin assume hab, induction n with n hn, { from le_refl, }, { apply le_mul_comb, { assumption, }, { assumption, }, }, end theorem pow_cancel_right: -- aka, "taking n-th roots" 1 < a β†’ n β‰  0 β†’ a ^ n = b ^ n β†’ a = b := begin assume h1a hnn0 hanbn, have h1b: 1 < b, { cases n, { contradiction, }, { have h1asn := pow_gt_1 h1a, rw hanbn at h1asn, from pow_gt_1_converse h1asn, }, }, wlog_le a b, { assume h1a hanbn h1b, symmetry, from hsymm h1b hanbn.symm h1a, }, { assume h1b hbnan h1a, cases (le_iff_lt_or_eq.mp hle) with hlt heq, { have := pow_monotone h1a hnn0 hlt, exfalso, from (lt_impl_neq this) hbnan.symm, }, { symmetry, assumption, }, }, end -- this is probably bad, I'm rusty theorem root_monotone: 1 < a β†’ n β‰  0 β†’ a ^ n ≀ b ^ n β†’ a ≀ b := begin assume h1a hnn0 hanbn, by_contradiction, cases n, { contradiction, }, { cases b, { simp at hanbn, rw ←pow_succ at hanbn, have := @pow_gt_1 n a h1a, have := lt_le_chain _ this hanbn, from lt_nzero this, }, { cases b, { simp at hanbn, rw ←pow_succ at hanbn, have := @pow_gt_1 n a h1a, have := lt_le_chain _ this hanbn, from lt_nrefl this, }, { have h1b: 1 < b.succ.succ, { rw ←add_one_succ, rw add_comm, from @lt_to_add_succ 1 b, }, have := pow_monotone h1b hnn0 a_1, contradiction, }, }, }, end end mynat end hidden
5b49fe7cf1c29e53ca66c2b77b444bfd397ae6c0
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/denoms_clearable.lean
bf5a0d881afeb78034e6857b5c470d1ba29243f9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,676
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.erase_lead import data.polynomial.eval /-! # Denominators of evaluation of polynomials at ratios Let `i : R β†’ K` be a homomorphism of semirings. Assume that `K` is commutative. If `a` and `b` are elements of `R` such that `i b ∈ K` is invertible, then for any polynomial `f ∈ R[X]` the "mathematical" expression `b ^ f.nat_degree * f (a / b) ∈ K` is in the image of the homomorphism `i`. -/ open polynomial finset open_locale polynomial section denoms_clearable variables {R K : Type*} [semiring R] [comm_semiring K] {i : R β†’+* K} variables {a b : R} {bi : K} -- TODO: use hypothesis (ub : is_unit (i b)) to work with localizations. /-- `denoms_clearable` formalizes the property that `b ^ N * f (a / b)` does not have denominators, if the inequality `f.nat_degree ≀ N` holds. The definition asserts the existence of an element `D` of `R` and an element `bi = 1 / i b` of `K` such that clearing the denominators of the fraction equals `i D`. -/ def denoms_clearable (a b : R) (N : β„•) (f : R[X]) (i : R β†’+* K) : Prop := βˆƒ (D : R) (bi : K), bi * i b = 1 ∧ i D = i b ^ N * eval (i a * bi) (f.map i) lemma denoms_clearable_zero (N : β„•) (a : R) (bu : bi * i b = 1) : denoms_clearable a b N 0 i := ⟨0, bi, bu, by simp only [eval_zero, ring_hom.map_zero, mul_zero, polynomial.map_zero]⟩ lemma denoms_clearable_C_mul_X_pow {N : β„•} (a : R) (bu : bi * i b = 1) {n : β„•} (r : R) (nN : n ≀ N) : denoms_clearable a b N (C r * X ^ n) i := begin refine ⟨r * a ^ n * b ^ (N - n), bi, bu, _⟩, rw [C_mul_X_pow_eq_monomial, map_monomial, ← C_mul_X_pow_eq_monomial, eval_mul, eval_pow, eval_C], rw [ring_hom.map_mul, ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_pow, eval_X, mul_comm], rw [← tsub_add_cancel_of_le nN] {occs := occurrences.pos [2]}, rw [pow_add, mul_assoc, mul_comm (i b ^ n), mul_pow, mul_assoc, mul_assoc (i a ^ n), ← mul_pow], rw [bu, one_pow, mul_one], end lemma denoms_clearable.add {N : β„•} {f g : R[X]} : denoms_clearable a b N f i β†’ denoms_clearable a b N g i β†’ denoms_clearable a b N (f + g) i := Ξ» ⟨Df, bf, bfu, Hf⟩ ⟨Dg, bg, bgu, Hg⟩, ⟨Df + Dg, bf, bfu, begin rw [ring_hom.map_add, polynomial.map_add, eval_add, mul_add, Hf, Hg], congr, refine @inv_unique K _ (i b) bg bf _ _; rwa mul_comm, end ⟩ lemma denoms_clearable_of_nat_degree_le (N : β„•) (a : R) (bu : bi * i b = 1) : βˆ€ (f : R[X]), f.nat_degree ≀ N β†’ denoms_clearable a b N f i := induction_with_nat_degree_le _ N (denoms_clearable_zero N a bu) (Ξ» N_1 r r0, denoms_clearable_C_mul_X_pow a bu r) (Ξ» f g fg gN df dg, df.add dg) /-- If `i : R β†’ K` is a ring homomorphism, `f` is a polynomial with coefficients in `R`, `a, b` are elements of `R`, with `i b` invertible, then there is a `D ∈ R` such that `b ^ f.nat_degree * f (a / b)` equals `i D`. -/ theorem denoms_clearable_nat_degree (i : R β†’+* K) (f : R[X]) (a : R) (bu : bi * i b = 1) : denoms_clearable a b f.nat_degree f i := denoms_clearable_of_nat_degree_le f.nat_degree a bu f le_rfl end denoms_clearable open ring_hom /-- Evaluating a polynomial with integer coefficients at a rational number and clearing denominators, yields a number greater than or equal to one. The target can be any `linear_ordered_field K`. The assumption on `K` could be weakened to `linear_ordered_comm_ring` assuming that the image of the denominator is invertible in `K`. -/ lemma one_le_pow_mul_abs_eval_div {K : Type*} [linear_ordered_field K] {f : β„€[X]} {a b : β„€} (b0 : 0 < b) (fab : eval ((a : K) / b) (f.map (algebra_map β„€ K)) β‰  0) : (1 : K) ≀ b ^ f.nat_degree * |eval ((a : K) / b) (f.map (algebra_map β„€ K))| := begin obtain ⟨ev, bi, bu, hF⟩ := @denoms_clearable_nat_degree _ _ _ _ b _ (algebra_map β„€ K) f a (by { rw [eq_int_cast, one_div_mul_cancel], rw [int.cast_ne_zero], exact (b0.ne.symm) }), obtain Fa := congr_arg abs hF, rw [eq_one_div_of_mul_eq_one_left bu, eq_int_cast, eq_int_cast, abs_mul] at Fa, rw [abs_of_pos (pow_pos (int.cast_pos.mpr b0) _ : 0 < (b : K) ^ _), one_div, eq_int_cast] at Fa, rw [div_eq_mul_inv, ← Fa, ← int.cast_abs, ← int.cast_one, int.cast_le], refine int.le_of_lt_add_one ((lt_add_iff_pos_left 1).mpr (abs_pos.mpr (Ξ» F0, fab _))), rw [eq_one_div_of_mul_eq_one_left bu, F0, one_div, eq_int_cast, int.cast_zero, zero_eq_mul] at hF, cases hF with hF hF, { exact (not_le.mpr b0 (le_of_eq (int.cast_eq_zero.mp (pow_eq_zero hF)))).elim }, { rwa div_eq_mul_inv } end
26613e0e213df30fa26c0bad438bd951f46f7fbc
367134ba5a65885e863bdc4507601606690974c1
/src/order/filter/archimedean.lean
e7e2997c605c8083296b1ef1d9bfa43cf2e1811f
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,981
lean
/- Copyright (c) 2019 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Yury Kudryashov -/ import order.filter.at_top_bot import algebra.archimedean /-! # `at_top` filter and archimedean (semi)rings/fields In this file we prove that for a linear ordered archimedean semiring `R` and a function `f : Ξ± β†’ β„•`, the function `coe ∘ f : Ξ± β†’ R` tends to `at_top` along a filter `l` if and only if so does `f`. We also prove that `coe : β„• β†’ R` tends to `at_top` along `at_top`, as well as version of these two results for `β„€` (and a ring `R`) and `β„š` (and a field `R`). -/ variables {Ξ± R : Type*} open filter lemma tendsto_coe_nat_at_top_iff [ordered_semiring R] [nontrivial R] [archimedean R] {f : Ξ± β†’ β„•} {l : filter Ξ±} : tendsto (Ξ» n, (f n : R)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ aβ‚‚, nat.cast_le) exists_nat_ge lemma tendsto_coe_nat_at_top_at_top [ordered_semiring R] [archimedean R] : tendsto (coe : β„• β†’ R) at_top at_top := nat.mono_cast.tendsto_at_top_at_top exists_nat_ge lemma tendsto_coe_int_at_top_iff [ordered_ring R] [nontrivial R] [archimedean R] {f : Ξ± β†’ β„€} {l : filter Ξ±} : tendsto (Ξ» n, (f n : R)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ aβ‚‚, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_ge r in ⟨(n:β„€), hn⟩ lemma tendsto_coe_int_at_top_at_top [ordered_ring R] [archimedean R] : tendsto (coe : β„€ β†’ R) at_top at_top := int.cast_mono.tendsto_at_top_at_top $ Ξ» b, let ⟨n, hn⟩ := exists_nat_ge b in ⟨n, hn⟩ lemma tendsto_coe_rat_at_top_iff [linear_ordered_field R] [archimedean R] {f : Ξ± β†’ β„š} {l : filter Ξ±} : tendsto (Ξ» n, (f n : R)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ aβ‚‚, rat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_ge r in ⟨(n:β„š), by assumption_mod_cast⟩ variables [linear_ordered_semiring R] [archimedean R] variables {l : filter Ξ±} {f : Ξ± β†’ R} {r : R} /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `β„•`, `β„€` and `ℝ`, although not necessary (a version in ordered fields is given in `filter.tendsto.const_mul_at_top`). -/ lemma filter.tendsto.const_mul_at_top' (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (Ξ»x, r * f x) l at_top := begin apply tendsto_at_top.2 (Ξ»b, _), obtain ⟨n : β„•, hn : 1 ≀ n β€’β„• r⟩ := archimedean.arch 1 hr, rw nsmul_eq_mul' at hn, filter_upwards [tendsto_at_top.1 hf (n * max b 0)], assume x hx, calc b ≀ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ } ... ≀ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn (le_max_right _ _) ... = r * (n * max b 0) : by rw [mul_assoc] ... ≀ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr) end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `β„•`, `β„€` and `ℝ`, although not necessary (a version in ordered fields is given in `filter.tendsto.at_top_mul_const`). -/ lemma filter.tendsto.at_top_mul_const' (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (Ξ»x, f x * r) l at_top := begin apply tendsto_at_top.2 (Ξ»b, _), obtain ⟨n : β„•, hn : 1 ≀ n β€’β„• r⟩ := archimedean.arch 1 hr, have hn' : 1 ≀ (n : R) * r, by rwa nsmul_eq_mul at hn, filter_upwards [tendsto_at_top.1 hf (max b 0 * n)], assume x hx, calc b ≀ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ } ... ≀ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _) ... = (max b 0 * n) * r : by rw [mul_assoc] ... ≀ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr) end
236c66622d5f1c856abc5c9f8d09081fe31d2245
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/set_opt_tac.lean
1ee88da502749a41882fccdd8406915c8baad82d
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
314
lean
open tactic bool example (a b : nat) (H : a + b = 0) : a = a := by do H ← get_local `H, t ← infer_type H, trace t, set_bool_option `pp.all tt, trace "after pp.all true", trace t, rfl ← mk_const `rfl, apply rfl print "set_bool_option tactic does not affect other commands" check (0:nat) + 1
5bc46cd63ecbeaae30a837560ced93d74bc8b251
626e312b5c1cb2d88fca108f5933076012633192
/src/combinatorics/simple_graph/adj_matrix.lean
230fce0cef9e53926f02a0bb12a687c421fd1df3
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,176
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import combinatorics.simple_graph.basic import data.rel import linear_algebra.matrix.trace /-! # Adjacency Matrices This module defines the adjacency matrix of a graph, and provides theorems connecting graph properties to computational properties of the matrix. ## Main definitions * `adj_matrix` is the adjacency matrix of a `simple_graph` with coefficients in a given semiring. -/ open_locale big_operators matrix open finset matrix simple_graph universes u v variables {Ξ± : Type u} variables (R : Type v) [semiring R] namespace simple_graph variables (G : simple_graph Ξ±) (R) [decidable_rel G.adj] /-- `adj_matrix G R` is the matrix `A` such that `A i j = (1 : R)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adj_matrix : matrix Ξ± Ξ± R | i j := if (G.adj i j) then 1 else 0 variable {R} @[simp] lemma adj_matrix_apply (v w : Ξ±) : G.adj_matrix R v w = if (G.adj v w) then 1 else 0 := rfl @[simp] theorem transpose_adj_matrix : (G.adj_matrix R)α΅€ = G.adj_matrix R := by { ext, simp [adj_comm] } variables [fintype Ξ±] @[simp] lemma adj_matrix_dot_product (v : Ξ±) (vec : Ξ± β†’ R) : dot_product (G.adj_matrix R v) vec = βˆ‘ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter] @[simp] lemma dot_product_adj_matrix (v : Ξ±) (vec : Ξ± β†’ R) : dot_product vec (G.adj_matrix R v) = βˆ‘ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter, finset.sum_apply] @[simp] lemma adj_matrix_mul_vec_apply (v : Ξ±) (vec : Ξ± β†’ R) : ((G.adj_matrix R).mul_vec vec) v = βˆ‘ u in G.neighbor_finset v, vec u := by rw [mul_vec, adj_matrix_dot_product] @[simp] lemma adj_matrix_vec_mul_apply (v : Ξ±) (vec : Ξ± β†’ R) : ((G.adj_matrix R).vec_mul vec) v = βˆ‘ u in G.neighbor_finset v, vec u := begin rw [← dot_product_adj_matrix, vec_mul], refine congr rfl _, ext, rw [← transpose_apply (adj_matrix R G) x v, transpose_adj_matrix], end @[simp] lemma adj_matrix_mul_apply (M : matrix Ξ± Ξ± R) (v w : Ξ±) : (G.adj_matrix R ⬝ M) v w = βˆ‘ u in G.neighbor_finset v, M u w := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter] @[simp] lemma mul_adj_matrix_apply (M : matrix Ξ± Ξ± R) (v w : Ξ±) : (M ⬝ G.adj_matrix R) v w = βˆ‘ u in G.neighbor_finset w, M v u := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter, adj_comm] variable (R) theorem trace_adj_matrix : matrix.trace Ξ± R R (G.adj_matrix R) = 0 := by simp variable {R} theorem adj_matrix_mul_self_apply_self (i : Ξ±) : ((G.adj_matrix R) ⬝ (G.adj_matrix R)) i i = degree G i := by simp [degree] variable {G} @[simp] lemma adj_matrix_mul_vec_const_apply {r : R} {v : Ξ±} : (G.adj_matrix R).mul_vec (function.const _ r) v = G.degree v * r := by simp [degree] lemma adj_matrix_mul_vec_const_apply_of_regular {d : β„•} {r : R} (hd : G.is_regular_of_degree d) {v : Ξ±} : (G.adj_matrix R).mul_vec (function.const _ r) v = (d * r) := by simp [hd v] end simple_graph
fda5a2ae75864538c49d6c8e82e6d9f6b53a93f7
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/convex/specific_functions.lean
d5c55c7f462aecdf39378fc7279eeb5d5b5334a9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
9,903
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, SΓ©bastien GouΓ«zel -/ import analysis.calculus.mean_value import analysis.special_functions.pow_deriv /-! # Collection of convex functions In this file we prove that the following functions are convex: * `strict_convex_on_exp` : The exponential function is strictly convex. * `even.convex_on_pow`, `even.strict_convex_on_pow` : For an even `n : β„•`, `Ξ» x, x ^ n` is convex and strictly convex when `2 ≀ n`. * `convex_on_pow`, `strict_convex_on_pow` : For `n : β„•`, `Ξ» x, x ^ n` is convex on $[0, +∞)$ and strictly convex when `2 ≀ n`. * `convex_on_zpow`, `strict_convex_on_zpow` : For `m : β„€`, `Ξ» x, x ^ m` is convex on $[0, +∞)$ and strictly convex when `m β‰  0, 1`. * `convex_on_rpow`, `strict_convex_on_rpow` : For `p : ℝ`, `Ξ» x, x ^ p` is convex on $[0, +∞)$ when `1 ≀ p` and strictly convex when `1 < p`. * `strict_concave_on_log_Ioi`, `strict_concave_on_log_Iio`: `real.log` is strictly concave on $(0, +∞)$ and $(-∞, 0)$ respectively. ## TODO For `p : ℝ`, prove that `Ξ» x, x ^ p` is concave when `0 ≀ p ≀ 1` and strictly concave when `0 < p < 1`. -/ open real set open_locale big_operators /-- `exp` is strictly convex on the whole real line. -/ lemma strict_convex_on_exp : strict_convex_on ℝ univ exp := strict_convex_on_univ_of_deriv2_pos differentiable_exp (Ξ» x, (iter_deriv_exp 2).symm β–Έ exp_pos x) /-- `exp` is convex on the whole real line. -/ lemma convex_on_exp : convex_on ℝ univ exp := strict_convex_on_exp.convex_on /-- `x^n`, `n : β„•` is convex on the whole real line whenever `n` is even -/ lemma even.convex_on_pow {n : β„•} (hn : even n) : convex_on ℝ set.univ (Ξ» x : ℝ, x^n) := begin apply convex_on_univ_of_deriv2_nonneg differentiable_pow, { simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] }, { intro x, obtain ⟨k, hk⟩ := (hn.tsub_even $ even_bit0 _).exists_two_nsmul _, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub, hk, nsmul_eq_mul, pow_mul'], exact mul_nonneg (nat.cast_nonneg _) (pow_two_nonneg _) } end /-- `x^n`, `n : β„•` is strictly convex on the whole real line whenever `n β‰  0` is even. -/ lemma even.strict_convex_on_pow {n : β„•} (hn : even n) (h : n β‰  0) : strict_convex_on ℝ set.univ (Ξ» x : ℝ, x^n) := begin apply strict_mono.strict_convex_on_univ_of_deriv differentiable_pow, rw deriv_pow', replace h := nat.pos_of_ne_zero h, exact strict_mono.const_mul (odd.strict_mono_pow $ nat.even.sub_odd h hn $ nat.odd_iff.2 rfl) (nat.cast_pos.2 h), end /-- `x^n`, `n : β„•` is convex on `[0, +∞)` for all `n` -/ lemma convex_on_pow (n : β„•) : convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^n) := begin apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on differentiable_on_pow, { simp only [deriv_pow'], exact (@differentiable_on_pow ℝ _ _ _).const_mul (n : ℝ) }, { intros x hx, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub], exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (interior_subset hx) _) } end /-- `x^n`, `n : β„•` is strictly convex on `[0, +∞)` for all `n` greater than `2`. -/ lemma strict_convex_on_pow {n : β„•} (hn : 2 ≀ n) : strict_convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^n) := begin apply strict_mono_on.strict_convex_on_of_deriv (convex_Ici _) (continuous_on_pow _) differentiable_on_pow, rw [deriv_pow', interior_Ici], exact Ξ» x (hx : 0 < x) y hy hxy, mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_left hxy hx.le $ nat.sub_pos_of_lt hn) (nat.cast_pos.2 $ zero_lt_two.trans_le hn), end lemma finset.prod_nonneg_of_card_nonpos_even {Ξ± Ξ² : Type*} [linear_ordered_comm_ring Ξ²] {f : Ξ± β†’ Ξ²} [decidable_pred (Ξ» x, f x ≀ 0)] {s : finset Ξ±} (h0 : even (s.filter (Ξ» x, f x ≀ 0)).card) : 0 ≀ ∏ x in s, f x := calc 0 ≀ (∏ x in s, ((if f x ≀ 0 then (-1:Ξ²) else 1) * f x)) : finset.prod_nonneg (Ξ» x _, by { split_ifs with hx hx, by simp [hx], simp at hx ⊒, exact le_of_lt hx }) ... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one, mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul] lemma int_prod_range_nonneg (m : β„€) (n : β„•) (hn : even n) : 0 ≀ ∏ k in finset.range n, (m - k) := begin rcases hn with ⟨n, rfl⟩, induction n with n ihn, { simp }, rw ← two_mul at ihn, rw [← two_mul, nat.succ_eq_add_one, mul_add, mul_one, bit0, ← add_assoc, finset.prod_range_succ, finset.prod_range_succ, mul_assoc], refine mul_nonneg ihn _, generalize : (1 + 1) * n = k, cases le_or_lt m k with hmk hmk, { have : m ≀ k + 1, from hmk.trans (lt_add_one ↑k).le, exact mul_nonneg_of_nonpos_of_nonpos (sub_nonpos_of_le hmk) (sub_nonpos_of_le this) }, { exact mul_nonneg (sub_nonneg_of_le hmk.le) (sub_nonneg_of_le hmk) } end lemma int_prod_range_pos {m : β„€} {n : β„•} (hn : even n) (hm : m βˆ‰ Ico (0 : β„€) n) : 0 < ∏ k in finset.range n, (m - k) := begin refine (int_prod_range_nonneg m n hn).lt_of_ne (Ξ» h, hm _), rw [eq_comm, finset.prod_eq_zero_iff] at h, obtain ⟨a, ha, h⟩ := h, rw sub_eq_zero.1 h, exact ⟨int.coe_zero_le _, int.coe_nat_lt.2 $ finset.mem_range.1 ha⟩, end /-- `x^m`, `m : β„€` is convex on `(0, +∞)` for all `m` -/ lemma convex_on_zpow (m : β„€) : convex_on ℝ (Ioi 0) (Ξ» x : ℝ, x^m) := begin have : βˆ€ n : β„€, differentiable_on ℝ (Ξ» x, x ^ n) (Ioi (0 : ℝ)), from Ξ» n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _), apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { simp only [interior_Ioi, deriv_zpow'] }, { exact (this _).continuous_on }, { exact this _ }, { exact (this _).const_mul _ }, { intros x hx, simp only [iter_deriv_zpow, ← int.cast_coe_nat, ← int.cast_sub, ← int.cast_prod], refine mul_nonneg (int.cast_nonneg.2 _) (zpow_nonneg (le_of_lt hx) _), exact int_prod_range_nonneg _ _ (even_bit0 1) } end /-- `x^m`, `m : β„€` is convex on `(0, +∞)` for all `m` except `0` and `1`. -/ lemma strict_convex_on_zpow {m : β„€} (hmβ‚€ : m β‰  0) (hm₁ : m β‰  1) : strict_convex_on ℝ (Ioi 0) (Ξ» x : ℝ, x^m) := begin have : βˆ€ n : β„€, differentiable_on ℝ (Ξ» x, x ^ n) (Ioi (0 : ℝ)), from Ξ» n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _), apply strict_convex_on_of_deriv2_pos (convex_Ioi 0), { exact (this _).continuous_on }, all_goals { rw interior_Ioi }, { exact this _ }, intros x hx, simp only [iter_deriv_zpow, ← int.cast_coe_nat, ← int.cast_sub, ← int.cast_prod], refine mul_pos (int.cast_pos.2 _) (zpow_pos_of_pos hx _), refine int_prod_range_pos (even_bit0 1) (Ξ» hm, _), norm_cast at hm, rw ←finset.coe_Ico at hm, fin_cases hm, { exact hmβ‚€ rfl }, { exact hm₁ rfl } end lemma convex_on_rpow {p : ℝ} (hp : 1 ≀ p) : convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^p) := begin have A : deriv (Ξ» (x : ℝ), x ^ p) = Ξ» x, p * x^(p-1), by { ext x, simp [hp] }, apply convex_on_of_deriv2_nonneg (convex_Ici 0), { exact continuous_on_id.rpow_const (Ξ» x _, or.inr (zero_le_one.trans hp)) }, { exact (differentiable_rpow_const hp).differentiable_on }, { rw A, assume x hx, replace hx : x β‰  0, by { simp at hx, exact ne_of_gt hx }, simp [differentiable_at.differentiable_within_at, hx] }, { assume x hx, replace hx : 0 < x, by simpa using hx, suffices : 0 ≀ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], apply mul_nonneg (le_trans zero_le_one hp), exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg hx.le _) } end lemma strict_convex_on_rpow {p : ℝ} (hp : 1 < p) : strict_convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^p) := begin have A : deriv (Ξ» (x : ℝ), x ^ p) = Ξ» x, p * x^(p-1), by { ext x, simp [hp.le] }, apply strict_convex_on_of_deriv2_pos (convex_Ici 0), { exact continuous_on_id.rpow_const (Ξ» x _, or.inr (zero_le_one.trans hp.le)) }, { exact (differentiable_rpow_const hp.le).differentiable_on }, rw interior_Ici, rintro x (hx : 0 < x), suffices : 0 < p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], exact mul_pos (zero_lt_one.trans hp) (mul_pos (sub_pos_of_lt hp) (rpow_pos_of_pos hx _)), end lemma strict_concave_on_log_Ioi : strict_concave_on ℝ (Ioi 0) log := begin have h₁ : Ioi 0 βŠ† ({0} : set ℝ)ᢜ, { exact Ξ» x (hx : 0 < x) (hx' : x = 0), hx.ne' hx' }, refine strict_concave_on_open_of_deriv2_neg (convex_Ioi 0) is_open_Ioi (differentiable_on_log.mono h₁) (Ξ» x (hx : 0 < x), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne'), end lemma strict_concave_on_log_Iio : strict_concave_on ℝ (Iio 0) log := begin have h₁ : Iio 0 βŠ† ({0} : set ℝ)ᢜ, { exact Ξ» x (hx : x < 0) (hx' : x = 0), hx.ne hx' }, refine strict_concave_on_open_of_deriv2_neg (convex_Iio 0) is_open_Iio (differentiable_on_log.mono h₁) (Ξ» x (hx : x < 0), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne), end open_locale real lemma strict_concave_on_sin_Icc : strict_concave_on ℝ (Icc 0 Ο€) sin := begin apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_sin differentiable_sin.differentiable_on (Ξ» x hx, _), rw interior_Icc at hx, simp [sin_pos_of_mem_Ioo hx], end lemma strict_concave_on_cos_Icc : strict_concave_on ℝ (Icc (-(Ο€/2)) (Ο€/2)) cos := begin apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_cos differentiable_cos.differentiable_on (Ξ» x hx, _), rw interior_Icc at hx, simp [cos_pos_of_mem_Ioo hx], end
98251fc2c07a2f8ee6f884dcdf1bfc0f60522c28
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/computability/language.lean
2a2f1e673acfd4a8a9803a23f2e7cfd49b890124
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,855
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import algebra.hom.ring import data.list.join import data.set.lattice /-! # Languages This file contains the definition and operations on formal languages over an alphabet. Note strings are implemented as lists over the alphabet. The operations in this file define a [Kleene algebra](https://en.wikipedia.org/wiki/Kleene_algebra) over the languages. -/ open list set universes v variables {Ξ± Ξ² Ξ³ : Type*} /-- A language is a set of strings over an alphabet. -/ @[derive [has_mem (list Ξ±), has_singleton (list Ξ±), has_insert (list Ξ±), complete_boolean_algebra]] def language (Ξ±) := set (list Ξ±) namespace language variables {l m : language Ξ±} {a b x : list Ξ±} local attribute [reducible] language /-- Zero language has no elements. -/ instance : has_zero (language Ξ±) := ⟨(βˆ… : set _)⟩ /-- `1 : language Ξ±` contains only one element `[]`. -/ instance : has_one (language Ξ±) := ⟨{[]}⟩ instance : inhabited (language Ξ±) := ⟨0⟩ /-- The sum of two languages is their union. -/ instance : has_add (language Ξ±) := ⟨(βˆͺ)⟩ /-- The product of two languages `l` and `m` is the language made of the strings `x ++ y` where `x ∈ l` and `y ∈ m`. -/ instance : has_mul (language Ξ±) := ⟨image2 (++)⟩ lemma zero_def : (0 : language Ξ±) = (βˆ… : set _) := rfl lemma one_def : (1 : language Ξ±) = {[]} := rfl lemma add_def (l m : language Ξ±) : l + m = l βˆͺ m := rfl lemma mul_def (l m : language Ξ±) : l * m = image2 (++) l m := rfl /-- The star of a language `L` is the set of all strings which can be written by concatenating strings from `L`. -/ def star (l : language Ξ±) : language Ξ± := { x | βˆƒ S : list (list Ξ±), x = S.join ∧ βˆ€ y ∈ S, y ∈ l} lemma star_def (l : language Ξ±) : l.star = { x | βˆƒ S : list (list Ξ±), x = S.join ∧ βˆ€ y ∈ S, y ∈ l} := rfl @[simp] lemma not_mem_zero (x : list Ξ±) : x βˆ‰ (0 : language Ξ±) := id @[simp] lemma mem_one (x : list Ξ±) : x ∈ (1 : language Ξ±) ↔ x = [] := by refl lemma nil_mem_one : [] ∈ (1 : language Ξ±) := set.mem_singleton _ @[simp] lemma mem_add (l m : language Ξ±) (x : list Ξ±) : x ∈ l + m ↔ x ∈ l ∨ x ∈ m := iff.rfl lemma mem_mul : x ∈ l * m ↔ βˆƒ a b, a ∈ l ∧ b ∈ m ∧ a ++ b = x := mem_image2 lemma append_mem_mul : a ∈ l β†’ b ∈ m β†’ a ++ b ∈ l * m := mem_image2_of_mem lemma mem_star : x ∈ l.star ↔ βˆƒ S : list (list Ξ±), x = S.join ∧ βˆ€ y ∈ S, y ∈ l := iff.rfl lemma join_mem_star {S : list (list Ξ±)} (h : βˆ€ y ∈ S, y ∈ l) : S.join ∈ l.star := ⟨S, rfl, h⟩ lemma nil_mem_star (l : language Ξ±) : [] ∈ l.star := ⟨[], rfl, Ξ» _, false.elim⟩ instance : semiring (language Ξ±) := { add := (+), add_assoc := union_assoc, zero := 0, zero_add := empty_union, add_zero := union_empty, add_comm := union_comm, mul := (*), mul_assoc := Ξ» _ _ _, image2_assoc append_assoc, zero_mul := Ξ» _, image2_empty_left, mul_zero := Ξ» _, image2_empty_right, one := 1, one_mul := Ξ» l, by simp [mul_def, one_def], mul_one := Ξ» l, by simp [mul_def, one_def], nat_cast := Ξ» n, if n = 0 then 0 else 1, nat_cast_zero := rfl, nat_cast_succ := Ξ» n, by cases n; simp [nat.cast, add_def, zero_def], left_distrib := Ξ» _ _ _, image2_union_right, right_distrib := Ξ» _ _ _, image2_union_left } @[simp] lemma add_self (l : language Ξ±) : l + l = l := sup_idem /-- Maps the alphabet of a language. -/ def map (f : Ξ± β†’ Ξ²) : language Ξ± β†’+* language Ξ² := { to_fun := image (list.map f), map_zero' := image_empty _, map_one' := image_singleton, map_add' := image_union _, map_mul' := Ξ» _ _, image_image2_distrib $ map_append _ } @[simp] lemma map_id (l : language Ξ±) : map id l = l := by simp [map] @[simp] lemma map_map (g : Ξ² β†’ Ξ³) (f : Ξ± β†’ Ξ²) (l : language Ξ±) : map g (map f l) = map (g ∘ f) l := by simp [map, image_image] lemma star_def_nonempty (l : language Ξ±) : l.star = {x | βˆƒ S : list (list Ξ±), x = S.join ∧ βˆ€ y ∈ S, y ∈ l ∧ y β‰  []} := begin ext x, split, { rintro ⟨S, rfl, h⟩, refine ⟨S.filter (Ξ» l, Β¬list.empty l), by simp, Ξ» y hy, _⟩, rw [mem_filter, empty_iff_eq_nil] at hy, exact ⟨h y hy.1, hy.2⟩ }, { rintro ⟨S, hx, h⟩, exact ⟨S, hx, Ξ» y hy, (h y hy).1⟩ } end lemma le_iff (l m : language Ξ±) : l ≀ m ↔ l + m = m := sup_eq_right.symm lemma le_mul_congr {l₁ lβ‚‚ m₁ mβ‚‚ : language Ξ±} : l₁ ≀ m₁ β†’ lβ‚‚ ≀ mβ‚‚ β†’ l₁ * lβ‚‚ ≀ m₁ * mβ‚‚ := begin intros h₁ hβ‚‚ x hx, simp only [mul_def, exists_and_distrib_left, mem_image2, image_prod] at hx ⊒, tauto end lemma le_add_congr {l₁ lβ‚‚ m₁ mβ‚‚ : language Ξ±} : l₁ ≀ m₁ β†’ lβ‚‚ ≀ mβ‚‚ β†’ l₁ + lβ‚‚ ≀ m₁ + mβ‚‚ := sup_le_sup lemma mem_supr {ΞΉ : Sort v} {l : ΞΉ β†’ language Ξ±} {x : list Ξ±} : x ∈ (⨆ i, l i) ↔ βˆƒ i, x ∈ l i := mem_Union lemma supr_mul {ΞΉ : Sort v} (l : ΞΉ β†’ language Ξ±) (m : language Ξ±) : (⨆ i, l i) * m = ⨆ i, l i * m := image2_Union_left _ _ _ lemma mul_supr {ΞΉ : Sort v} (l : ΞΉ β†’ language Ξ±) (m : language Ξ±) : m * (⨆ i, l i) = ⨆ i, m * l i := image2_Union_right _ _ _ lemma supr_add {ΞΉ : Sort v} [nonempty ΞΉ] (l : ΞΉ β†’ language Ξ±) (m : language Ξ±) : (⨆ i, l i) + m = ⨆ i, l i + m := supr_sup lemma add_supr {ΞΉ : Sort v} [nonempty ΞΉ] (l : ΞΉ β†’ language Ξ±) (m : language Ξ±) : m + (⨆ i, l i) = ⨆ i, m + l i := sup_supr lemma mem_pow {l : language Ξ±} {x : list Ξ±} {n : β„•} : x ∈ l ^ n ↔ βˆƒ S : list (list Ξ±), x = S.join ∧ S.length = n ∧ βˆ€ y ∈ S, y ∈ l := begin induction n with n ihn generalizing x, { simp only [mem_one, pow_zero, length_eq_zero], split, { rintro rfl, exact ⟨[], rfl, rfl, Ξ» y h, h.elim⟩ }, { rintro ⟨_, rfl, rfl, _⟩, refl } }, { simp only [pow_succ, mem_mul, ihn], split, { rintro ⟨a, b, ha, ⟨S, rfl, rfl, hS⟩, rfl⟩, exact ⟨a :: S, rfl, rfl, forall_mem_cons.2 ⟨ha, hS⟩⟩ }, { rintro ⟨_|⟨a, S⟩, rfl, hn, hS⟩; cases hn, rw forall_mem_cons at hS, exact ⟨a, _, hS.1, ⟨S, rfl, rfl, hS.2⟩, rfl⟩ } } end lemma star_eq_supr_pow (l : language Ξ±) : l.star = ⨆ i : β„•, l ^ i := begin ext x, simp only [mem_star, mem_supr, mem_pow], split, { rintro ⟨S, rfl, hS⟩, exact ⟨_, S, rfl, rfl, hS⟩ }, { rintro ⟨_, S, rfl, rfl, hS⟩, exact ⟨S, rfl, hS⟩ } end @[simp] lemma map_star (f : Ξ± β†’ Ξ²) (l : language Ξ±) : map f (star l) = star (map f l) := begin rw [star_eq_supr_pow, star_eq_supr_pow], simp_rw ←map_pow, exact image_Union, end lemma mul_self_star_comm (l : language Ξ±) : l.star * l = l * l.star := by simp only [star_eq_supr_pow, mul_supr, supr_mul, ← pow_succ, ← pow_succ'] @[simp] lemma one_add_self_mul_star_eq_star (l : language Ξ±) : 1 + l * l.star = l.star := begin simp only [star_eq_supr_pow, mul_supr, ← pow_succ, ← pow_zero l], exact sup_supr_nat_succ _ end @[simp] lemma one_add_star_mul_self_eq_star (l : language Ξ±) : 1 + l.star * l = l.star := by rw [mul_self_star_comm, one_add_self_mul_star_eq_star] lemma star_mul_le_right_of_mul_le_right (l m : language Ξ±) : l * m ≀ m β†’ l.star * m ≀ m := begin intro h, rw [star_eq_supr_pow, supr_mul], refine supr_le _, intro n, induction n with n ih, { simp }, rw [pow_succ', mul_assoc (l^n) l m], exact le_trans (le_mul_congr le_rfl h) ih, end lemma star_mul_le_left_of_mul_le_left (l m : language Ξ±) : m * l ≀ m β†’ m * l.star ≀ m := begin intro h, rw [star_eq_supr_pow, mul_supr], refine supr_le _, intro n, induction n with n ih, { simp }, rw [pow_succ, ←mul_assoc m l (l^n)], exact le_trans (le_mul_congr h le_rfl) ih end end language
a666c092c6af454788d83a5f8335e2fe0f160346
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/field_theory/normal.lean
23ffeba7e77bdb4d36a93a7a12f60371abae9cd5
[ "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
15,248
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Thomas Browning, Patrick Lutz -/ import field_theory.adjoin import field_theory.tower import group_theory.solvable import ring_theory.power_basis /-! # Normal field extensions In this file we define normal field extensions and prove that for a finite extension, being normal is the same as being a splitting field (`normal.of_is_splitting_field` and `normal.exists_is_splitting_field`). ## Main Definitions - `normal F K` where `K` is a field extension of `F`. -/ noncomputable theory open_locale classical open polynomial is_scalar_tower variables (F K : Type*) [field F] [field K] [algebra F K] --TODO(Commelin): refactor normal to extend `is_algebraic`?? /-- Typeclass for normal field extension: `K` is a normal extension of `F` iff the minimal polynomial of every element `x` in `K` splits in `K`, i.e. every conjugate of `x` is in `K`. -/ class normal : Prop := (is_integral' (x : K) : is_integral F x) (splits' (x : K) : splits (algebra_map F K) (minpoly F x)) variables {F K} theorem normal.is_integral (h : normal F K) (x : K) : is_integral F x := normal.is_integral' x theorem normal.splits (h : normal F K) (x : K) : splits (algebra_map F K) (minpoly F x) := normal.splits' x theorem normal_iff : normal F K ↔ βˆ€ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := ⟨λ h x, ⟨h.is_integral x, h.splits x⟩, Ξ» h, ⟨λ x, (h x).1, Ξ» x, (h x).2⟩⟩ theorem normal.out : normal F K β†’ βˆ€ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := normal_iff.1 variables (F K) instance normal_self : normal F F := ⟨λ x, is_integral_algebra_map, Ξ» x, by { rw minpoly.eq_X_sub_C', exact splits_X_sub_C _ }⟩ variables {K} variables (K) theorem normal.exists_is_splitting_field [h : normal F K] [finite_dimensional F K] : βˆƒ p : polynomial F, is_splitting_field F K p := begin obtain ⟨s, hs⟩ := finite_dimensional.exists_is_basis_finset F K, refine ⟨s.prod $ Ξ» x, minpoly F x, splits_prod _ $ Ξ» x hx, h.splits x, subalgebra.to_submodule_injective _⟩, rw [algebra.coe_top, eq_top_iff, ← hs.2, submodule.span_le, set.range_subset_iff], refine Ξ» x, algebra.subset_adjoin (multiset.mem_to_finset.mpr $ (mem_roots $ mt (map_eq_zero $ algebra_map F K).1 $ finset.prod_ne_zero_iff.2 $ Ξ» x hx, _).2 _), { exact minpoly.ne_zero (h.is_integral x) }, rw [is_root.def, eval_map, ← aeval_def, alg_hom.map_prod], exact finset.prod_eq_zero x.2 (minpoly.aeval _ _) end section normal_tower variables (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma normal.tower_top_of_normal [h : normal F E] : normal K E := normal_iff.2 $ Ξ» x, begin cases h.out x with hx hhx, rw algebra_map_eq F K E at hhx, exact ⟨is_integral_of_is_scalar_tower x hx, polynomial.splits_of_splits_of_dvd (algebra_map K E) (polynomial.map_ne_zero (minpoly.ne_zero hx)) ((polynomial.splits_map_iff (algebra_map F K) (algebra_map K E)).mpr hhx) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩, end lemma alg_hom.normal_bijective [h : normal F E] (Ο• : E →ₐ[F] K) : function.bijective Ο• := βŸ¨Ο•.to_ring_hom.injective, Ξ» x, by { letI : algebra E K := Ο•.to_ring_hom.to_algebra, obtain ⟨h1, h2⟩ := h.out (algebra_map K E x), cases minpoly.mem_range_of_degree_eq_one E x (or.resolve_left h2 (minpoly.ne_zero h1) (minpoly.irreducible (is_integral_of_is_scalar_tower x ((is_integral_algebra_map_iff (algebra_map K E).injective).mp h1))) (minpoly.dvd E x ((algebra_map K E).injective (by { rw [ring_hom.map_zero, aeval_map, ←is_scalar_tower.to_alg_hom_apply F K E, ←alg_hom.comp_apply, ←aeval_alg_hom], exact minpoly.aeval F (algebra_map K E x) })))) with y hy, exact ⟨y, hy.2⟩ }⟩ variables {F} {E} {E' : Type*} [field E'] [algebra F E'] lemma normal.of_alg_equiv [h : normal F E] (f : E ≃ₐ[F] E') : normal F E' := normal_iff.2 $ Ξ» x, begin cases h.out (f.symm x) with hx hhx, have H := is_integral_alg_hom f.to_alg_hom hx, rw [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_equiv.apply_symm_apply] at H, use H, apply polynomial.splits_of_splits_of_dvd (algebra_map F E') (minpoly.ne_zero hx), { rw ← alg_hom.comp_algebra_map f.to_alg_hom, exact polynomial.splits_comp_of_splits (algebra_map F E) f.to_alg_hom.to_ring_hom hhx }, { apply minpoly.dvd _ _, rw ← add_equiv.map_eq_zero_iff f.symm.to_add_equiv, exact eq.trans (polynomial.aeval_alg_hom_apply f.symm.to_alg_hom x (minpoly F (f.symm x))).symm (minpoly.aeval _ _) }, end lemma alg_equiv.transfer_normal (f : E ≃ₐ[F] E') : normal F E ↔ normal F E' := ⟨λ h, by exactI normal.of_alg_equiv f, Ξ» h, by exactI normal.of_alg_equiv f.symm⟩ lemma normal.of_is_splitting_field (p : polynomial F) [hFEp : is_splitting_field F E p] : normal F E := begin by_cases hp : p = 0, { haveI : is_splitting_field F F p := by { rw hp, exact ⟨splits_zero _, subsingleton.elim _ _⟩ }, exactI (alg_equiv.transfer_normal ((is_splitting_field.alg_equiv F p).trans (is_splitting_field.alg_equiv E p).symm)).mp (normal_self F) }, refine normal_iff.2 (Ξ» x, _), haveI hFE : finite_dimensional F E := is_splitting_field.finite_dimensional E p, have Hx : is_integral F x := is_integral_of_noetherian hFE x, refine ⟨Hx, or.inr _⟩, rintros q q_irred ⟨r, hr⟩, let D := adjoin_root q, let pbED := adjoin_root.power_basis q_irred.ne_zero, haveI : finite_dimensional E D := power_basis.finite_dimensional pbED, have findimED : finite_dimensional.findim E D = q.nat_degree := power_basis.findim pbED, letI : algebra F D := ring_hom.to_algebra ((algebra_map E D).comp (algebra_map F E)), haveI : is_scalar_tower F E D := of_algebra_map_eq (Ξ» _, rfl), haveI : finite_dimensional F D := finite_dimensional.trans F E D, suffices : nonempty (D →ₐ[F] E), { cases this with Ο•, rw [←with_bot.coe_one, degree_eq_iff_nat_degree_eq q_irred.ne_zero, ←findimED], have nat_lemma : βˆ€ a b c : β„•, a * b = c β†’ c ≀ a β†’ 0 < c β†’ b = 1, { intros a b c h1 h2 h3, nlinarith }, exact nat_lemma _ _ _ (finite_dimensional.findim_mul_findim F E D) (linear_map.findim_le_findim_of_injective (show function.injective Ο•.to_linear_map, from Ο•.to_ring_hom.injective)) finite_dimensional.findim_pos, }, let C := adjoin_root (minpoly F x), have Hx_irred := minpoly.irreducible Hx, letI : algebra C D := ring_hom.to_algebra (adjoin_root.lift (algebra_map F D) (adjoin_root.root q) (by rw [algebra_map_eq F E D, ←evalβ‚‚_map, hr, adjoin_root.algebra_map_eq, evalβ‚‚_mul, adjoin_root.evalβ‚‚_root, zero_mul])), letI : algebra C E := ring_hom.to_algebra (adjoin_root.lift (algebra_map F E) x (minpoly.aeval F x)), haveI : is_scalar_tower F C D := of_algebra_map_eq (Ξ» x, adjoin_root.lift_of.symm), haveI : is_scalar_tower F C E := of_algebra_map_eq (Ξ» x, adjoin_root.lift_of.symm), suffices : nonempty (D →ₐ[C] E), { exact nonempty.map (alg_hom.restrict_scalars F) this }, let S : set D := ((p.map (algebra_map F E)).roots.map (algebra_map E D)).to_finset, suffices : ⊀ ≀ intermediate_field.adjoin C S, { refine intermediate_field.alg_hom_mk_adjoin_splits' (top_le_iff.mp this) (Ξ» y hy, _), rcases multiset.mem_map.mp (multiset.mem_to_finset.mp hy) with ⟨z, hz1, hz2⟩, have Hz : is_integral F z := is_integral_of_noetherian hFE z, use (show is_integral C y, from is_integral_of_noetherian (finite_dimensional.right F C D) y), apply splits_of_splits_of_dvd (algebra_map C E) (map_ne_zero (minpoly.ne_zero Hz)), { rw [splits_map_iff, ←algebra_map_eq F C E], exact splits_of_splits_of_dvd _ hp hFEp.splits (minpoly.dvd F z (eq.trans (evalβ‚‚_eq_eval_map _) ((mem_roots (map_ne_zero hp)).mp hz1))) }, { apply minpoly.dvd, rw [←hz2, aeval_def, evalβ‚‚_map, ←algebra_map_eq F C D, algebra_map_eq F E D, ←hom_evalβ‚‚, ←aeval_def, minpoly.aeval F z, ring_hom.map_zero] } }, rw [←intermediate_field.to_subalgebra_le_to_subalgebra, intermediate_field.top_to_subalgebra], apply ge_trans (intermediate_field.algebra_adjoin_le_adjoin C S), suffices : (algebra.adjoin C S).res F = (algebra.adjoin E {adjoin_root.root q}).res F, { rw [adjoin_root.adjoin_root_eq_top, subalgebra.res_top, ←@subalgebra.res_top F C] at this, exact top_le_iff.mpr (subalgebra.res_inj F this) }, dsimp only [S], rw [←finset.image_to_finset, finset.coe_image], apply eq.trans (algebra.adjoin_res_eq_adjoin_res F E C D hFEp.adjoin_roots adjoin_root.adjoin_root_eq_top), rw [set.image_singleton, ring_hom.algebra_map_to_algebra, adjoin_root.lift_root] end instance (p : polynomial F) : normal F p.splitting_field := normal.of_is_splitting_field p end normal_tower variables {F} {K} (Ο• ψ : K →ₐ[F] K) (Ο‡ Ο‰ : K ≃ₐ[F] K) section restrict variables (E : Type*) [field E] [algebra F E] [algebra E K] [is_scalar_tower F E K] /-- Restrict algebra homomorphism to image of normal subfield -/ def alg_hom.restrict_normal_aux [h : normal F E] : (to_alg_hom F E K).range →ₐ[F] (to_alg_hom F E K).range := { to_fun := Ξ» x, βŸ¨Ο• x, by { suffices : (to_alg_hom F E K).range.map Ο• ≀ _, { exact this ⟨x, subtype.mem x, rfl⟩ }, rintros x ⟨y, ⟨z, -, hy⟩, hx⟩, rw [←hx, ←hy], apply minpoly.mem_range_of_degree_eq_one E, exact or.resolve_left (h.splits z) (minpoly.ne_zero (h.is_integral z)) (minpoly.irreducible $ is_integral_of_is_scalar_tower _ $ is_integral_alg_hom Ο• $ is_integral_alg_hom _ $ h.is_integral z) (minpoly.dvd E _ $ by rw [aeval_map, aeval_alg_hom, aeval_alg_hom, alg_hom.comp_apply, alg_hom.comp_apply, minpoly.aeval, alg_hom.map_zero, alg_hom.map_zero]) }⟩, map_zero' := subtype.ext Ο•.map_zero, map_one' := subtype.ext Ο•.map_one, map_add' := Ξ» x y, subtype.ext (Ο•.map_add x y), map_mul' := Ξ» x y, subtype.ext (Ο•.map_mul x y), commutes' := Ξ» x, subtype.ext (Ο•.commutes x) } /-- Restrict algebra homomorphism to normal subfield -/ def alg_hom.restrict_normal [normal F E] : E →ₐ[F] E := ((alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).symm.to_alg_hom.comp (Ο•.restrict_normal_aux E)).comp (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).to_alg_hom @[simp] lemma alg_hom.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (Ο•.restrict_normal E x) = Ο• (algebra_map E K x) := subtype.ext_iff.mp (alg_equiv.apply_symm_apply (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)) (Ο•.restrict_normal_aux E ⟨is_scalar_tower.to_alg_hom F E K x, ⟨x, ⟨subsemiring.mem_top x, rfl⟩⟩⟩)) lemma alg_hom.restrict_normal_comp [normal F E] : (Ο•.restrict_normal E).comp (ψ.restrict_normal E) = (Ο•.comp ψ).restrict_normal E := alg_hom.ext (Ξ» _, (algebra_map E K).injective (by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes])) /-- Restrict algebra isomorphism to a normal subfield -/ def alg_equiv.restrict_normal [h : normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (Ο‡.to_alg_hom.restrict_normal E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_equiv.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (Ο‡.restrict_normal E x) = Ο‡ (algebra_map E K x) := Ο‡.to_alg_hom.restrict_normal_commutes E x lemma alg_equiv.restrict_normal_trans [normal F E] : (Ο‡.trans Ο‰).restrict_normal E = (Ο‡.restrict_normal E).trans (Ο‰.restrict_normal E) := alg_equiv.ext (Ξ» _, (algebra_map E K).injective (by simp only [alg_equiv.trans_apply, alg_equiv.restrict_normal_commutes])) /-- Restriction to an normal subfield as a group homomorphism -/ def alg_equiv.restrict_normal_hom [normal F E] : (K ≃ₐ[F] K) β†’* (E ≃ₐ[F] E) := monoid_hom.mk' (Ξ» Ο‡, Ο‡.restrict_normal E) (Ξ» Ο‰ Ο‡, (Ο‡.restrict_normal_trans Ο‰ E)) end restrict section lift variables {F} {K} (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] /-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift an algebra homomorphism `Ο• : K →ₐ[F] K` to `Ο•.lift_normal E : E →ₐ[F] E`. -/ noncomputable def alg_hom.lift_normal [h : normal F E] : E →ₐ[F] E := @alg_hom.restrict_scalars F K E E _ _ _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp Ο•).to_ring_hom.to_algebra _ _ _ _ (nonempty.some (@intermediate_field.alg_hom_mk_adjoin_splits' K E E _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp Ο•).to_ring_hom.to_algebra ⊀ rfl (Ξ» x hx, ⟨is_integral_of_is_scalar_tower x (h.out x).1, splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero (h.out x).1)) (by { rw [splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact (h.out x).2 }) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩))) @[simp] lemma alg_hom.lift_normal_commutes [normal F E] (x : K) : Ο•.lift_normal E (algebra_map K E x) = algebra_map K E (Ο• x) := @alg_hom.commutes K E E _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp Ο•).to_ring_hom.to_algebra _ x @[simp] lemma alg_hom.restrict_lift_normal [normal F K] [normal F E] : (Ο•.lift_normal E).restrict_normal K = Ο• := alg_hom.ext (Ξ» x, (algebra_map K E).injective (eq.trans (alg_hom.restrict_normal_commutes _ K x) (Ο•.lift_normal_commutes E x))) /-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift an algebra isomorphism `Ο• : K ≃ₐ[F] K` to `Ο•.lift_normal E : E ≃ₐ[F] E`. -/ noncomputable def alg_equiv.lift_normal [normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (Ο‡.to_alg_hom.lift_normal E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_equiv.lift_normal_commutes [normal F E] (x : K) : Ο‡.lift_normal E (algebra_map K E x) = algebra_map K E (Ο‡ x) := Ο‡.to_alg_hom.lift_normal_commutes E x @[simp] lemma alg_equiv.restrict_lift_normal [normal F K] [normal F E] : (Ο‡.lift_normal E).restrict_normal K = Ο‡ := alg_equiv.ext (Ξ» x, (algebra_map K E).injective (eq.trans (alg_equiv.restrict_normal_commutes _ K x) (Ο‡.lift_normal_commutes E x))) lemma alg_equiv.restrict_normal_hom_surjective [normal F K] [normal F E] : function.surjective (alg_equiv.restrict_normal_hom K : (E ≃ₐ[F] E) β†’ (K ≃ₐ[F] K)) := Ξ» Ο‡, βŸ¨Ο‡.lift_normal E, Ο‡.restrict_lift_normal E⟩ variables (F) (K) (E) lemma is_solvable_of_is_scalar_tower [normal F K] [h1 : is_solvable (K ≃ₐ[F] K)] [h2 : is_solvable (E ≃ₐ[K] E)] : is_solvable (E ≃ₐ[F] E) := begin let f : (E ≃ₐ[K] E) β†’* (E ≃ₐ[F] E) := { to_fun := Ξ» Ο•, alg_equiv.of_alg_hom (Ο•.to_alg_hom.restrict_scalars F) (Ο•.symm.to_alg_hom.restrict_scalars F) (alg_hom.ext (Ξ» x, Ο•.apply_symm_apply x)) (alg_hom.ext (Ξ» x, Ο•.symm_apply_apply x)), map_one' := alg_equiv.ext (Ξ» _, rfl), map_mul' := Ξ» _ _, alg_equiv.ext (Ξ» _, rfl) }, refine solvable_of_ker_le_range f (alg_equiv.restrict_normal_hom K) (Ξ» Ο• hΟ•, ⟨{commutes' := Ξ» x, _, .. Ο•}, alg_equiv.ext (Ξ» _, rfl)⟩), exact (eq.trans (Ο•.restrict_normal_commutes K x).symm (congr_arg _ (alg_equiv.ext_iff.mp hΟ• x))), end end lift
f2a85388753fc0f71a7e59afbbdb5c1d87070f64
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/localization/away.lean
0ea25713791ebb4034ca9297bf25e1aab944a718
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
13,064
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.adjoin_root import ring_theory.localization.basic /-! # Localizations away from an element ## Main definitions * `is_localization.away (x : R) S` expresses that `S` is a localization away from `x`, as an abbreviation of `is_localization (submonoid.powers x) S` * `exists_reduced_fraction (hb : b β‰  0)` produces a reduced fraction of the form `b = a * x^n` for some `n : β„€` and some `a : R` that is not divisible by `x`. ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ section comm_semiring variables {R : Type*} [comm_semiring R] (M : submonoid R) {S : Type*} [comm_semiring S] variables [algebra R S] {P : Type*} [comm_semiring P] namespace is_localization section away variables (x : R) /-- Given `x : R`, the typeclass `is_localization.away x S` states that `S` is isomorphic to the localization of `R` at the submonoid generated by `x`. -/ abbreviation away (S : Type*) [comm_semiring S] [algebra R S] := is_localization (submonoid.powers x) S namespace away variables [is_localization.away x S] /-- Given `x : R` and a localization map `F : R β†’+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def inv_self : S := mk' S (1 : R) ⟨x, submonoid.mem_powers _⟩ @[simp] lemma mul_inv_self : algebra_map R S x * inv_self x = 1 := by { convert is_localization.mk'_mul_mk'_eq_one _ 1, symmetry, apply is_localization.mk'_one } variables {g : R β†’+* P} /-- Given `x : R`, a localization map `F : R β†’+* S` away from `x`, and a map of `comm_semiring`s `g : R β†’+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending `z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : β„•` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def lift (hg : is_unit (g x)) : S β†’+* P := is_localization.lift $ Ξ» (y : submonoid.powers x), show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (pow_monoid_hom n : P β†’* P) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) : lift x hg ((algebra_map R S) a) = g a := lift_eq _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (lift x hg).comp (algebra_map R S) = g := lift_comp _ /-- Given `x y : R` and localizations `S`, `P` away from `x` and `x * y` respectively, the homomorphism induced from `S` to `P`. -/ noncomputable def away_to_away_right (y : R) [algebra R P] [is_localization.away (x * y) P] : S β†’+* P := lift x $ show is_unit ((algebra_map R P) x), from is_unit_of_mul_eq_one ((algebra_map R P) x) (mk' P y ⟨x * y, submonoid.mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] variables (S) (Q : Type*) [comm_semiring Q] [algebra P Q] /-- Given a map `f : R β†’+* S` and an element `r : R`, we may construct a map `Rα΅£ β†’+* Sα΅£`. -/ noncomputable def map (f : R β†’+* P) (r : R) [is_localization.away r S] [is_localization.away (f r) Q] : S β†’+* Q := is_localization.map Q f (show submonoid.powers r ≀ (submonoid.powers (f r)).comap f, by { rintros x ⟨n, rfl⟩, use n, simp }) end away end away variables [is_localization M S] section at_units variables (R) (S) (M) /-- The localization at a module of units is isomorphic to the ring -/ noncomputable def at_units (H : βˆ€ x : M, is_unit (x : R)) : R ≃ₐ[R] S := begin refine alg_equiv.of_bijective (algebra.of_id R S) ⟨_, _⟩, { intros x y hxy, obtain ⟨c, eq⟩ := (is_localization.eq_iff_exists M S).mp hxy, obtain ⟨u, hu⟩ := H c, rwa [← hu, units.mul_right_inj] at eq }, { intros y, obtain ⟨⟨x, s⟩, eq⟩ := is_localization.surj M y, obtain ⟨u, hu⟩ := H s, use x * u.inv, dsimp only [algebra.of_id, ring_hom.to_fun_eq_coe, alg_hom.coe_mk], rw [ring_hom.map_mul, ← eq, ← hu, mul_assoc, ← ring_hom.map_mul], simp } end /-- The localization away from a unit is isomorphic to the ring -/ noncomputable def at_unit (x : R) (e : is_unit x) [is_localization.away x S] : R ≃ₐ[R] S := begin apply at_units R (submonoid.powers x), rintros ⟨xn, n, hxn⟩, obtain ⟨u, hu⟩ := e, rw is_unit_iff_exists_inv, use u.inv ^ n, simp[← hxn, ← hu, ← mul_pow] end /-- The localization at one is isomorphic to the ring. -/ noncomputable def at_one [is_localization.away (1 : R) S] : R ≃ₐ[R] S := @at_unit R _ S _ _ (1 : R) is_unit_one _ lemma away_of_is_unit_of_bijective {R : Type*} (S : Type*) [comm_ring R] [comm_ring S] [algebra R S] {r : R} (hr : is_unit r) (H : function.bijective (algebra_map R S)) : is_localization.away r S := { map_units := by { rintros ⟨_, n, rfl⟩, exact (algebra_map R S).is_unit_map (hr.pow _) }, surj := Ξ» z, by { obtain ⟨z', rfl⟩ := H.2 z, exact ⟨⟨z', 1⟩, by simp⟩ }, eq_iff_exists := Ξ» x y, begin erw H.1.eq_iff, split, { rintro rfl, exact ⟨1, rfl⟩ }, { rintro ⟨⟨_, n, rfl⟩, e⟩, exact (hr.pow _).mul_right_inj.mp e } end } end at_units end is_localization namespace localization open is_localization variables {M} /-- Given a map `f : R β†’+* S` and an element `r : R`, such that `f r` is invertible, we may construct a map `Rα΅£ β†’+* S`. -/ noncomputable abbreviation away_lift (f : R β†’+* P) (r : R) (hr : is_unit (f r)) : localization.away r β†’+* P := is_localization.away.lift r hr /-- Given a map `f : R β†’+* S` and an element `r : R`, we may construct a map `Rα΅£ β†’+* Sα΅£`. -/ noncomputable abbreviation away_map (f : R β†’+* P) (r : R) : localization.away r β†’+* localization.away (f r) := is_localization.away.map _ _ f r end localization end comm_semiring open polynomial adjoin_root localization variables {R : Type*} [comm_ring R] local attribute [instance] is_localization.alg_hom_subsingleton adjoin_root.alg_hom_subsingleton /-- The `R`-`alg_equiv` between the localization of `R` away from `r` and `R` with an inverse of `r` adjoined. -/ noncomputable def localization.away_equiv_adjoin (r : R) : away r ≃ₐ[R] adjoin_root (C r * X - 1) := alg_equiv.of_alg_hom { commutes' := is_localization.away.away_map.lift_eq r (is_unit_of_mul_eq_one _ _ $ root_is_inv r), .. away_lift _ r _ } (lift_hom _ (is_localization.away.inv_self r) $ by simp only [map_sub, map_mul, aeval_C, aeval_X, is_localization.away.mul_inv_self, aeval_one, sub_self]) (subsingleton.elim _ _) (subsingleton.elim _ _) lemma is_localization.adjoin_inv (r : R) : is_localization.away r (adjoin_root $ C r * X - 1) := is_localization.is_localization_of_alg_equiv _ (localization.away_equiv_adjoin r) lemma is_localization.away.finite_presentation (r : R) {S} [comm_ring S] [algebra R S] [is_localization.away r S] : algebra.finite_presentation R S := (adjoin_root.finite_presentation _).equiv $ (localization.away_equiv_adjoin r).symm.trans $ is_localization.alg_equiv (submonoid.powers r) _ _ section num_denom open multiplicity unique_factorization_monoid is_localization variable (x : R) variables (B : Type*) [comm_ring B] [algebra R B] [is_localization.away x B] /-- `self_zpow x (m : β„€)` is `x ^ m` as an element of the localization away from `x`. -/ noncomputable def self_zpow (m : β„€) : B := if hm : 0 ≀ m then algebra_map _ _ x ^ m.nat_abs else mk' _ (1 : R) (submonoid.pow x m.nat_abs) lemma self_zpow_of_nonneg {n : β„€} (hn : 0 ≀ n) : self_zpow x B n = algebra_map R B x ^ n.nat_abs := dif_pos hn @[simp] lemma self_zpow_coe_nat (d : β„•) : self_zpow x B d = (algebra_map R B x)^d := self_zpow_of_nonneg _ _ (int.coe_nat_nonneg d) @[simp] lemma self_zpow_zero : self_zpow x B 0 = 1 := by simp [self_zpow_of_nonneg _ _ le_rfl] lemma self_zpow_of_neg {n : β„€} (hn : n < 0) : self_zpow x B n = mk' _ (1 : R) (submonoid.pow x n.nat_abs) := dif_neg hn.not_le lemma self_zpow_of_nonpos {n : β„€} (hn : n ≀ 0) : self_zpow x B n = mk' _ (1 : R) (submonoid.pow x n.nat_abs) := begin by_cases hn0 : n = 0, { simp [hn0, self_zpow_zero, submonoid.pow_apply] }, { simp [self_zpow_of_neg _ _ (lt_of_le_of_ne hn hn0)] } end @[simp] lemma self_zpow_neg_coe_nat (d : β„•) : self_zpow x B (-d) = mk' _ (1 : R) (submonoid.pow x d) := by simp [self_zpow_of_nonpos _ _ (neg_nonpos.mpr (int.coe_nat_nonneg d))] @[simp] lemma self_zpow_sub_cast_nat {n m : β„•} : self_zpow x B (n - m) = mk' _ (x ^ n) (submonoid.pow x m) := begin by_cases h : m ≀ n, { rw [is_localization.eq_mk'_iff_mul_eq, submonoid.pow_apply, subtype.coe_mk, ← int.coe_nat_sub h, self_zpow_coe_nat, ← map_pow, ← map_mul, ← pow_add, nat.sub_add_cancel h] }, { rw [← neg_sub, ← int.coe_nat_sub (le_of_not_le h), self_zpow_neg_coe_nat, is_localization.mk'_eq_iff_eq], simp [submonoid.pow_apply, ← pow_add, nat.sub_add_cancel (le_of_not_le h)] } end @[simp] lemma self_zpow_add {n m : β„€} : self_zpow x B (n + m) = self_zpow x B n * self_zpow x B m := begin cases le_or_lt 0 n with hn hn; cases le_or_lt 0 m with hm hm, { rw [self_zpow_of_nonneg _ _ hn, self_zpow_of_nonneg _ _ hm, self_zpow_of_nonneg _ _ (add_nonneg hn hm), int.nat_abs_add_nonneg hn hm, pow_add] }, { have : n + m = n.nat_abs - m.nat_abs, { rw [int.nat_abs_of_nonneg hn, int.of_nat_nat_abs_of_nonpos hm.le, sub_neg_eq_add] }, rw [self_zpow_of_nonneg _ _ hn, self_zpow_of_neg _ _ hm, this, self_zpow_sub_cast_nat, is_localization.mk'_eq_mul_mk'_one, map_pow] }, { have : n + m = m.nat_abs - n.nat_abs, { rw [int.nat_abs_of_nonneg hm, int.of_nat_nat_abs_of_nonpos hn.le, sub_neg_eq_add, add_comm] }, rw [self_zpow_of_nonneg _ _ hm, self_zpow_of_neg _ _ hn, this, self_zpow_sub_cast_nat, is_localization.mk'_eq_mul_mk'_one, map_pow, mul_comm] }, { rw [self_zpow_of_neg _ _ hn, self_zpow_of_neg _ _ hm, self_zpow_of_neg _ _ (add_neg hn hm), int.nat_abs_add_neg hn hm, ← mk'_mul, one_mul], congr, ext, simp [pow_add] }, end lemma self_zpow_mul_neg (d : β„€) : self_zpow x B d * self_zpow x B (-d) = 1 := begin by_cases hd : d ≀ 0, { erw [self_zpow_of_nonpos x B hd, self_zpow_of_nonneg, ← map_pow, int.nat_abs_neg, is_localization.mk'_spec, map_one], apply nonneg_of_neg_nonpos, rwa [neg_neg]}, { erw [self_zpow_of_nonneg x B (le_of_not_le hd), self_zpow_of_nonpos, ← map_pow, int.nat_abs_neg, @is_localization.mk'_spec' R _ (submonoid.powers x) B _ _ _ 1 (submonoid.pow x d.nat_abs), map_one], refine nonpos_of_neg_nonneg (le_of_lt _), rwa [neg_neg, ← not_le] }, end lemma self_zpow_neg_mul (d : β„€) : self_zpow x B (-d) * self_zpow x B d = 1 := by rw [mul_comm, self_zpow_mul_neg x B d] lemma self_zpow_pow_sub (a : R) (b : B) (m d : β„€) : (self_zpow x B (m - d)) * mk' B a (1 : submonoid.powers x) = b ↔ (self_zpow x B m) * mk' B a (1 : submonoid.powers x) = (self_zpow x B d) * b := begin rw [sub_eq_add_neg, self_zpow_add, mul_assoc, mul_comm _ (mk' B a 1), ← mul_assoc], split, { intro h, have := congr_arg (Ξ» s : B, s * self_zpow x B d) h, simp only at this, rwa [mul_assoc, mul_assoc, self_zpow_neg_mul, mul_one, mul_comm b _] at this}, { intro h, have := congr_arg (Ξ» s : B, s * self_zpow x B (-d)) h, simp only at this, rwa [mul_comm _ b, mul_assoc b _ _, self_zpow_mul_neg, mul_one] at this} end variables [is_domain R] [normalization_monoid R] [unique_factorization_monoid R] theorem exists_reduced_fraction' {b : B} (hb : b β‰  0) (hx : irreducible x) : βˆƒ (a : R) (n : β„€), Β¬ x ∣ a ∧ self_zpow x B n * algebra_map R B a = b := begin classical, obtain ⟨⟨aβ‚€, y⟩, H⟩ := surj (submonoid.powers x) b, obtain ⟨d, hy⟩ := (submonoid.mem_powers_iff y.1 x).mp y.2, have haβ‚€ : aβ‚€ β‰  0, { haveI := @is_domain_of_le_non_zero_divisors B _ R _ _ _ (submonoid.powers x) _ (powers_le_non_zero_divisors_of_no_zero_divisors hx.ne_zero), simp only [map_zero, ← subtype.val_eq_coe, ← hy, map_pow] at H, apply ((injective_iff_map_eq_zero' (algebra_map R B)).mp _ aβ‚€).mpr.mt, rw ← H, apply mul_ne_zero hb (pow_ne_zero _ _), exact is_localization.to_map_ne_zero_of_mem_non_zero_divisors B (powers_le_non_zero_divisors_of_no_zero_divisors (hx.ne_zero)) (mem_non_zero_divisors_iff_ne_zero.mpr hx.ne_zero), exact is_localization.injective B (powers_le_non_zero_divisors_of_no_zero_divisors (hx.ne_zero)) }, simp only [← subtype.val_eq_coe, ← hy] at H, obtain ⟨m, a, hyp1, hyp2⟩ := max_power_factor haβ‚€ hx, refine ⟨a, m-d, _⟩, rw [← mk'_one B, self_zpow_pow_sub, self_zpow_coe_nat, self_zpow_coe_nat, ← map_pow _ _ d, mul_comm _ b, H, hyp2, map_mul, map_pow _ _ m], exact ⟨hyp1, (congr_arg _ (is_localization.mk'_one _ _))⟩, end end num_denom
f8a9e7ca29424c0916ae7058858faa3e3c61b5d9
b794ca1df49bc5a3bd3fd5552eed3bc4f63b8b93
/src/mywork/sep_3_2021.lean
57f14af1da55e0604da6f7d76d7b7bf0a194fffc
[]
no_license
akraisinger/cs2120f21
8235ac98375e04ffcec504cff5cab7833ee69e54
4ef83d7151bb6a284028092aa4f1d509c0eb8237
refs/heads/main
1,691,714,771,612
1,632,889,465,000
1,632,889,465,000
399,946,508
0
0
null
null
null
null
UTF-8
Lean
false
false
1,167
lean
/- Theorem: Equality is symmetric. -/ theorem eq_symm : βˆ€ (T : Type) (x y : T), x = y β†’ y = x := begin assume (T : Type), assume (x y : T), assume (e : x = y), rw e, end /- Theorem: Equality is symmetric. In other words, βˆ€ (T : Type) (x y : T), x = y β†’ y = x Proof: Assuming a type and x&y of that type, if x = y then y = x. Proof: First we'll asssume that T is any type and we have objects x and y of this type. What remains to be shown i sthat x = y β†’ y = x. To prove this, we'll assume the premise, that x = y, and in this context we can prove y = x. But by the axiom of substitutabilty of equals, and using the fact x = y, we can rewrite x in the goal as y, yielding y = y as our new proof goal. But this is true by the axiom of reflexivity of equality. QED. -/ theorem eq_trans : βˆ€ (T : Type) (x y z : T), x = y β†’ y = z β†’ x = z := begin assume T, assume x y z, assume e1, assume e2, rw e1, exact e2, end theorem eq_trans_ops : βˆ€ (T : Type) (x y z : T), x = y β†’ y = z β†’ z = x := begin assume T, assume x y z, assume e1, assume e2, rw e1, rw e2 end
0591a5d88cb2b8b347c175e645dd866cee5bcc64
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/02_Dependent_Type_Theory.org.2.lean
c6209d2cdb63b4c5b12b0f48caa9ddbcc600d284
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
1,075
lean
/- page 12 -/ import standard import standard open bool nat -- BEGIN open prod -- makes notation for the product available constants m n : nat constant f : nat β†’ nat -- type the arrow as "\to" or "\r" constant f' : nat -> nat -- alternative ASCII notation constant f'' : β„• β†’ β„• -- \nat is alternative notation for nat constant p : nat Γ— nat -- type the product as "\times" constant q : prod nat nat -- alternative notation constant g : nat β†’ nat β†’ nat constant g' : nat β†’ (nat β†’ nat) -- has the same type as g! constant h : nat Γ— nat β†’ nat constant F : (nat β†’ nat) β†’ nat -- a "functional" check f -- β„• β†’ β„• check f n -- β„• check g m n -- β„• check g m -- β„• β†’ β„• check pair m n -- β„• Γ— β„• check pr1 p -- β„• check pr2 p -- β„• check pr1 (pair m n) -- β„• check pair (pr1 p) n -- β„• Γ— β„• check F f -- β„• -- END -- Write down some types, declare some constants, and check some expressions.
7d84f0f5f609a6114275bd952cb0f86ced498d9c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/continuous_function/cocompact_map.lean
7b5b64c25d702fba53cec55bbdd93e017a8ab05f
[ "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
6,275
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 topology.continuous_function.basic /-! # Cocompact continuous maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The type of *cocompact continuous maps* are those which tend to the cocompact filter on the codomain along the cocompact filter on the domain. When the domain and codomain are Hausdorff, this is equivalent to many other conditions, including that preimages of compact sets are compact. -/ universes u v w open filter set /-! ### Cocompact continuous maps -/ /-- A *cocompact continuous map* is a continuous function between topological spaces which tends to the cocompact filter along the cocompact filter. Functions for which preimages of compact sets are compact always satisfy this property, and the converse holds for cocompact continuous maps when the codomain is Hausdorff (see `cocompact_map.tendsto_of_forall_preimage` and `cocompact_map.is_compact_preimage`). Cocompact maps thus generalise proper maps, with which they correspond when the codomain is Hausdorff. -/ structure cocompact_map (Ξ± : Type u) (Ξ² : Type v) [topological_space Ξ±] [topological_space Ξ²] extends continuous_map Ξ± Ξ² : Type (max u v) := (cocompact_tendsto' : tendsto to_fun (cocompact Ξ±) (cocompact Ξ²)) section set_option old_structure_cmd true /-- `cocompact_map_class F Ξ± Ξ²` states that `F` is a type of cocompact continuous maps. You should also extend this typeclass when you extend `cocompact_map`. -/ class cocompact_map_class (F : Type*) (Ξ± Ξ² : out_param $ Type*) [topological_space Ξ±] [topological_space Ξ²] extends continuous_map_class F Ξ± Ξ² := (cocompact_tendsto (f : F) : tendsto f (cocompact Ξ±) (cocompact Ξ²)) end namespace cocompact_map_class variables {F Ξ± Ξ² : Type*} [topological_space Ξ±] [topological_space Ξ²] [cocompact_map_class F Ξ± Ξ²] instance : has_coe_t F (cocompact_map Ξ± Ξ²) := ⟨λ f, ⟨f, cocompact_tendsto f⟩⟩ end cocompact_map_class export cocompact_map_class (cocompact_tendsto) namespace cocompact_map section basics variables {Ξ± Ξ² Ξ³ Ξ΄ : Type*} [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] [topological_space Ξ΄] instance : cocompact_map_class (cocompact_map Ξ± Ξ²) Ξ± Ξ² := { coe := Ξ» f, f.to_fun, coe_injective' := Ξ» f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_continuous := Ξ» f, f.continuous_to_fun, cocompact_tendsto := Ξ» f, f.cocompact_tendsto' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (cocompact_map Ξ± Ξ²) (Ξ» _, Ξ± β†’ Ξ²) := fun_like.has_coe_to_fun @[simp] lemma coe_to_continuous_fun {f : cocompact_map Ξ± Ξ²} : (f.to_continuous_map : Ξ± β†’ Ξ²) = f := rfl @[ext] lemma ext {f g : cocompact_map Ξ± Ξ²} (h : βˆ€ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Copy of a `cocompact_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : cocompact_map Ξ± Ξ²) (f' : Ξ± β†’ Ξ²) (h : f' = f) : cocompact_map Ξ± Ξ² := { to_fun := f', continuous_to_fun := by {rw h, exact f.continuous_to_fun}, cocompact_tendsto' := by { simp_rw h, exact f.cocompact_tendsto' } } @[simp] lemma coe_copy (f : cocompact_map Ξ± Ξ²) (f' : Ξ± β†’ Ξ²) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : cocompact_map Ξ± Ξ²) (f' : Ξ± β†’ Ξ²) (h : f' = f) : f.copy f' h = f := fun_like.ext' h @[simp] lemma coe_mk (f : C(Ξ±, Ξ²)) (h : tendsto f (cocompact Ξ±) (cocompact Ξ²)) : ⇑(⟨f, h⟩ : cocompact_map Ξ± Ξ²) = f := rfl section variable (Ξ±) /-- The identity as a cocompact continuous map. -/ protected def id : cocompact_map Ξ± Ξ± := ⟨continuous_map.id _, tendsto_id⟩ @[simp] lemma coe_id : ⇑(cocompact_map.id Ξ±) = id := rfl end instance : inhabited (cocompact_map Ξ± Ξ±) := ⟨cocompact_map.id α⟩ /-- The composition of cocompact continuous maps, as a cocompact continuous map. -/ def comp (f : cocompact_map Ξ² Ξ³) (g : cocompact_map Ξ± Ξ²) : cocompact_map Ξ± Ξ³ := ⟨f.to_continuous_map.comp g, (cocompact_tendsto f).comp (cocompact_tendsto g)⟩ @[simp] lemma coe_comp (f : cocompact_map Ξ² Ξ³) (g : cocompact_map Ξ± Ξ²) : ⇑(comp f g) = f ∘ g := rfl @[simp] lemma comp_apply (f : cocompact_map Ξ² Ξ³) (g : cocompact_map Ξ± Ξ²) (a : Ξ±) : comp f g a = f (g a) := rfl @[simp] lemma comp_assoc (f : cocompact_map Ξ³ Ξ΄) (g : cocompact_map Ξ² Ξ³) (h : cocompact_map Ξ± Ξ²) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma id_comp (f : cocompact_map Ξ± Ξ²) : (cocompact_map.id _).comp f = f := ext $ Ξ» _, rfl @[simp] lemma comp_id (f : cocompact_map Ξ± Ξ²) : f.comp (cocompact_map.id _) = f := ext $ Ξ» _, rfl lemma tendsto_of_forall_preimage {f : Ξ± β†’ Ξ²} (h : βˆ€ s, is_compact s β†’ is_compact (f ⁻¹' s)) : tendsto f (cocompact Ξ±) (cocompact Ξ²) := Ξ» s hs, match mem_cocompact.mp hs with ⟨t, ht, hts⟩ := mem_map.mpr (mem_cocompact.mpr ⟨f ⁻¹' t, h t ht, by simpa using preimage_mono hts⟩) end /-- If the codomain is Hausdorff, preimages of compact sets are compact under a cocompact continuous map. -/ lemma is_compact_preimage [t2_space Ξ²] (f : cocompact_map Ξ± Ξ²) ⦃s : set β⦄ (hs : is_compact s) : is_compact (f ⁻¹' s) := begin obtain ⟨t, ht, hts⟩ := mem_cocompact'.mp (by simpa only [preimage_image_preimage, preimage_compl] using mem_map.mp (cocompact_tendsto f $ mem_cocompact.mpr ⟨s, hs, compl_subset_compl.mpr (image_preimage_subset f _)⟩)), exact is_compact_of_is_closed_subset ht (hs.is_closed.preimage $ map_continuous f) (by simpa using hts), end end basics end cocompact_map /-- A homemomorphism is a cocompact map. -/ @[simps] def homeomorph.to_cocompact_map {Ξ± Ξ² : Type*} [topological_space Ξ±] [topological_space Ξ²] (f : Ξ± β‰ƒβ‚œ Ξ²) : cocompact_map Ξ± Ξ² := { to_fun := f, continuous_to_fun := f.continuous, cocompact_tendsto' := begin refine cocompact_map.tendsto_of_forall_preimage (Ξ» K hK, _), erw K.preimage_equiv_eq_image_symm, exact hK.image f.symm.continuous, end }
458ccf571f8ced6f1161dd0b18f0b675289058e1
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/matrix/determinant.lean
95a4b8e199953ad84071eb8f50f7e6569627e3b3
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,333
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Tim Baanen -/ import data.matrix.pequiv import data.matrix.block import data.fintype.card import group_theory.perm.fin import group_theory.perm.sign import algebra.algebra.basic import tactic.ring import linear_algebra.alternating import linear_algebra.pi /-! # Determinant of a matrix This file defines the determinant of a matrix, `matrix.det`, and its essential properties. ## Main definitions - `matrix.det`: the determinant of a square matrix, as a sum over permutations - `matrix.det_row_multilinear`: the determinant, as an `alternating_map` in the rows of the matrix ## Main results - `det_mul`: the determinant of `A ⬝ B` is the product of determinants - `det_zero_of_row_eq`: the determinant is zero if there is a repeated row - `det_block_diagonal`: the determinant of a block diagonal matrix is a product of the blocks' determinants ## Implementation notes It is possible to configure `simp` to compute determinants. See the file `test/matrix.lean` for some examples. -/ universes u v w z open equiv equiv.perm finset function namespace matrix open_locale matrix big_operators variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] local notation `Ξ΅` Οƒ:max := ((sign Οƒ : β„€ ) : R) /-- `det` is an `alternating_map` in the rows of the matrix. -/ def det_row_multilinear : alternating_map R (n β†’ R) R n := ((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization /-- The determinant of a matrix given by the Leibniz formula. -/ abbreviation det (M : matrix n n R) : R := det_row_multilinear M lemma det_apply (M : matrix n n R) : M.det = βˆ‘ Οƒ : perm n, Οƒ.sign β€’ ∏ i, M (Οƒ i) i := multilinear_map.alternatization_apply _ M -- This is what the old definition was. We use it to avoid having to change the old proofs below lemma det_apply' (M : matrix n n R) : M.det = βˆ‘ Οƒ : perm n, Ξ΅ Οƒ * ∏ i, M (Οƒ i) i := by simp [det_apply, units.smul_def] @[simp] lemma det_diagonal {d : n β†’ R} : det (diagonal d) = ∏ i, d i := begin rw det_apply', refine (finset.sum_eq_single 1 _ _).trans _, { intros Οƒ h1 h2, cases not_forall.1 (mt equiv.ext h2) with x h3, convert mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := (det_row_multilinear : alternating_map R (n β†’ R) R n).map_zero @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] @[simp] lemma det_is_empty [is_empty n] {A : matrix n n R} : det A = 1 := by simp [det_apply] lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := begin haveI : is_empty n := fintype.card_eq_zero_iff.mp h, exact det_is_empty, end /-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element. Although `unique` implies `decidable_eq` and `fintype`, the instances might not be syntactically equal. Thus, we need to fill in the args explicitly. -/ @[simp] lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) : det A = A (default n) (default n) := by simp [det_apply, univ_unique] lemma det_eq_elem_of_subsingleton [subsingleton n] (A : matrix n n R) (k : n) : det A = A k k := begin convert det_unique _, exact unique_of_subsingleton k end lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) : det A = A k k := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, exact det_eq_elem_of_subsingleton _ _ end lemma det_mul_aux {M N : matrix n n R} {p : n β†’ n} (H : Β¬bijective p) : βˆ‘ Οƒ : perm n, (Ξ΅ Οƒ) * ∏ x, (M (Οƒ x) (p x) * N (p x) x) = 0 := begin obtain ⟨i, j, hpij, hij⟩ : βˆƒ i j, p i = p j ∧ i β‰  j, { rw [← fintype.injective_iff_bijective, injective] at H, push_neg at H, exact H }, exact sum_involution (Ξ» Οƒ _, Οƒ * swap i j) (Ξ» Οƒ _, have ∏ x, M (Οƒ x) (p x) = ∏ x, M ((Οƒ * swap i j) x) (p x), from fintype.prod_equiv (swap i j) _ _ (by simp [apply_swap_eq_self hpij]), by simp [this, sign_swap hij, prod_mul_distrib]) (Ξ» Οƒ _ _, (not_congr mul_swap_eq_iff).mpr hij) (Ξ» _ _, mem_univ _) (Ξ» Οƒ _, mul_swap_involutive i j Οƒ) end @[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N := calc det (M ⬝ N) = βˆ‘ p : n β†’ n, βˆ‘ Οƒ : perm n, Ξ΅ Οƒ * ∏ i, (M (Οƒ i) (p i) * N (p i) i) : by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum, fintype.pi_finset_univ]; rw [finset.sum_comm] ... = βˆ‘ p in (@univ (n β†’ n) _).filter bijective, βˆ‘ Οƒ : perm n, Ξ΅ Οƒ * ∏ i, (M (Οƒ i) (p i) * N (p i) i) : eq.symm $ sum_subset (filter_subset _ _) (Ξ» f _ hbij, det_mul_aux $ by simpa only [true_and, mem_filter, mem_univ] using hbij) ... = βˆ‘ Ο„ : perm n, βˆ‘ Οƒ : perm n, Ξ΅ Οƒ * ∏ i, (M (Οƒ i) (Ο„ i) * N (Ο„ i) i) : sum_bij (Ξ» p h, equiv.of_bijective p (mem_filter.1 h).2) (Ξ» _ _, mem_univ _) (Ξ» _ _, rfl) (Ξ» _ _ _ _ h, by injection h) (Ξ» b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩) ... = βˆ‘ Οƒ : perm n, βˆ‘ Ο„ : perm n, (∏ i, N (Οƒ i) i) * Ξ΅ Ο„ * (∏ j, M (Ο„ j) (Οƒ j)) : by simp only [mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = βˆ‘ Οƒ : perm n, βˆ‘ Ο„ : perm n, (((∏ i, N (Οƒ i) i) * (Ξ΅ Οƒ * Ξ΅ Ο„)) * ∏ i, M (Ο„ i) i) : sum_congr rfl (Ξ» Οƒ _, fintype.sum_equiv (equiv.mul_right σ⁻¹) _ _ (Ξ» Ο„, have ∏ j, M (Ο„ j) (Οƒ j) = ∏ j, M ((Ο„ * σ⁻¹) j) j, by { rw ← σ⁻¹.prod_comp, simp only [equiv.perm.coe_mul, apply_inv_self] }, have h : Ξ΅ Οƒ * Ξ΅ (Ο„ * σ⁻¹) = Ξ΅ Ο„ := calc Ξ΅ Οƒ * Ξ΅ (Ο„ * σ⁻¹) = Ξ΅ ((Ο„ * σ⁻¹) * Οƒ) : by { rw [mul_comm, sign_mul (Ο„ * σ⁻¹)], simp only [int.cast_mul, units.coe_mul] } ... = Ξ΅ Ο„ : by simp only [inv_mul_cancel_right], by { simp_rw [equiv.coe_mul_right, h], simp only [this] })) ... = det M * det N : by simp only [det_apply', finset.mul_sum, mul_comm, mul_left_comm] /-- The determinant of a matrix, as a monoid homomorphism. -/ def det_monoid_hom : matrix n n R β†’* R := { to_fun := det, map_one' := det_one, map_mul' := det_mul } @[simp] lemma coe_det_monoid_hom : (det_monoid_hom : matrix n n R β†’ R) = det := rfl /-- On square matrices, `mul_comm` applies under `det`. -/ lemma det_mul_comm (M N : matrix m m R) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- On square matrices, `mul_left_comm` applies under `det`. -/ lemma det_mul_left_comm (M N P : matrix m m R) : det (M ⬝ (N ⬝ P)) = det (N ⬝ (M ⬝ P)) := by rw [←matrix.mul_assoc, ←matrix.mul_assoc, det_mul, det_mul_comm M N, ←det_mul] /-- On square matrices, `mul_right_comm` applies under `det`. -/ lemma det_mul_right_comm (M N P : matrix m m R) : det (M ⬝ N ⬝ P) = det (M ⬝ P ⬝ N) := by rw [matrix.mul_assoc, matrix.mul_assoc, det_mul, det_mul_comm N P, ←det_mul] lemma det_units_conj (M : units (matrix m m R)) (N : matrix m m R) : det (↑M ⬝ N ⬝ ↑M⁻¹ : matrix m m R) = det N := by rw [det_mul_right_comm, ←mul_eq_mul, ←mul_eq_mul, units.mul_inv, one_mul] lemma det_units_conj' (M : units (matrix m m R)) (N : matrix m m R) : det (↑M⁻¹ ⬝ N ⬝ ↑M : matrix m m R) = det N := det_units_conj M⁻¹ N /-- Transposing a matrix preserves the determinant. -/ @[simp] lemma det_transpose (M : matrix n n R) : Mα΅€.det = M.det := begin rw [det_apply', det_apply'], refine fintype.sum_bijective _ inv_involutive.bijective _ _ _, intros Οƒ, rw sign_inv, congr' 1, apply fintype.prod_equiv Οƒ, intros, simp end /-- Permuting the columns changes the sign of the determinant. -/ lemma det_permute (Οƒ : perm n) (M : matrix n n R) : matrix.det (Ξ» i, M (Οƒ i)) = Οƒ.sign * M.det := ((det_row_multilinear : alternating_map R (n β†’ R) R n).map_perm M Οƒ).trans (by simp [units.smul_def]) /-- Permuting rows and columns with the same equivalence has no effect. -/ @[simp] lemma det_minor_equiv_self (e : n ≃ m) (A : matrix m m R) : det (A.minor e e) = det A := begin rw [det_apply', det_apply'], apply fintype.sum_equiv (equiv.perm_congr e), intro Οƒ, rw equiv.perm.sign_perm_congr e Οƒ, congr' 1, apply fintype.prod_equiv e, intro i, rw [equiv.perm_congr_apply, equiv.symm_apply_apply, minor_apply], end /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_minor_equiv_self`; this one is unsuitable because `matrix.reindex_apply` unfolds `reindex` first. -/ lemma det_reindex_self (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A := det_minor_equiv_self e.symm A /-- The determinant of a permutation matrix equals its sign. -/ @[simp] lemma det_permutation (Οƒ : perm n) : matrix.det (Οƒ.to_pequiv.to_matrix : matrix n n R) = Οƒ.sign := by rw [←matrix.mul_one (Οƒ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix, det_permute, det_one, mul_one] @[simp] lemma det_smul (A : matrix n n R) (c : R) : det (c β€’ A) = c ^ fintype.card n * det A := calc det (c β€’ A) = det (matrix.mul (diagonal (Ξ» _, c)) A) : by rw [smul_eq_diagonal_mul] ... = det (diagonal (Ξ» _, c)) * det A : det_mul _ _ ... = c ^ fintype.card n * det A : by simp [card_univ] /-- Multiplying each row by a fixed `v i` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_row (v : n β†’ R) (A : matrix n n R) : det (Ξ» i j, v j * A i j) = (∏ i, v i) * det A := calc det (Ξ» i j, v j * A i j) = det (A ⬝ diagonal v) : congr_arg det $ by { ext, simp [mul_comm] } ... = (∏ i, v i) * det A : by rw [det_mul, det_diagonal, mul_comm] /-- Multiplying each column by a fixed `v j` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_column (v : n β†’ R) (A : matrix n n R) : det (Ξ» i j, v i * A i j) = (∏ i, v i) * det A := multilinear_map.map_smul_univ _ v A @[simp] lemma det_pow (M : matrix m m R) (n : β„•) : det (M ^ n) = (det M) ^ n := (det_monoid_hom : matrix m m R β†’* R).map_pow M n section hom_map variables {S : Type w} [comm_ring S] lemma _root_.ring_hom.map_det (f : R β†’+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := by simp [matrix.det_apply', f.map_sum, f.map_prod] lemma _root_.ring_equiv.map_det (f : R ≃+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S →ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det (f.map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_equiv.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S ≃ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det (f.map_matrix M) := f.to_alg_hom.map_det _ end hom_map @[simp] lemma det_conj_transpose [star_ring R] (M : matrix m m R) : det (Mα΄΄) = star (det M) := ((star_ring_aut : ring_aut R).map_det _).symm.trans $ congr_arg star M.det_transpose section det_zero /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : βˆ€ j, A i j = 0) : det A = 0 := (det_row_multilinear : alternating_map R (n β†’ R) R n).map_coord_zero i (funext h) lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : βˆ€ i, A i j = 0) : det A = 0 := by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, } variables {M : matrix n n R} {i j : n} /-- If a matrix has a repeated row, the determinant will be zero. -/ theorem det_zero_of_row_eq (i_ne_j : i β‰  j) (hij : M i = M j) : M.det = 0 := (det_row_multilinear : alternating_map R (n β†’ R) R n).map_eq_zero_of_eq M hij i_ne_j /-- If a matrix has a repeated column, the determinant will be zero. -/ theorem det_zero_of_column_eq (i_ne_j : i β‰  j) (hij : βˆ€ k, M k i = M k j) : M.det = 0 := by { rw [← det_transpose, det_zero_of_row_eq i_ne_j], exact funext hij } end det_zero lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n β†’ R) : det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) := (det_row_multilinear : alternating_map R (n β†’ R) R n).map_add M j u v lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n β†’ R) : det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_add], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n β†’ R) : det (update_row M j $ s β€’ u) = s * det (update_row M j u) := (det_row_multilinear : alternating_map R (n β†’ R) R n).map_smul M j s u lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n β†’ R) : det (update_column M j $ s β€’ u) = s * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_smul], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul' (M : matrix n n R) (j : n) (s : R) (u : n β†’ R) : det (update_row (s β€’ M) j u) = s ^ (fintype.card n - 1) * det (update_row M j u) := multilinear_map.map_update_smul _ M j s u lemma det_update_column_smul' (M : matrix n n R) (j : n) (s : R) (u : n β†’ R) : det (update_column (s β€’ M) j u) = s ^ (fintype.card n - 1) * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, transpose_smul, det_update_row_smul'], simp [update_row_transpose, det_transpose] end section det_eq /-! ### `det_eq` section Lemmas showing the determinant is invariant under a variety of operations. -/ lemma det_eq_of_eq_mul_det_one {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = B ⬝ C) : det A = det B := calc det A = det (B ⬝ C) : congr_arg _ hA ... = det B * det C : det_mul _ _ ... = det B : by rw [hC, mul_one] lemma det_eq_of_eq_det_one_mul {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = C ⬝ B) : det A = det B := calc det A = det (C ⬝ B) : congr_arg _ hA ... = det C * det B : det_mul _ _ ... = det B : by rw [hC, one_mul] lemma det_update_row_add_self (A : matrix n n R) {i j : n} (hij : i β‰  j) : det (update_row A i (A i + A j)) = det A := by simp [det_update_row_add, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_self (A : matrix n n R) {i j : n} (hij : i β‰  j) : det (update_column A i (Ξ» k, A k i + A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_self Aα΅€ hij } lemma det_update_row_add_smul_self (A : matrix n n R) {i j : n} (hij : i β‰  j) (c : R) : det (update_row A i (A i + c β€’ A j)) = det A := by simp [det_update_row_add, det_update_row_smul, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_smul_self (A : matrix n n R) {i j : n} (hij : i β‰  j) (c : R) : det (update_column A i (Ξ» k, A k i + c β€’ A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_smul_self Aα΅€ hij c } lemma det_eq_of_forall_row_eq_smul_add_const_aux {A B : matrix n n R} {s : finset n} : βˆ€ (c : n β†’ R) (hs : βˆ€ i, i βˆ‰ s β†’ c i = 0) (k : n) (hk : k βˆ‰ s) (A_eq : βˆ€ i j, A i j = B i j + c i * B k j), det A = det B := begin revert B, refine s.induction_on _ _, { intros A c hs k hk A_eq, have : βˆ€ i, c i = 0, { intros i, specialize hs i, contrapose! hs, simp [hs] }, congr, ext i j, rw [A_eq, this, zero_mul, add_zero], }, { intros i s hi ih B c hs k hk A_eq, have hAi : A i = B i + c i β€’ B k := funext (A_eq i), rw [@ih (update_row B i (A i)) (function.update c i 0), hAi, det_update_row_add_smul_self], { exact mt (Ξ» h, show k ∈ insert i s, from h β–Έ finset.mem_insert_self _ _) hk }, { intros i' hi', rw function.update_apply, split_ifs with hi'i, { refl }, { exact hs i' (Ξ» h, hi' ((finset.mem_insert.mp h).resolve_left hi'i)) } }, { exact Ξ» h, hk (finset.mem_insert_of_mem h) }, { intros i' j', rw [update_row_apply, function.update_apply], split_ifs with hi'i, { simp [hi'i] }, rw [A_eq, update_row_ne (Ξ» (h : k = i), hk $ h β–Έ finset.mem_insert_self k s)] } } end /-- If you add multiples of row `B k` to other rows, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_const {A B : matrix n n R} (c : n β†’ R) (k : n) (hk : c k = 0) (A_eq : βˆ€ i j, A i j = B i j + c i * B k j) : det A = det B := det_eq_of_forall_row_eq_smul_add_const_aux c (Ξ» i, not_imp_comm.mp $ Ξ» hi, finset.mem_erase.mpr ⟨mt (Ξ» (h : i = k), show c i = 0, from h.symm β–Έ hk) hi, finset.mem_univ i⟩) k (finset.not_mem_erase k finset.univ) A_eq lemma det_eq_of_forall_row_eq_smul_add_pred_aux {n : β„•} (k : fin (n + 1)) : βˆ€ (c : fin n β†’ R) (hc : βˆ€ (i : fin n), k < i.succ β†’ c i = 0) {M N : matrix (fin n.succ) (fin n.succ) R} (h0 : βˆ€ j, M 0 j = N 0 j) (hsucc : βˆ€ (i : fin n) j, M i.succ j = N i.succ j + c i * M i.cast_succ j), det M = det N := begin refine fin.induction _ (Ξ» k ih, _) k; intros c hc M N h0 hsucc, { congr, ext i j, refine fin.cases (h0 j) (Ξ» i, _) i, rw [hsucc, hc i (fin.succ_pos _), zero_mul, add_zero] }, set M' := update_row M k.succ (N k.succ) with hM', have hM : M = update_row M' k.succ (M' k.succ + c k β€’ M k.cast_succ), { ext i j, by_cases hi : i = k.succ, { simp [hi, hM', hsucc, update_row_self] }, rw [update_row_ne hi, hM', update_row_ne hi] }, have k_ne_succ : k.cast_succ β‰  k.succ := (fin.cast_succ_lt_succ k).ne, have M_k : M k.cast_succ = M' k.cast_succ := (update_row_ne k_ne_succ).symm, rw [hM, M_k, det_update_row_add_smul_self M' k_ne_succ.symm, ih (function.update c k 0)], { intros i hi, rw [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff] at hi, rw function.update_apply, split_ifs with hik, { refl }, exact hc _ (fin.succ_lt_succ_iff.mpr (lt_of_le_of_ne hi (ne.symm hik))) }, { rwa [hM', update_row_ne (fin.succ_ne_zero _).symm] }, intros i j, rw function.update_apply, split_ifs with hik, { rw [zero_mul, add_zero, hM', hik, update_row_self] }, rw [hM', update_row_ne ((fin.succ_injective _).ne hik), hsucc], by_cases hik2 : k < i, { simp [hc i (fin.succ_lt_succ_iff.mpr hik2)] }, rw update_row_ne, apply ne_of_lt, rwa [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff, ← not_lt] end /-- If you add multiples of previous rows to the next row, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_pred {n : β„•} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n β†’ R) (A_zero : βˆ€ j, A 0 j = B 0 j) (A_succ : βˆ€ (i : fin n) j, A i.succ j = B i.succ j + c i * A i.cast_succ j) : det A = det B := det_eq_of_forall_row_eq_smul_add_pred_aux (fin.last _) c (Ξ» i hi, absurd hi (not_lt_of_ge (fin.le_last _))) A_zero A_succ /-- If you add multiples of previous columns to the next columns, the determinant doesn't change. -/ lemma det_eq_of_forall_col_eq_smul_add_pred {n : β„•} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n β†’ R) (A_zero : βˆ€ i, A i 0 = B i 0) (A_succ : βˆ€ i (j : fin n), A i j.succ = B i j.succ + c j * A i j.cast_succ) : det A = det B := by { rw [← det_transpose A, ← det_transpose B], exact det_eq_of_forall_row_eq_smul_add_pred c A_zero (Ξ» i j, A_succ j i) } end det_eq @[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o β†’ matrix n n R) : (block_diagonal M).det = ∏ k, (M k).det := begin -- Rewrite the determinants as a sum over permutations. simp_rw [det_apply'], -- The right hand side is a product of sums, rewrite it as a sum of products. rw finset.prod_sum, simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ], -- We claim that the only permutations contributing to the sum are those that -- preserve their second component. let preserving_snd : finset (equiv.perm (n Γ— o)) := finset.univ.filter (Ξ» Οƒ, βˆ€ x, (Οƒ x).snd = x.snd), have mem_preserving_snd : βˆ€ {Οƒ : equiv.perm (n Γ— o)}, Οƒ ∈ preserving_snd ↔ βˆ€ x, (Οƒ x).snd = x.snd := Ξ» Οƒ, finset.mem_filter.trans ⟨λ h, h.2, Ξ» h, ⟨finset.mem_univ _, h⟩⟩, rw ← finset.sum_subset (finset.subset_univ preserving_snd) _, -- And that these are in bijection with `o β†’ equiv.perm m`. rw (finset.sum_bij (Ξ» (Οƒ : βˆ€ (k : o), k ∈ finset.univ β†’ equiv.perm n) _, prod_congr_left (Ξ» k, Οƒ k (finset.mem_univ k))) _ _ _ _).symm, { intros Οƒ _, rw mem_preserving_snd, rintros ⟨k, x⟩, simp only [prod_congr_left_apply] }, { intros Οƒ _, rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product, finset.prod_comm], simp only [sign_prod_congr_left, units.coe_prod, int.cast_prod, block_diagonal_apply_eq, prod_congr_left_apply] }, { intros Οƒ Οƒ' _ _ eq, ext x hx k, simp only at eq, have : βˆ€ k x, prod_congr_left (Ξ» k, Οƒ k (finset.mem_univ _)) (k, x) = prod_congr_left (Ξ» k, Οƒ' k (finset.mem_univ _)) (k, x) := Ξ» k x, by rw eq, simp only [prod_congr_left_apply, prod.mk.inj_iff] at this, exact (this k x).1 }, { intros Οƒ hΟƒ, rw mem_preserving_snd at hΟƒ, have hΟƒ' : βˆ€ x, (σ⁻¹ x).snd = x.snd, { intro x, conv_rhs { rw [← perm.apply_inv_self Οƒ x, hΟƒ] } }, have mk_apply_eq : βˆ€ k x, ((Οƒ (x, k)).fst, k) = Οƒ (x, k), { intros k x, ext, { simp only}, { simp only [hΟƒ] } }, have mk_inv_apply_eq : βˆ€ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k), { intros k x, conv_lhs { rw ← perm.apply_inv_self Οƒ (x, k) }, ext, { simp only [apply_inv_self] }, { simp only [hΟƒ'] } }, refine ⟨λ k _, ⟨λ x, (Οƒ (x, k)).fst, Ξ» x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩, { intro x, simp only [mk_apply_eq, inv_apply_self] }, { intro x, simp only [mk_inv_apply_eq, apply_inv_self] }, { apply finset.mem_univ }, { ext ⟨k, x⟩, { simp only [coe_fn_mk, prod_congr_left_apply] }, { simp only [prod_congr_left_apply, hΟƒ] } } }, { intros Οƒ _ hΟƒ, rw mem_preserving_snd at hΟƒ, obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hΟƒ, rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero], rw [← @prod.mk.eta _ _ (Οƒ (k, x)), block_diagonal_apply_ne], exact hkx } end /-- The determinant of a 2x2 block matrix with the lower-left block equal to zero is the product of the determinants of the diagonal blocks. For the generalization to any number of blocks, see `matrix.upper_block_triangular_det`. -/ lemma upper_two_block_triangular_det (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : (matrix.from_blocks A B 0 D).det = A.det * D.det := begin classical, simp_rw det_apply', convert (sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m βŠ• n))).to_finset) _).symm, rw sum_mul_sum, simp_rw univ_product_univ, rw (sum_bij (Ξ» (Οƒ : perm m Γ— perm n) _, equiv.sum_congr Οƒ.fst Οƒ.snd) _ _ _ _).symm, { intros σ₁₂ h, simp only [], erw [set.mem_to_finset, monoid_hom.mem_range], use σ₁₂, simp only [sum_congr_hom_apply] }, { simp only [forall_prop_of_true, prod.forall, mem_univ], intros σ₁ Οƒβ‚‚, rw fintype.prod_sum_type, simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁, from_blocks_applyβ‚‚β‚‚], have hr : βˆ€ (a b c d : R), (a * b) * (c * d) = a * c * (b * d), { intros, ac_refl }, rw hr, congr, rw [sign_sum_congr, units.coe_mul, int.cast_mul] }, { intros σ₁ Οƒβ‚‚ h₁ hβ‚‚, dsimp only [], intro h, have h2 : βˆ€ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr Οƒβ‚‚.fst Οƒβ‚‚.snd x, { intro x, exact congr_fun (congr_arg to_fun h) x }, simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2, ext, { exact h2.left x }, { exact h2.right x }}, { intros Οƒ hΟƒ, erw [set.mem_to_finset, monoid_hom.mem_range] at hΟƒ, obtain βŸ¨Οƒβ‚β‚‚, hΟƒβ‚β‚‚βŸ© := hΟƒ, use σ₁₂, rw ←hσ₁₂, simp }, { intros Οƒ hΟƒ hΟƒn, have h1 : Β¬ (βˆ€ x, βˆƒ y, sum.inl y = Οƒ (sum.inl x)), { by_contradiction, rw set.mem_to_finset at hΟƒn, apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hΟƒn, rintros x ⟨a, ha⟩, rw [←ha], exact h a }, obtain ⟨a, ha⟩ := not_forall.mp h1, cases hx : Οƒ (sum.inl a) with a2 b, { have hn := (not_exists.mp ha) a2, exact absurd hx.symm hn }, { rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero], rw [hx, from_blocks_apply₂₁], refl }} end /-- Laplacian expansion of the determinant of an `n+1 Γ— n+1` matrix along column 0. -/ lemma det_succ_column_zero {n : β„•} (A : matrix (fin n.succ) (fin n.succ) R) : det A = βˆ‘ i : fin n.succ, (-1) ^ (i : β„•) * A i 0 * det (A.minor i.succ_above fin.succ) := begin rw [matrix.det_apply, finset.univ_perm_fin_succ, ← finset.univ_product_univ], simp only [finset.sum_map, equiv.to_embedding_apply, finset.sum_product, matrix.minor], refine finset.sum_congr rfl (Ξ» i _, fin.cases _ (Ξ» i, _) i), { simp only [fin.prod_univ_succ, matrix.det_apply, finset.mul_sum, equiv.perm.decompose_fin_symm_apply_zero, fin.coe_zero, one_mul, equiv.perm.decompose_fin.symm_sign, equiv.swap_self, if_true, id.def, eq_self_iff_true, equiv.perm.decompose_fin_symm_apply_succ, fin.succ_above_zero, equiv.coe_refl, pow_zero, mul_smul_comm] }, -- `univ_perm_fin_succ` gives a different embedding of `perm (fin n)` into -- `perm (fin n.succ)` than the determinant of the submatrix we want, -- permute `A` so that we get the correct one. have : (-1 : R) ^ (i : β„•) = i.cycle_range.sign, { simp [fin.sign_cycle_range] }, rw [fin.coe_succ, pow_succ, this, mul_assoc, mul_assoc, mul_left_comm ↑(equiv.perm.sign _), ← det_permute, matrix.det_apply, finset.mul_sum, finset.mul_sum], -- now we just need to move the corresponding parts to the same place refine finset.sum_congr rfl (Ξ» Οƒ _, _), rw [equiv.perm.decompose_fin.symm_sign, if_neg (fin.succ_ne_zero i)], calc ((-1) * Οƒ.sign : β„€) β€’ ∏ i', A (equiv.perm.decompose_fin.symm (fin.succ i, Οƒ) i') i' = ((-1) * Οƒ.sign : β„€) β€’ (A (fin.succ i) 0 * ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (Οƒ i'))) i'.succ) : by simp only [fin.prod_univ_succ, fin.succ_above_cycle_range, equiv.perm.decompose_fin_symm_apply_zero, equiv.perm.decompose_fin_symm_apply_succ] ... = (-1) * (A (fin.succ i) 0 * (Οƒ.sign : β„€) β€’ ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (Οƒ i'))) i'.succ) : by simp only [mul_assoc, mul_comm, neg_mul_eq_neg_mul_symm, one_mul, zsmul_eq_mul, neg_inj, neg_smul, fin.succ_above_cycle_range], end /-- Laplacian expansion of the determinant of an `n+1 Γ— n+1` matrix along row 0. -/ lemma det_succ_row_zero {n : β„•} (A : matrix (fin n.succ) (fin n.succ) R) : det A = βˆ‘ j : fin n.succ, (-1) ^ (j : β„•) * A 0 j * det (A.minor fin.succ j.succ_above) := by { rw [← det_transpose A, det_succ_column_zero], refine finset.sum_congr rfl (Ξ» i _, _), rw [← det_transpose], simp only [transpose_apply, transpose_minor, transpose_transpose] } /-- Laplacian expansion of the determinant of an `n+1 Γ— n+1` matrix along row `i`. -/ lemma det_succ_row {n : β„•} (A : matrix (fin n.succ) (fin n.succ) R) (i : fin n.succ) : det A = βˆ‘ j : fin n.succ, (-1) ^ (i + j : β„•) * A i j * det (A.minor i.succ_above j.succ_above) := begin simp_rw [pow_add, mul_assoc, ← mul_sum], have : det A = (-1 : R) ^ (i : β„•) * (i.cycle_range⁻¹).sign * det A, { calc det A = ↑((-1 : units β„€) ^ (i : β„•) * (-1 : units β„€) ^ (i : β„•) : units β„€) * det A : by simp ... = (-1 : R) ^ (i : β„•) * (i.cycle_range⁻¹).sign * det A : by simp [-int.units_mul_self] }, rw [this, mul_assoc], congr, rw [← det_permute, det_succ_row_zero], refine finset.sum_congr rfl (Ξ» j _, _), rw [mul_assoc, matrix.minor, matrix.minor], congr, { rw [equiv.perm.inv_def, fin.cycle_range_symm_zero] }, { ext i' j', rw [equiv.perm.inv_def, fin.cycle_range_symm_succ] }, end /-- Laplacian expansion of the determinant of an `n+1 Γ— n+1` matrix along column `j`. -/ lemma det_succ_column {n : β„•} (A : matrix (fin n.succ) (fin n.succ) R) (j : fin n.succ) : det A = βˆ‘ i : fin n.succ, (-1) ^ (i + j : β„•) * A i j * det (A.minor i.succ_above j.succ_above) := by { rw [← det_transpose, det_succ_row _ j], refine finset.sum_congr rfl (Ξ» i _, _), rw [add_comm, ← det_transpose, transpose_apply, transpose_minor, transpose_transpose] } /-- Determinant of 0x0 matrix -/ @[simp] lemma det_fin_zero {A : matrix (fin 0) (fin 0) R} : det A = 1 := det_is_empty /-- Determinant of 1x1 matrix -/ lemma det_fin_one (A : matrix (fin 1) (fin 1) R) : det A = A 0 0 := det_unique A /-- Determinant of 2x2 matrix -/ lemma det_fin_two (A : matrix (fin 2) (fin 2) R) : det A = A 0 0 * A 1 1 - A 0 1 * A 1 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end /-- Determinant of 3x3 matrix -/ lemma det_fin_three (A : matrix (fin 3) (fin 3) R) : det A = A 0 0 * A 1 1 * A 2 2 - A 0 0 * A 1 2 * A 2 1 - A 0 1 * A 1 0 * A 2 2 + A 0 1 * A 1 2 * A 2 0 + A 0 2 * A 1 0 * A 2 1 - A 0 2 * A 1 1 * A 2 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end end matrix
f4b5a398d2bdda87bce5e9166fceb5620abab2b3
87d5955e1100ba73f6b56149b659e85116fa215b
/group_theory/finfun.lean
4301f1a21726ebcdf8f7e03d0fb7449a3a098ce9
[ "Apache-2.0" ]
permissive
avigad/leanproved
4d15a05f8544a67b9f589c5e656358e1485aef3c
3cf0f5dda3ace82f6b7cdc159528ce3ebaef159f
refs/heads/master
1,611,368,103,158
1,433,589,072,000
1,433,589,072,000
36,843,899
0
0
null
1,433,385,918,000
1,433,385,918,000
null
UTF-8
Lean
false
false
3,890
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import data .extra open nat function list namespace fintype open eq.ops section list_to_fun variables {A B : Type} variable [finA : fintype A] include finA definition list_to_fun [deceqA : decidable_eq A] (l : list B) (leq : length l = card A) : A β†’ B := assume x, let k := find x (elements_of A) in have Plt : k < card A, from (find_lt_length (complete x)), have Pltl : k < length l, from leq⁻¹ β–Έ Plt, kth _ _ Pltl end list_to_fun section surj_inv variables {A B : Type} variable [finA : fintype A] include finA -- surj from fintype domain implies fintype range lemma mem_map_of_surj {f : A β†’ B} (surj : surjective f) : βˆ€ b, b ∈ map f (elements_of A) := take b, obtain a Peq, from surj b, Peq β–Έ mem_map f (complete a) variable [deceqB : decidable_eq B] include deceqB lemma found_of_surj {f : A β†’ B} (surj : surjective f) : βˆ€ b, let elts := elems A, k := find b (map f elts) in k < length elts := Ξ» b, let elts := elems A, img := map f elts, k := find b img in have Pin : b ∈ img, from mem_map_of_surj surj b, assert Pfound : k < length img, from find_lt_length (mem_map_of_surj surj b), length_map f elts β–Έ Pfound definition right_inv {f : A β†’ B} (surj : surjective f) : B β†’ A := Ξ» b, let elts := elems A, k := find b (map f elts) in kth k elts (found_of_surj surj b) lemma found_of_map {f : A β†’ B} (b : B) : βˆ€ (l : list A) (P : find b (map f l) < length l), f (kth (find b (map f l)) l P) = b | [] := assume P, begin exact absurd P !not_lt_zero end | (a::l) := decidable.rec_on (deceqB b (f a)) (assume Peq, begin rewrite [map_cons f a l, find_cons_of_eq _ Peq], intro P, rewrite [kth_zero_of_cons], exact (Peq⁻¹) end) (assume Pne, begin rewrite [map_cons f a l, find_cons_of_ne _ Pne], intro P, rewrite [kth_succ_of_cons (find b (map f l)) l P], exact found_of_map l (lt_of_succ_lt_succ P) end) lemma id_of_right_inv' {f : A β†’ B} (surj : surjective f) (b : B) : f (right_inv surj b) = b := found_of_map b (elems A) (found_of_surj surj b) lemma id_of_right_inv {f : A β†’ B} (surj : surjective f) : f ∘ (right_inv surj) = id := funext (id_of_right_inv' surj) end surj_inv -- inj functions for equal card types are also surj and therefore bij -- the right inv (since it is surj) is also the left inv section inj variables {A B : Type} variable [finA : fintype A] include finA variable [deceqA : decidable_eq A] include deceqA variable [finB : fintype B] include finB variable [deceqB : decidable_eq B] include deceqB open finset lemma surj_of_inj_eq_card : card A = card B β†’ βˆ€ {f : A β†’ B}, injective f β†’ surjective f := assume Peqcard, take f, assume Pinj, decidable.rec_on decidable_forall_finite (assume P : surjective f, P) (assume Pnsurj : Β¬surjective f, obtain b Pne, from exists_not_of_not_forall Pnsurj, assert Pall : βˆ€ a, f a β‰  b, from forall_not_of_not_exists Pne, assert Pbnin : b βˆ‰ image f univ, from Ξ» Pin, obtain a Pa, from exists_of_mem_image Pin, absurd (and.right Pa) (Pall a), assert Puniv : finset.card (image f univ) = card A, from card_eq_card_image_of_inj Pinj, assert Punivb : finset.card (image f univ) = card B, from eq.trans Puniv Peqcard, assert P : image f univ = univ, from univ_of_card_eq_univ Punivb, absurd (P⁻¹▸ mem_univ b) Pbnin) end inj end fintype
2c5d08687f3ee2c557732680187de6e47761a93e
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/theorem_proving_in_lean/not_p_iff_not_p.lean
d732873f526af54a96bfb155d0aac9974bbaf4df
[]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
209
lean
variable p : Prop example : Β¬(p ↔ Β¬p) := begin intro h, have hnp: Β¬ p, intro hp, have hnp := iff.mp h hp, exact hnp hp, have hp: p, exact iff.mpr h hnp, exact hnp hp, end
e2a48309f1ae4c030acbcbf908c4e42d71bf269b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/list/sections.lean
a389b765a290c61ca912d851537ab480d83aa900
[ "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
1,448
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.forall2 /-! # List sections This file proves some stuff about `list.sections` (definition in `data.list.defs`). A section of a list of lists `[l₁, ..., lβ‚™]` is a list whose `i`-th element comes from the `i`-th list. -/ open nat function namespace list variables {Ξ± Ξ² : Type*} theorem mem_sections {L : list (list Ξ±)} {f} : f ∈ sections L ↔ forallβ‚‚ (∈) f L := begin refine ⟨λ h, _, Ξ» h, _⟩, { induction L generalizing f, {cases mem_singleton.1 h, exact forallβ‚‚.nil}, simp only [sections, bind_eq_bind, mem_bind, mem_map] at h, rcases h with ⟨_, _, _, _, rfl⟩, simp only [*, forallβ‚‚_cons, true_and] }, { induction h with a l f L al fL fs, {exact or.inl rfl}, simp only [sections, bind_eq_bind, mem_bind, mem_map], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list Ξ±)} {f} (h : f ∈ sections L) : length f = length L := (mem_sections.1 h).length_eq lemma rel_sections {r : Ξ± β†’ Ξ² β†’ Prop} : (forallβ‚‚ (forallβ‚‚ r) β‡’ forallβ‚‚ (forallβ‚‚ r)) sections sections | _ _ forallβ‚‚.nil := forallβ‚‚.cons forallβ‚‚.nil forallβ‚‚.nil | _ _ (forallβ‚‚.cons hβ‚€ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forallβ‚‚.cons ha hl) hβ‚€) end list
500c03f6309dd44b44f5309655800229e6c63104
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/hull.lean
535a17885c56f987950eca42b492dfeac0cf8820
[ "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
7,289
lean
/- Copyright (c) 2020 Yury Kudriashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudriashov, YaΓ«l Dillies -/ import analysis.convex.basic import order.closure /-! # Convex hull > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the convex hull of a set `s` in a module. `convex_hull π•œ s` is the smallest convex set containing `s`. In order theory speak, this is a closure operator. ## Implementation notes `convex_hull` is defined as a closure operator. This gives access to the `closure_operator` API while the impact on writing code is minimal as `convex_hull π•œ s` is automatically elaborated as `⇑(convex_hull π•œ) s`. -/ open set open_locale pointwise variables {π•œ E F : Type*} section convex_hull section ordered_semiring variables [ordered_semiring π•œ] section add_comm_monoid variables (π•œ) [add_comm_monoid E] [add_comm_monoid F] [module π•œ E] [module π•œ F] /-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/ def convex_hull : closure_operator (set E) := closure_operator.mk₃ (Ξ» s, β‹‚ (t : set E) (hst : s βŠ† t) (ht : convex π•œ t), t) (convex π•œ) (Ξ» s, set.subset_Inter (Ξ» t, set.subset_Inter $ Ξ» hst, set.subset_Inter $ Ξ» ht, hst)) (Ξ» s, convex_Inter $ Ξ» t, convex_Inter $ Ξ» ht, convex_Inter id) (Ξ» s t hst ht, set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht) variables (s : set E) lemma subset_convex_hull : s βŠ† convex_hull π•œ s := (convex_hull π•œ).le_closure s lemma convex_convex_hull : convex π•œ (convex_hull π•œ s) := closure_operator.closure_mem_mk₃ s lemma convex_hull_eq_Inter : convex_hull π•œ s = β‹‚ (t : set E) (hst : s βŠ† t) (ht : convex π•œ t), t := rfl variables {π•œ s} {t : set E} {x y : E} lemma mem_convex_hull_iff : x ∈ convex_hull π•œ s ↔ βˆ€ t, s βŠ† t β†’ convex π•œ t β†’ x ∈ t := by simp_rw [convex_hull_eq_Inter, mem_Inter] lemma convex_hull_min (hst : s βŠ† t) (ht : convex π•œ t) : convex_hull π•œ s βŠ† t := closure_operator.closure_le_mk₃_iff (show s ≀ t, from hst) ht lemma convex.convex_hull_subset_iff (ht : convex π•œ t) : convex_hull π•œ s βŠ† t ↔ s βŠ† t := ⟨(subset_convex_hull _ _).trans, Ξ» h, convex_hull_min h ht⟩ @[mono] lemma convex_hull_mono (hst : s βŠ† t) : convex_hull π•œ s βŠ† convex_hull π•œ t := (convex_hull π•œ).monotone hst lemma convex.convex_hull_eq (hs : convex π•œ s) : convex_hull π•œ s = s := closure_operator.mem_mk₃_closed hs @[simp] lemma convex_hull_univ : convex_hull π•œ (univ : set E) = univ := closure_operator.closure_top (convex_hull π•œ) @[simp] lemma convex_hull_empty : convex_hull π•œ (βˆ… : set E) = βˆ… := convex_empty.convex_hull_eq @[simp] lemma convex_hull_empty_iff : convex_hull π•œ s = βˆ… ↔ s = βˆ… := begin split, { intro h, rw [←set.subset_empty_iff, ←h], exact subset_convex_hull π•œ _ }, { rintro rfl, exact convex_hull_empty } end @[simp] lemma convex_hull_nonempty_iff : (convex_hull π•œ s).nonempty ↔ s.nonempty := begin rw [nonempty_iff_ne_empty, nonempty_iff_ne_empty, ne.def, ne.def], exact not_congr convex_hull_empty_iff, end alias convex_hull_nonempty_iff ↔ _ set.nonempty.convex_hull attribute [protected] set.nonempty.convex_hull lemma segment_subset_convex_hull (hx : x ∈ s) (hy : y ∈ s) : segment π•œ x y βŠ† convex_hull π•œ s := (convex_convex_hull _ _).segment_subset (subset_convex_hull _ _ hx) (subset_convex_hull _ _ hy) @[simp] lemma convex_hull_singleton (x : E) : convex_hull π•œ ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq @[simp] lemma convex_hull_zero : convex_hull π•œ (0 : set E) = 0 := convex_hull_singleton 0 @[simp] lemma convex_hull_pair (x y : E) : convex_hull π•œ {x, y} = segment π•œ x y := begin refine (convex_hull_min _ $ convex_segment _ _).antisymm (segment_subset_convex_hull (mem_insert _ _) $ mem_insert_of_mem _ $ mem_singleton _), rw [insert_subset, singleton_subset_iff], exact ⟨left_mem_segment _ _ _, right_mem_segment _ _ _⟩, end lemma convex_hull_convex_hull_union_left (s t : set E) : convex_hull π•œ (convex_hull π•œ s βˆͺ t) = convex_hull π•œ (s βˆͺ t) := closure_operator.closure_sup_closure_left _ _ _ lemma convex_hull_convex_hull_union_right (s t : set E) : convex_hull π•œ (s βˆͺ convex_hull π•œ t) = convex_hull π•œ (s βˆͺ t) := closure_operator.closure_sup_closure_right _ _ _ lemma convex.convex_remove_iff_not_mem_convex_hull_remove {s : set E} (hs : convex π•œ s) (x : E) : convex π•œ (s \ {x}) ↔ x βˆ‰ convex_hull π•œ (s \ {x}) := begin split, { rintro hsx hx, rw hsx.convex_hull_eq at hx, exact hx.2 (mem_singleton _) }, rintro hx, suffices h : s \ {x} = convex_hull π•œ (s \ {x}), { convert convex_convex_hull π•œ _ }, exact subset.antisymm (subset_convex_hull π•œ _) (Ξ» y hy, ⟨convex_hull_min (diff_subset _ _) hs hy, by { rintro (rfl : y = x), exact hx hy }⟩), end lemma is_linear_map.convex_hull_image {f : E β†’ F} (hf : is_linear_map π•œ f) (s : set E) : convex_hull π•œ (f '' s) = f '' convex_hull π•œ s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull π•œ s)) $ (convex_convex_hull π•œ s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull π•œ _) ((convex_convex_hull π•œ _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E β†’β‚—[π•œ] F) (s : set E) : convex_hull π•œ (f '' s) = f '' convex_hull π•œ s := f.is_linear.convex_hull_image s end add_comm_monoid end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring π•œ] [add_comm_monoid E] [module π•œ E] lemma convex_hull_smul (a : π•œ) (s : set E) : convex_hull π•œ (a β€’ s) = a β€’ convex_hull π•œ s := (linear_map.lsmul _ _ a).convex_hull_image _ end ordered_comm_semiring section ordered_ring variables [ordered_ring π•œ] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module π•œ E] [module π•œ F] (s : set E) lemma affine_map.image_convex_hull (f : E →ᡃ[π•œ] F) : f '' convex_hull π•œ s = convex_hull π•œ (f '' s) := begin apply set.subset.antisymm, { rw set.image_subset_iff, refine convex_hull_min _ ((convex_convex_hull π•œ (⇑f '' s)).affine_preimage f), rw ← set.image_subset_iff, exact subset_convex_hull π•œ (f '' s) }, { exact convex_hull_min (set.image_subset _ (subset_convex_hull π•œ s)) ((convex_convex_hull π•œ s).affine_image f) } end lemma convex_hull_subset_affine_span : convex_hull π•œ s βŠ† (affine_span π•œ s : set E) := convex_hull_min (subset_affine_span π•œ s) (affine_span π•œ s).convex @[simp] lemma affine_span_convex_hull : affine_span π•œ (convex_hull π•œ s) = affine_span π•œ s := begin refine le_antisymm _ (affine_span_mono π•œ (subset_convex_hull π•œ s)), rw affine_span_le, exact convex_hull_subset_affine_span s, end lemma convex_hull_neg (s : set E) : convex_hull π•œ (-s) = -convex_hull π•œ s := by { simp_rw ←image_neg, exact (affine_map.image_convex_hull _ $ -1).symm } end add_comm_group end ordered_ring end convex_hull
f3b3feb4e93f77eb8f36eab6047654b0ba48b595
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/control/monad_fail_auto.lean
df0553ee23542713517bf5bbab5cca324bf0220f
[]
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
734
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.control.lift import Mathlib.Lean3Lib.init.data.string.basic universes u v l namespace Mathlib class monad_fail (m : Type u β†’ Type v) where fail : {a : Type u} β†’ string β†’ m a def match_failed {Ξ± : Type u} {m : Type u β†’ Type v} [monad_fail m] : m Ξ± := sorry protected instance monad_fail_lift (m : Type u β†’ Type v) (n : Type u β†’ Type v) [Monad n] [monad_fail m] [has_monad_lift m n] : monad_fail n := monad_fail.mk fun (Ξ± : Type u) (s : string) => monad_lift (monad_fail.fail s) end Mathlib
97f49550d0b9b258b311187992c38e8a5e561cac
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/opens_auto.lean
a43e19369833f36915c3a22517af8b287c8d9935
[]
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
14,784
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, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.bases import Mathlib.topology.homeomorph import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Open sets ## Summary We define the subtype of open sets in a topological space. ## Main Definitions - `opens Ξ±` is the type of open subsets of a topological space `Ξ±`. - `open_nhds_of x` is the type of open subsets of a topological space `Ξ±` containing `x : Ξ±`. - -/ namespace topological_space /-- The type of open subsets of a topological space. -/ def opens (Ξ± : Type u_1) [topological_space Ξ±] := Subtype fun (s : set Ξ±) => is_open s namespace opens protected instance set.has_coe {Ξ± : Type u_1} [topological_space Ξ±] : has_coe (opens Ξ±) (set Ξ±) := has_coe.mk subtype.val theorem val_eq_coe {Ξ± : Type u_1} [topological_space Ξ±] (U : opens Ξ±) : subtype.val U = ↑U := rfl /-- the coercion `opens Ξ± β†’ set Ξ±` applied to a pair is the same as taking the first component -/ theorem coe_mk {Ξ± : Type u_1} [topological_space Ξ±] {U : set Ξ±} {hU : is_open U} : ↑{ val := U, property := hU } = U := rfl protected instance has_subset {Ξ± : Type u_1} [topological_space Ξ±] : has_subset (opens Ξ±) := has_subset.mk fun (U V : opens Ξ±) => ↑U βŠ† ↑V protected instance has_mem {Ξ± : Type u_1} [topological_space Ξ±] : has_mem Ξ± (opens Ξ±) := has_mem.mk fun (a : Ξ±) (U : opens Ξ±) => a ∈ ↑U @[simp] theorem subset_coe {Ξ± : Type u_1} [topological_space Ξ±] {U : opens Ξ±} {V : opens Ξ±} : ↑U βŠ† ↑V = (U βŠ† V) := rfl @[simp] theorem mem_coe {Ξ± : Type u_1} [topological_space Ξ±] {x : Ξ±} {U : opens Ξ±} : x ∈ ↑U = (x ∈ U) := rfl theorem ext {Ξ± : Type u_1} [topological_space Ξ±] {U : opens Ξ±} {V : opens Ξ±} (h : ↑U = ↑V) : U = V := iff.mpr subtype.ext_iff h theorem ext_iff {Ξ± : Type u_1} [topological_space Ξ±] {U : opens Ξ±} {V : opens Ξ±} : ↑U = ↑V ↔ U = V := { mp := ext, mpr := congr_arg coe } protected instance partial_order {Ξ± : Type u_1} [topological_space Ξ±] : partial_order (opens Ξ±) := subtype.partial_order fun (s : set Ξ±) => is_open s /-- The interior of a set, as an element of `opens`. -/ def interior {Ξ± : Type u_1} [topological_space Ξ±] (s : set Ξ±) : opens Ξ± := { val := interior s, property := is_open_interior } theorem gc {Ξ± : Type u_1} [topological_space Ξ±] : galois_connection coe interior := fun (U : opens Ξ±) (s : set Ξ±) => { mp := fun (h : ↑U ≀ s) => interior_maximal h (subtype.property U), mpr := fun (h : U ≀ interior s) => le_trans h interior_subset } /-- The galois insertion between sets and opens, but ordered by reverse inclusion. -/ def gi {Ξ± : Type u_1} [topological_space Ξ±] : galois_insertion interior subtype.val := galois_insertion.mk (fun (s : order_dual (set Ξ±)) (hs : subtype.val (interior s) ≀ s) => { val := s, property := sorry }) sorry sorry sorry @[simp] theorem gi_choice_val {Ξ± : Type u_1} [topological_space Ξ±] {s : order_dual (set Ξ±)} {hs : subtype.val (interior s) ≀ s} : subtype.val (galois_insertion.choice gi s hs) = s := rfl protected instance complete_lattice {Ξ± : Type u_1} [topological_space Ξ±] : complete_lattice (opens Ξ±) := complete_lattice.copy (order_dual.complete_lattice (order_dual (opens Ξ±))) (fun (U V : opens Ξ±) => U βŠ† V) sorry { val := set.univ, property := is_open_univ } sorry { val := βˆ…, property := is_open_empty } sorry (fun (U V : opens Ξ±) => { val := ↑U βˆͺ ↑V, property := sorry }) sorry (fun (U V : opens Ξ±) => { val := ↑U ∩ ↑V, property := sorry }) sorry (fun (Us : set (opens Ξ±)) => { val := ⋃₀(coe '' Us), property := sorry }) sorry complete_lattice.Inf sorry /- le -/ (Ξ» U V, U βŠ† V) rfl /- top -/ ⟨set.univ, is_open_univ⟩ (subtype.ext_iff_val.mpr interior_univ.symm) /- bot -/ βŸ¨βˆ…, is_open_empty⟩ rfl /- sup -/ (Ξ» U V, βŸ¨β†‘U βˆͺ ↑V, is_open_union U.2 V.2⟩) rfl /- inf -/ (Ξ» U V, βŸ¨β†‘U ∩ ↑V, is_open_inter U.2 V.2⟩) begin funext, apply subtype.ext_iff_val.mpr, exact (is_open_inter U.2 V.2).interior_eq.symm, end /- Sup -/ (Ξ» Us, βŸ¨β‹ƒβ‚€ (coe '' Us), is_open_sUnion $ Ξ» U hU, by { rcases hU with ⟨⟨V, hV⟩, h, h'⟩, dsimp at h', subst h', exact hV}⟩) begin funext, apply subtype.ext_iff_val.mpr, simp [Sup_range], refl, end /- Inf -/ _ rfl lemma le_def {U V : opens Ξ±} : U ≀ V ↔ (U : set Ξ±) ≀ (V : set Ξ±) := by refl theorem le_def {Ξ± : Type u_1} [topological_space Ξ±] {U : opens Ξ±} {V : opens Ξ±} : U ≀ V ↔ ↑U ≀ ↑V := iff.refl (U ≀ V) @[simp] lemma mk_inf_mk {U V : set Ξ±} {hU : is_open U} {hV : is_open V} : (⟨U, hU⟩ βŠ“ ⟨V, hV⟩ : opens Ξ±) = ⟨U βŠ“ V, is_open_inter hU hV⟩ := rfl @[simp] theorem mk_inf_mk {Ξ± : Type u_1} [topological_space Ξ±] {U : set Ξ±} {V : set Ξ±} {hU : is_open U} {hV : is_open V} : { val := U, property := hU } βŠ“ { val := V, property := hV } = { val := U βŠ“ V, property := is_open_inter hU hV } := rfl @[simp,norm_cast] lemma coe_inf {U V : opens Ξ±} : ((U βŠ“ V : opens Ξ±) : set Ξ±) = (U : set Ξ±) βŠ“ (V : set Ξ±) := rfl @[simp] theorem coe_inf {Ξ± : Type u_1} [topological_space Ξ±] {U : opens Ξ±} {V : opens Ξ±} : ↑(U βŠ“ V) = ↑U βŠ“ ↑V := rfl instance : has_inter (opens Ξ±) := ⟨λ U V, U βŠ“ V⟩ instance : has_union (opens Ξ±) := ⟨λ U V, U βŠ” V⟩ protected instance has_inter {Ξ± : Type u_1} [topological_space Ξ±] : has_inter (opens Ξ±) := has_inter.mk fun (U V : opens Ξ±) => U βŠ“ V instance : has_emptyc (opens Ξ±) := ⟨βŠ₯⟩ protected instance has_union {Ξ± : Type u_1} [topological_space Ξ±] : has_union (opens Ξ±) := has_union.mk fun (U V : opens Ξ±) => U βŠ” V instance : inhabited (opens Ξ±) := βŸ¨βˆ…βŸ© protected instance has_emptyc {Ξ± : Type u_1} [topological_space Ξ±] : has_emptyc (opens Ξ±) := has_emptyc.mk βŠ₯ protected instance inhabited {Ξ± : Type u_1} [topological_space Ξ±] : Inhabited (opens Ξ±) := { default := βˆ… } @[simp] lemma inter_eq (U V : opens Ξ±) : U ∩ V = U βŠ“ V := rfl @[simp] lemma union_eq (U V : opens Ξ±) : U βˆͺ V = U βŠ” V := rfl @[simp] theorem inter_eq {Ξ± : Type u_1} [topological_space Ξ±] (U : opens Ξ±) (V : opens Ξ±) : U ∩ V = U βŠ“ V := rfl @[simp] lemma empty_eq : (βˆ… : opens Ξ±) = βŠ₯ := rfl @[simp] theorem union_eq {Ξ± : Type u_1} [topological_space Ξ±] (U : opens Ξ±) (V : opens Ξ±) : U βˆͺ V = U βŠ” V := rfl @[simp] theorem empty_eq {Ξ± : Type u_1} [topological_space Ξ±] : βˆ… = βŠ₯ := rfl @[simp] lemma Sup_s {Us : set (opens Ξ±)} : ↑(Sup Us) = ⋃₀ ((coe : _ β†’ set Ξ±) '' Us) := begin @[simp] theorem Sup_s {Ξ± : Type u_1} [topological_space Ξ±] {Us : set (opens Ξ±)} : ↑(Sup Us) = ⋃₀(coe '' Us) := sorry rw [@galois_connection.l_Sup (opens Ξ±) (set Ξ±) _ _ (coe : opens Ξ± β†’ set Ξ±) interior gc Us], rw [set.sUnion_image] end lemma supr_def {ΞΉ} (s : ΞΉ β†’ opens Ξ±) : (⨆ i, s i) = βŸ¨β‹ƒ i, s i, is_open_Union $ Ξ» i, (s i).2⟩ := by { ext, simp only [supr, opens.Sup_s, sUnion_image, bUnion_range], refl } theorem supr_def {Ξ± : Type u_1} [topological_space Ξ±] {ΞΉ : Sort u_2} (s : ΞΉ β†’ opens Ξ±) : (supr fun (i : ΞΉ) => s i) = { val := set.Union fun (i : ΞΉ) => ↑(s i), property := is_open_Union fun (i : ΞΉ) => subtype.property (s i) } := sorry @[simp] lemma supr_mk {ΞΉ} (s : ΞΉ β†’ set Ξ±) (h : Ξ  i, is_open (s i)) : (⨆ i, ⟨s i, h i⟩ : opens Ξ±) = βŸ¨β¨† i, s i, is_open_Union h⟩ := @[simp] theorem supr_mk {Ξ± : Type u_1} [topological_space Ξ±] {ΞΉ : Sort u_2} (s : ΞΉ β†’ set Ξ±) (h : βˆ€ (i : ΞΉ), is_open (s i)) : (supr fun (i : ΞΉ) => { val := s i, property := h i }) = { val := supr fun (i : ΞΉ) => s i, property := is_open_Union h } := sorry by { rw supr_def, simp } @[simp] lemma supr_s {ΞΉ} (s : ΞΉ β†’ opens Ξ±) : ((⨆ i, s i : opens Ξ±) : set Ξ±) = ⋃ i, s i := by simp [supr_def] @[simp] theorem supr_s {Ξ± : Type u_1} [topological_space Ξ±] {ΞΉ : Sort u_2} (s : ΞΉ β†’ opens Ξ±) : ↑(supr fun (i : ΞΉ) => s i) = set.Union fun (i : ΞΉ) => ↑(s i) := sorry theorem mem_supr {ΞΉ} {x : Ξ±} {s : ΞΉ β†’ opens Ξ±} : x ∈ supr s ↔ βˆƒ i, x ∈ s i := by { rw [←mem_coe], simp, } theorem mem_supr {Ξ± : Type u_1} [topological_space Ξ±] {ΞΉ : Sort u_2} {x : Ξ±} {s : ΞΉ β†’ opens Ξ±} : x ∈ supr s ↔ βˆƒ (i : ΞΉ), x ∈ s i := sorry lemma open_embedding_of_le {U V : opens Ξ±} (i : U ≀ V) : open_embedding (set.inclusion i) := theorem open_embedding_of_le {Ξ± : Type u_1} [topological_space Ξ±] {U : opens Ξ±} {V : opens Ξ±} (i : U ≀ V) : open_embedding (set.inclusion i) := open_embedding.mk (embedding.mk (inducing.mk (Eq.symm induced_compose)) (set.inclusion_injective i)) (eq.mpr (id (Eq._oldrec (Eq.refl (is_open (set.range (set.inclusion i)))) (set.range_inclusion i))) (is_open.preimage continuous_subtype_val (subtype.property U))) { inj := set.inclusion_injective i, induced := (@induced_compose _ _ _ _ (set.inclusion i) coe).symm, open_range := begin rw set.range_inclusion i, exact U.property.preimage continuous_subtype_val end, } def is_basis (B : set (opens Ξ±)) : Prop := is_topological_basis ((coe : _ β†’ set Ξ±) '' B) def is_basis {Ξ± : Type u_1} [topological_space Ξ±] (B : set (opens Ξ±)) := is_topological_basis (coe '' B) lemma is_basis_iff_nbhd {B : set (opens Ξ±)} : is_basis B ↔ βˆ€ {U : opens Ξ±} {x}, x ∈ U β†’ βˆƒ U' ∈ B, x ∈ U' ∧ U' βŠ† U := theorem is_basis_iff_nbhd {Ξ± : Type u_1} [topological_space Ξ±] {B : set (opens Ξ±)} : is_basis B ↔ βˆ€ {U : opens Ξ±} {x : Ξ±}, x ∈ U β†’ βˆƒ (U' : opens Ξ±), βˆƒ (H : U' ∈ B), x ∈ U' ∧ U' βŠ† U := sorry begin split; intro h, { rintros ⟨sU, hU⟩ x hx, rcases (mem_nhds_of_is_topological_basis h).mp (mem_nhds_sets hU hx) with ⟨sV, ⟨⟨V, H₁, Hβ‚‚βŸ©, hsV⟩⟩, refine ⟨V, H₁, _⟩, cases V, dsimp at Hβ‚‚, subst Hβ‚‚, exact hsV }, { refine is_topological_basis_of_open_of_nhds _ _, { rintros sU ⟨U, ⟨H₁, Hβ‚‚βŸ©βŸ©, subst Hβ‚‚, exact U.property }, { intros x sU hx hsU, rcases @h (⟨sU, hsU⟩ : opens Ξ±) x hx with ⟨V, hV, H⟩, exact ⟨V, ⟨V, hV, rfl⟩, H⟩ } } end lemma is_basis_iff_cover {B : set (opens Ξ±)} : is_basis B ↔ βˆ€ U : opens Ξ±, βˆƒ Us βŠ† B, U = Sup Us := theorem is_basis_iff_cover {Ξ± : Type u_1} [topological_space Ξ±] {B : set (opens Ξ±)} : is_basis B ↔ βˆ€ (U : opens Ξ±), βˆƒ (Us : set (opens Ξ±)), βˆƒ (H : Us βŠ† B), U = Sup Us := sorry begin split, { intros hB U, rcases sUnion_basis_of_is_open hB U.prop with ⟨sUs, H, hU⟩, existsi {U : opens Ξ± | U ∈ B ∧ ↑U ∈ sUs}, split, { intros U hU, exact hU.left }, { apply ext, rw [Sup_s, hU], congr' with s; split; intro hs, { rcases H hs with ⟨V, hV⟩, rw ← hV.right at hs, refine ⟨V, ⟨⟨hV.left, hs⟩, hV.right⟩⟩ }, { rcases hs with ⟨V, ⟨⟨H₁, Hβ‚‚βŸ©, Hβ‚ƒβŸ©βŸ©, subst H₃, exact Hβ‚‚ } } }, { intro h, rw is_basis_iff_nbhd, intros U x hx, rcases h U with ⟨Us, hUs, H⟩, replace H := congr_arg (coe : _ β†’ set Ξ±) H, rw Sup_s at H, change x ∈ ↑U at hx, rw H at hx, rcases set.mem_sUnion.mp hx with ⟨sV, ⟨⟨V, H₁, Hβ‚‚βŸ©, hsV⟩⟩, refine ⟨V,hUs H₁,_⟩, cases V with V hV, dsimp at Hβ‚‚, subst Hβ‚‚, refine ⟨hsV,_⟩, change V βŠ† U, rw H, exact set.subset_sUnion_of_mem ⟨⟨V, _⟩, ⟨H₁, rfl⟩⟩ } end /-- The preimage of an open set, as an open set. -/ def comap {f : Ξ± β†’ Ξ²} (hf : continuous f) (V : opens Ξ²) : opens Ξ± := ⟨f ⁻¹' V.1, V.2.preimage hf⟩ def comap {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] {f : Ξ± β†’ Ξ²} (hf : continuous f) (V : opens Ξ²) : opens Ξ± := { val := f ⁻¹' subtype.val V, property := sorry } @[simp] lemma comap_id (U : opens Ξ±) : U.comap continuous_id = U := by { ext, refl } @[simp] theorem comap_id {Ξ± : Type u_1} [topological_space Ξ±] (U : opens Ξ±) : comap continuous_id U = U := ext (set.ext fun (x : Ξ±) => iff.refl (x ∈ ↑(comap continuous_id U))) lemma comap_mono {f : Ξ± β†’ Ξ²} (hf : continuous f) {V W : opens Ξ²} (hVW : V βŠ† W) : V.comap hf βŠ† W.comap hf := theorem comap_mono {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] {f : Ξ± β†’ Ξ²} (hf : continuous f) {V : opens Ξ²} {W : opens Ξ²} (hVW : V βŠ† W) : comap hf V βŠ† comap hf W := fun (_x : Ξ±) (h : _x ∈ ↑(comap hf V)) => hVW h Ξ» _ h, hVW h @[simp] lemma coe_comap {f : Ξ± β†’ Ξ²} (hf : continuous f) (U : opens Ξ²) : ↑(U.comap hf) = f ⁻¹' U := rfl @[simp] theorem coe_comap {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] {f : Ξ± β†’ Ξ²} (hf : continuous f) (U : opens Ξ²) : ↑(comap hf U) = f ⁻¹' ↑U := rfl @[simp] lemma comap_val {f : Ξ± β†’ Ξ²} (hf : continuous f) (U : opens Ξ²) : (U.comap hf).1 = f ⁻¹' U := rfl @[simp] theorem comap_val {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] {f : Ξ± β†’ Ξ²} (hf : continuous f) (U : opens Ξ²) : subtype.val (comap hf U) = f ⁻¹' ↑U := rfl protected lemma comap_comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : continuous g) (hf : continuous f) (U : opens Ξ³) : U.comap (hg.comp hf) = (U.comap hg).comap hf := protected theorem comap_comp {Ξ± : Type u_1} {Ξ² : Type u_2} {Ξ³ : Type u_3} [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : continuous g) (hf : continuous f) (U : opens Ξ³) : comap (continuous.comp hg hf) U = comap hf (comap hg U) := sorry by { ext1, simp only [coe_comap, preimage_preimage] } /-- A homeomorphism induces an equivalence on open sets, by taking comaps. -/ @[simp] protected def equiv {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] (f : Ξ± β‰ƒβ‚œ Ξ²) : opens Ξ± ≃ opens Ξ² := equiv.mk (comap sorry) (comap (homeomorph.continuous f)) sorry sorry end opens /-- The open neighborhoods of a point. See also `opens` or `nhds`. -/ def open_nhds_of {Ξ± : Type u_1} [topological_space Ξ±] (x : Ξ±) := Subtype fun (s : set Ξ±) => is_open s ∧ x ∈ s protected instance open_nhds_of.inhabited {Ξ± : Type u_1} [topological_space Ξ±] (x : Ξ±) : Inhabited (open_nhds_of x) := { default := { val := set.univ, property := sorry } } end Mathlib
4a9685b175b9a7238c3e8f97bda4207b45b42d28
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/subgroup/pointwise.lean
ee899b4054625347ee60b55bd1deff0f6ab7e993
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
10,134
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.subgroup.basic import group_theory.submonoid.pointwise import group_theory.group_action.conj_act /-! # Pointwise instances on `subgroup` and `add_subgroup`s This file provides the actions * `subgroup.pointwise_mul_action` * `add_subgroup.pointwise_mul_action` which matches the action of `mul_action_set`. These actions are available in the `pointwise` locale. ## Implementation notes This file is almost identical to `group_theory/submonoid/pointwise.lean`. Where possible, try to keep them in sync. -/ open set variables {Ξ± : Type*} {G : Type*} {A : Type*} [group G] [add_group A] namespace subgroup section monoid variables [monoid Ξ±] [mul_distrib_mul_action Ξ± G] /-- The action on a subgroup corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action Ξ± (subgroup G) := { smul := Ξ» a S, S.map (mul_distrib_mul_action.to_monoid_End _ _ a), one_smul := Ξ» S, (congr_arg (Ξ» f, S.map f) (monoid_hom.map_one _)).trans S.map_id, mul_smul := Ξ» a₁ aβ‚‚ S, (congr_arg (Ξ» f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,} localized "attribute [instance] subgroup.pointwise_mul_action" in pointwise open_locale pointwise lemma pointwise_smul_def {a : Ξ±} (S : subgroup G) : a β€’ S = S.map (mul_distrib_mul_action.to_monoid_End _ _ a) := rfl @[simp] lemma coe_pointwise_smul (a : Ξ±) (S : subgroup G) : ↑(a β€’ S) = a β€’ (S : set G) := rfl @[simp] lemma pointwise_smul_to_submonoid (a : Ξ±) (S : subgroup G) : (a β€’ S).to_submonoid = a β€’ S.to_submonoid := rfl lemma smul_mem_pointwise_smul (m : G) (a : Ξ±) (S : subgroup G) : m ∈ S β†’ a β€’ m ∈ a β€’ S := (set.smul_mem_smul_set : _ β†’ _ ∈ a β€’ (S : set G)) lemma mem_smul_pointwise_iff_exists (m : G) (a : Ξ±) (S : subgroup G) : m ∈ a β€’ S ↔ βˆƒ (s : G), s ∈ S ∧ a β€’ s = m := (set.mem_smul_set : m ∈ a β€’ (S : set G) ↔ _) instance pointwise_central_scalar [mul_distrib_mul_action αᡐᡒᡖ G] [is_central_scalar Ξ± G] : is_central_scalar Ξ± (subgroup G) := ⟨λ a S, congr_arg (Ξ» f, S.map f) $ monoid_hom.ext $ by exact op_smul_eq_smul _⟩ lemma conj_smul_le_of_le {P H : subgroup G} (hP : P ≀ H) (h : H) : mul_aut.conj (h : G) β€’ P ≀ H := begin rintro - ⟨g, hg, rfl⟩, exact H.mul_mem (H.mul_mem h.2 (hP hg)) (H.inv_mem h.2), end lemma conj_smul_subgroup_of {P H : subgroup G} (hP : P ≀ H) (h : H) : mul_aut.conj h β€’ P.subgroup_of H = (mul_aut.conj (h : G) β€’ P).subgroup_of H := begin refine le_antisymm _ _, { rintro - ⟨g, hg, rfl⟩, exact ⟨g, hg, rfl⟩ }, { rintro p ⟨g, hg, hp⟩, exact ⟨⟨g, hP hg⟩, hg, subtype.ext hp⟩ }, end end monoid section group variables [group Ξ±] [mul_distrib_mul_action Ξ± G] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : Ξ±} {S : subgroup G} {x : G} : a β€’ x ∈ a β€’ S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : Ξ±} {S : subgroup G} {x : G} : x ∈ a β€’ S ↔ a⁻¹ β€’ x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : Ξ±} {S : subgroup G} {x : G} : x ∈ a⁻¹ β€’ S ↔ a β€’ x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : Ξ±} {S T : subgroup G} : a β€’ S ≀ a β€’ T ↔ S ≀ T := set_smul_subset_set_smul_iff lemma pointwise_smul_subset_iff {a : Ξ±} {S T : subgroup G} : a β€’ S ≀ T ↔ S ≀ a⁻¹ β€’ T := set_smul_subset_iff lemma subset_pointwise_smul_iff {a : Ξ±} {S T : subgroup G} : S ≀ a β€’ T ↔ a⁻¹ β€’ S ≀ T := subset_set_smul_iff /-- Applying a `mul_distrib_mul_action` results in an isomorphic subgroup -/ @[simps] def equiv_smul (a : Ξ±) (H : subgroup G) : H ≃* (a β€’ H : subgroup G) := (mul_distrib_mul_action.to_mul_equiv G a).subgroup_map H lemma subgroup_mul_singleton {H : subgroup G} {h : G} (hh : h ∈ H) : (H : set G) * {h} = H := begin refine le_antisymm _ (Ξ» h' hh', ⟨h' * h⁻¹, h, H.mul_mem hh' (H.inv_mem hh), rfl, inv_mul_cancel_right h' h⟩), rintros _ ⟨h', h, hh', rfl : _ = _, rfl⟩, exact H.mul_mem hh' hh, end lemma singleton_mul_subgroup {H : subgroup G} {h : G} (hh : h ∈ H) : {h} * (H : set G) = H := begin refine le_antisymm _ (Ξ» h' hh', ⟨h, h⁻¹ * h', rfl, H.mul_mem (H.inv_mem hh) hh', mul_inv_cancel_left h h'⟩), rintros _ ⟨h, h', rfl : _ = _, hh', rfl⟩, exact H.mul_mem hh hh', end lemma normal.conj_act {G : Type*} [group G] {H : subgroup G} (hH : H.normal ) (g : conj_act G) : g β€’ H = H := begin ext, split, { intro h, have := hH.conj_mem (g⁻¹ β€’ x) _ (conj_act.of_conj_act g), rw subgroup.mem_pointwise_smul_iff_inv_smul_mem at h, dsimp at *, rw conj_act.smul_def at *, simp only [conj_act.of_conj_act_inv, conj_act.of_conj_act_to_conj_act, inv_inv] at *, convert this, simp only [←mul_assoc, mul_right_inv, one_mul, mul_inv_cancel_right], rw subgroup.mem_pointwise_smul_iff_inv_smul_mem at h, exact h}, { intro h, rw [subgroup.mem_pointwise_smul_iff_inv_smul_mem, conj_act.smul_def], apply hH.conj_mem, exact h} end end group section group_with_zero variables [group_with_zero Ξ±] [mul_distrib_mul_action Ξ± G] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) (S : subgroup G) (x : G) : a β€’ x ∈ a β€’ S ↔ x ∈ S := smul_mem_smul_set_iffβ‚€ ha (S : set G) x lemma mem_pointwise_smul_iff_inv_smul_memβ‚€ {a : Ξ±} (ha : a β‰  0) (S : subgroup G) (x : G) : x ∈ a β€’ S ↔ a⁻¹ β€’ x ∈ S := mem_smul_set_iff_inv_smul_memβ‚€ ha (S : set G) x lemma mem_inv_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) (S : subgroup G) (x : G) : x ∈ a⁻¹ β€’ S ↔ a β€’ x ∈ S := mem_inv_smul_set_iffβ‚€ ha (S : set G) x @[simp] lemma pointwise_smul_le_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) {S T : subgroup G} : a β€’ S ≀ a β€’ T ↔ S ≀ T := set_smul_subset_set_smul_iffβ‚€ ha lemma pointwise_smul_le_iffβ‚€ {a : Ξ±} (ha : a β‰  0) {S T : subgroup G} : a β€’ S ≀ T ↔ S ≀ a⁻¹ β€’ T := set_smul_subset_iffβ‚€ ha lemma le_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) {S T : subgroup G} : S ≀ a β€’ T ↔ a⁻¹ β€’ S ≀ T := subset_set_smul_iffβ‚€ ha end group_with_zero end subgroup namespace add_subgroup section monoid variables [monoid Ξ±] [distrib_mul_action Ξ± A] /-- The action on an additive subgroup corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action Ξ± (add_subgroup A) := { smul := Ξ» a S, S.map (distrib_mul_action.to_add_monoid_End _ _ a), one_smul := Ξ» S, (congr_arg (Ξ» f, S.map f) (monoid_hom.map_one _)).trans S.map_id, mul_smul := Ξ» a₁ aβ‚‚ S, (congr_arg (Ξ» f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,} localized "attribute [instance] add_subgroup.pointwise_mul_action" in pointwise open_locale pointwise @[simp] lemma coe_pointwise_smul (a : Ξ±) (S : add_subgroup A) : ↑(a β€’ S) = a β€’ (S : set A) := rfl @[simp] lemma pointwise_smul_to_add_submonoid (a : Ξ±) (S : add_subgroup A) : (a β€’ S).to_add_submonoid = a β€’ S.to_add_submonoid := rfl lemma smul_mem_pointwise_smul (m : A) (a : Ξ±) (S : add_subgroup A) : m ∈ S β†’ a β€’ m ∈ a β€’ S := (set.smul_mem_smul_set : _ β†’ _ ∈ a β€’ (S : set A)) lemma mem_smul_pointwise_iff_exists (m : A) (a : Ξ±) (S : add_subgroup A) : m ∈ a β€’ S ↔ βˆƒ (s : A), s ∈ S ∧ a β€’ s = m := (set.mem_smul_set : m ∈ a β€’ (S : set A) ↔ _) instance pointwise_central_scalar [distrib_mul_action αᡐᡒᡖ A] [is_central_scalar Ξ± A] : is_central_scalar Ξ± (add_subgroup A) := ⟨λ a S, congr_arg (Ξ» f, S.map f) $ add_monoid_hom.ext $ by exact op_smul_eq_smul _⟩ end monoid section group variables [group Ξ±] [distrib_mul_action Ξ± A] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : Ξ±} {S : add_subgroup A} {x : A} : a β€’ x ∈ a β€’ S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : Ξ±} {S : add_subgroup A} {x : A} : x ∈ a β€’ S ↔ a⁻¹ β€’ x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : Ξ±} {S : add_subgroup A} {x : A} : x ∈ a⁻¹ β€’ S ↔ a β€’ x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : Ξ±} {S T : add_subgroup A} : a β€’ S ≀ a β€’ T ↔ S ≀ T := set_smul_subset_set_smul_iff lemma pointwise_smul_le_iff {a : Ξ±} {S T : add_subgroup A} : a β€’ S ≀ T ↔ S ≀ a⁻¹ β€’ T := set_smul_subset_iff lemma le_pointwise_smul_iff {a : Ξ±} {S T : add_subgroup A} : S ≀ a β€’ T ↔ a⁻¹ β€’ S ≀ T := subset_set_smul_iff end group section group_with_zero variables [group_with_zero Ξ±] [distrib_mul_action Ξ± A] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) (S : add_subgroup A) (x : A) : a β€’ x ∈ a β€’ S ↔ x ∈ S := smul_mem_smul_set_iffβ‚€ ha (S : set A) x lemma mem_pointwise_smul_iff_inv_smul_memβ‚€ {a : Ξ±} (ha : a β‰  0) (S : add_subgroup A) (x : A) : x ∈ a β€’ S ↔ a⁻¹ β€’ x ∈ S := mem_smul_set_iff_inv_smul_memβ‚€ ha (S : set A) x lemma mem_inv_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) (S : add_subgroup A) (x : A) : x ∈ a⁻¹ β€’ S ↔ a β€’ x ∈ S := mem_inv_smul_set_iffβ‚€ ha (S : set A) x @[simp] lemma pointwise_smul_le_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) {S T : add_subgroup A} : a β€’ S ≀ a β€’ T ↔ S ≀ T := set_smul_subset_set_smul_iffβ‚€ ha lemma pointwise_smul_le_iffβ‚€ {a : Ξ±} (ha : a β‰  0) {S T : add_subgroup A} : a β€’ S ≀ T ↔ S ≀ a⁻¹ β€’ T := set_smul_subset_iffβ‚€ ha lemma le_pointwise_smul_iffβ‚€ {a : Ξ±} (ha : a β‰  0) {S T : add_subgroup A} : S ≀ a β€’ T ↔ a⁻¹ β€’ S ≀ T := subset_set_smul_iffβ‚€ ha end group_with_zero end add_subgroup
abd5277212022a12a54b316fb804d3271ba3fb2d
4a894698f2ae3f991490c25af3c13ea4435dac48
/src/instructor/lectures/review_new_students.lean
b8c9fd866da447103b07ed9d57c5991bddee3a54
[]
no_license
gnujey/cs2120f21
8a33f636346d59ade049dcc1726634f434ac1955
138d43446c443c1d15cd2f17fb607c4f0dff702f
refs/heads/main
1,690,598,880,775
1,631,132,566,000
1,631,132,566,000
405,182,739
1
0
null
1,631,299,824,000
1,631,299,823,000
null
UTF-8
Lean
false
false
1,870
lean
/- DEFINITION -/ def x : β„• := 7 example : β„• := 5 /- PROPOSITION Any statement, claim, conjecture, that could have a truth value. -/ def ev (n : β„•) := n % 2 = 0 /- 5 is even -/ example : β„• := 5 example : ev 5 := begin unfold ev, -- give up, i'm stuck end /- 4 is even -/ example : ev 4 := begin unfold ev, exact (eq.refl 0), end /- PREDICATE: - Proposition with parameters. - A parameterized *family* of propositions -/ -- def ev (n : β„•) := n % 2 = 0 #reduce (ev 5) #reduce (ev 4) #reduce (ev 33) /- An axiom is a proposition whose truth we just assume, without any proof. -/ def z := begin exact 4 end def id_nat (n : β„•) := begin exact n, end #reduce id_nat 2 axiom equality_is_reflexive : βˆ€ (T : Type) (t : T), t = t #reduce equality_is_reflexive β„• 3 def three_equals_three : 3 = 3 := (eq.refl 3) def k : β„• := 5 example : βˆ€ (T : Type) (x y z : T), x = y β†’ y = z β†’ x = z := begin assume T, assume x y z, assume h1, assume h2, rw h1, exact h2, end /- Give an English language proof that for any x and y, if x = y then y = x. Proof: We'll assume we're given arbitrary but specific values of x and y, and in this context what remains to be proved is that if x = y then y = x. To prove this we first assume x = y, and in this context what now remains to be proved is y = x. To prove that y = x we can first apply the axiom of the substitutablity of equals for equals to rewrite y = x as y = y, justified by the assume that x = y. So what now remains to be proved is that y = y, and this is true by the application the axiom of reflexivity. QED. Proof. Rewrite y = x as y = y using substitutablity of equals then apply the axiom of reflexivity of equality. DONE. -/ /- Conjecture: There exist natural numbers, x, y, and z, all greater than 1, and n > 2, such that x^n + y^n = z^n. -/
4dbb93e3a929e228e521993bbdb7cb0f3d883ec2
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/Tactic/Revert.lean
6c8f488b349ba3da497db18119643528e8925561
[ "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
884
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Util namespace Lean.Meta def revert (mvarId : MVarId) (fvars : Array FVarId) (preserveOrder : Bool := false) : MetaM (Array FVarId Γ— MVarId) := do if fvars.isEmpty then pure (fvars, mvarId) else withMVarContext mvarId do let tag ← getMVarTag mvarId checkNotAssigned mvarId `revert -- Set metavariable kind to natural to make sure `elimMVarDeps` will assign it. setMVarKind mvarId MetavarKind.natural let e ← try elimMVarDeps (fvars.map mkFVar) (mkMVar mvarId) preserveOrder finally setMVarKind mvarId MetavarKind.syntheticOpaque e.withApp fun mvar args => do setMVarTag mvar.mvarId! tag pure (args.map Expr.fvarId!, mvar.mvarId!) end Lean.Meta
93d13e0fdf4e1dfddf8c4cb21e54b3bba049dc07
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/test/examples.lean
6d907777188aa22abce2bcac2005c9365c35816c
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
6,774
lean
import tactic data.stream.basic data.set.basic data.finset data.multiset category.traversable.derive meta.coinductive_predicates open tactic universe u variable {Ξ± : Type} example (s t u : set β„•) (h : s βŠ† t ∩ u) (h' : u βŠ† s) : u βŠ† s β†’ true := begin dunfold has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (s t u : set β„•) (h : s βŠ† t ∩ u) (h' : u βŠ† s) : u βŠ† s β†’ true := begin delta has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (x y z : β„•) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, -- trace_state, rw [←h, ←h'] end example (x y z : β„•) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, simp [h] at h', simp [*] end def my_id (x : Ξ±) := x def my_id_def (x : Ξ±) : my_id x = x := rfl example (x y z : β„•) (h'' : true) (h : 0 + my_id y = x) (h' : 0 + y = z) : x = z + 0 := begin simp [my_id_def] at *, simp [h] at h', simp [*] end @[simp] theorem mem_set_of {a : Ξ±} {p : Ξ± β†’ Prop} : a ∈ {a | p a} = p a := rfl -- TODO: write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set Ξ±} : (s βŠ† t) = βˆ€ x, x ∈ s β†’ x ∈ t := rfl theorem union_def {s₁ sβ‚‚ : set Ξ±} : s₁ βˆͺ sβ‚‚ = {a | a ∈ s₁ ∨ a ∈ sβ‚‚} := rfl theorem inter_def {s₁ sβ‚‚ : set Ξ±} : s₁ ∩ sβ‚‚ = {a | a ∈ s₁ ∧ a ∈ sβ‚‚} := rfl theorem union_subset {s t r : set Ξ±} (sr : s βŠ† r) (tr : t βŠ† r) : s βˆͺ t βŠ† r := begin dsimp [subset_def, union_def] at *, intros x h, cases h; back_chaining_using_hs end theorem subset_inter {s t r : set Ξ±} (rs : r βŠ† s) (rt : r βŠ† t) : r βŠ† s ∩ t := begin dsimp [subset_def, inter_def] at *, intros x h, split; back_chaining_using_hs end /- extensionality -/ example : true := begin have : βˆ€ (sβ‚€ s₁ : set β„€), sβ‚€ = s₁, { intros, ext1, guard_target x ∈ sβ‚€ ↔ x ∈ s₁, admit }, have : βˆ€ (sβ‚€ s₁ : finset β„•), sβ‚€ = s₁, { intros, ext1, guard_target a ∈ sβ‚€ ↔ a ∈ s₁, admit }, have : βˆ€ (sβ‚€ s₁ : multiset β„•), sβ‚€ = s₁, { intros, ext1, guard_target multiset.count a sβ‚€ = multiset.count a s₁, admit }, have : βˆ€ (sβ‚€ s₁ : list β„•), sβ‚€ = s₁, { intros, ext1, guard_target list.nth sβ‚€ n = list.nth s₁ n, admit }, have : βˆ€ (sβ‚€ s₁ : stream β„•), sβ‚€ = s₁, { intros, ext1, guard_target stream.nth n sβ‚€ = stream.nth n s₁, admit }, have : βˆ€ n (sβ‚€ s₁ : array n β„•), sβ‚€ = s₁, { intros, ext1, guard_target array.read sβ‚€ i = array.read s₁ i, admit }, trivial end /- choice -/ example (h : βˆ€n m : β„•, βˆƒi j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := β„• β†’ β„• β†’ β„•, guard_hyp j := β„• β†’ β„• β†’ β„•, guard_hyp h := βˆ€ (n m : β„•), m = n + i n m ∨ m + j n m = n, trivial end example (h : βˆ€n m : β„•, βˆƒi, βˆ€n:β„•, βˆƒj, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := β„• β†’ β„• β†’ β„•, guard_hyp j := β„• β†’ β„• β†’ β„• β†’ β„•, guard_hyp h := βˆ€ (n m k : β„•), m = k + i n m ∨ m + j n m k = k, trivial end -- Test `simp only [exists_prop]` gets applied after choosing. -- Because of this simp, we need a non-rfl goal example (h : βˆ€ n, βˆƒ k β‰₯ 0, n = k) : βˆ€ x : β„•, 1 = 1 := begin choose u hu using h, guard_hyp hu := βˆ€ n, u n β‰₯ 0 ∧ n = u n, intro, refl end /- refine_struct -/ section refine_struct variables {Ξ±} [_inst : monoid Ξ±] include _inst example : true := begin have : group Ξ±, { refine_struct { .._inst }, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, }, trivial end end refine_struct meta example : true := begin success_if_fail { let := compact_relation }, trivial end import_private compact_relation from tactic.coinduction meta example : true := begin let := compact_relation, trivial end meta example : true := begin success_if_fail { let := elim_gen_sum_aux }, trivial end import_private elim_gen_sum_aux meta example : true := begin let := elim_gen_sum_aux, trivial end /- traversable -/ open tactic.interactive run_cmd do lawful_traversable_derive_handler' `test ``(is_lawful_traversable) ``list -- the above creates local instances of `traversable` and `is_lawful_traversable` -- for `list` -- do not put in instances because they are not universe polymorphic @[derive [traversable, is_lawful_traversable]] structure my_struct (Ξ± : Type) := (y : β„€) @[derive [traversable, is_lawful_traversable]] inductive either (Ξ± : Type u) | left : Ξ± β†’ β„€ β†’ either | right : Ξ± β†’ either @[derive [traversable, is_lawful_traversable]] structure my_struct2 (Ξ± : Type u) : Type u := (x : Ξ±) (y : β„€) (Ξ· : list Ξ±) (k : list (list Ξ±)) @[derive [traversable, is_lawful_traversable]] inductive rec_data3 (Ξ± : Type u) : Type u | nil : rec_data3 | cons : β„• β†’ Ξ± β†’ rec_data3 β†’ rec_data3 β†’ rec_data3 @[derive traversable] meta structure meta_struct (Ξ± : Type u) : Type u := (x : Ξ±) (y : β„€) (z : list Ξ±) (k : list (list Ξ±)) (w : expr) @[derive [traversable,is_lawful_traversable]] inductive my_tree (Ξ± : Type) | leaf {} : my_tree | node : my_tree β†’ my_tree β†’ Ξ± β†’ my_tree section open my_tree (hiding traverse) def x : my_tree (list nat) := node leaf (node (node leaf leaf [1,2,3]) leaf [3,2]) [1] /-- demonstrate the nested use of `traverse`. It traverses each node of the tree and in each node, traverses each list. For each `β„•` visited, apply an action `β„• -> state (list β„•) unit` which adds its argument to the state. -/ def ex : state (list β„•) (my_tree $ list unit) := do xs ← traverse (traverse $ Ξ» a, modify $ list.cons a) x, pure xs example : (ex.run []).1 = node leaf (node (node leaf leaf [(), (), ()]) leaf [(), ()]) [()] := rfl example : (ex.run []).2 = [1, 2, 3, 3, 2, 1] := rfl example : is_lawful_traversable my_tree := my_tree.is_lawful_traversable end /- tests of has_sep on finset -/ example {Ξ±} (s : finset Ξ±) (p : Ξ± β†’ Prop) [decidable_pred p] : {x ∈ s | p x} = s.filter p := by simp example {Ξ±} (s : finset Ξ±) (p : Ξ± β†’ Prop) [decidable_pred p] : {x ∈ s | p x} = @finset.filter Ξ± p (Ξ» _, classical.prop_decidable _) s := by simp section open_locale classical example {Ξ±} (s : finset Ξ±) (p : Ξ± β†’ Prop) : {x ∈ s | p x} = s.filter p := by simp example (n m k : β„•) : {x ∈ finset.range n | x < m ∨ x < k } = {x ∈ finset.range n | x < m } βˆͺ {x ∈ finset.range n | x < k } := by simp [finset.filter_or] example : 1 = 1 := by { squeeze_simp } end open tactic
3f95c8726f9375c35904df687facf2688dce153c
82e44445c70db0f03e30d7be725775f122d72f3e
/src/combinatorics/simple_graph/degree_sum.lean
4c381fdc6738925a27043acc6b661354b16d526d
[ "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
8,336
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.basic import algebra.big_operators.basic import data.nat.parity import data.zmod.parity /-! # Degree-sum formula and handshaking lemma The degree-sum formula is that the sum of the degrees of the vertices in a finite graph is equal to twice the number of edges. The handshaking lemma, a corollary, is that the number of odd-degree vertices is even. ## Main definitions - A `dart` is a directed edge, consisting of an ordered pair of adjacent vertices, thought of as being a directed edge. - `simple_graph.sum_degrees_eq_twice_card_edges` is the degree-sum formula. - `simple_graph.even_card_odd_degree_vertices` is the handshaking lemma. - `simple_graph.odd_card_odd_degree_vertices_ne` is that the number of odd-degree vertices different from a given odd-degree vertex is odd. - `simple_graph.exists_ne_odd_degree_of_exists_odd_degree` is that the existence of an odd-degree vertex implies the existence of another one. ## Implementation notes We give a combinatorial proof by using the facts that (1) the map from darts to vertices is such that each fiber has cardinality the degree of the corresponding vertex and that (2) the map from darts to edges is 2-to-1. ## Tags simple graphs, sums, degree-sum formula, handshaking lemma -/ open finset open_locale big_operators namespace simple_graph universes u variables {V : Type u} (G : simple_graph V) /-- A dart is a directed edge, consisting of an ordered pair of adjacent vertices. -/ @[ext, derive decidable_eq] structure dart := (fst snd : V) (is_adj : G.adj fst snd) instance dart.fintype [fintype V] [decidable_rel G.adj] : fintype G.dart := fintype.of_equiv (Ξ£ v, G.neighbor_set v) { to_fun := Ξ» s, ⟨s.fst, s.snd, s.snd.property⟩, inv_fun := Ξ» d, ⟨d.fst, d.snd, d.is_adj⟩, left_inv := Ξ» s, by ext; simp, right_inv := Ξ» d, by ext; simp } variables {G} /-- The edge associated to the dart. -/ def dart.edge (d : G.dart) : sym2 V := ⟦(d.fst, d.snd)⟧ @[simp] lemma dart.edge_mem (d : G.dart) : d.edge ∈ G.edge_set := d.is_adj /-- The dart with reversed orientation from a given dart. -/ def dart.rev (d : G.dart) : G.dart := ⟨d.snd, d.fst, G.sym d.is_adj⟩ @[simp] lemma dart.rev_edge (d : G.dart) : d.rev.edge = d.edge := sym2.eq_swap @[simp] lemma dart.rev_rev (d : G.dart) : d.rev.rev = d := dart.ext _ _ rfl rfl @[simp] lemma dart.rev_involutive : function.involutive (dart.rev : G.dart β†’ G.dart) := dart.rev_rev lemma dart.rev_ne (d : G.dart) : d.rev β‰  d := begin cases d with f s h, simp only [dart.rev, not_and, ne.def], rintro rfl, exact false.elim (G.loopless _ h), end lemma dart_edge_eq_iff (d₁ dβ‚‚ : G.dart) : d₁.edge = dβ‚‚.edge ↔ d₁ = dβ‚‚ ∨ d₁ = dβ‚‚.rev := begin cases d₁ with s₁ t₁ h₁, cases dβ‚‚ with sβ‚‚ tβ‚‚ hβ‚‚, simp only [dart.edge, dart.rev_edge, dart.rev], rw sym2.eq_iff, end variables (G) /-- For a given vertex `v`, this is the bijective map from the neighbor set at `v` to the darts `d` with `d.fst = v`. --/ def dart_of_neighbor_set (v : V) (w : G.neighbor_set v) : G.dart := ⟨v, w, w.property⟩ lemma dart_of_neighbor_set_injective (v : V) : function.injective (G.dart_of_neighbor_set v) := Ξ» e₁ eβ‚‚ h, by { injection h with h₁ hβ‚‚, exact subtype.ext hβ‚‚ } instance dart.inhabited [inhabited V] [inhabited (G.neighbor_set (default _))] : inhabited G.dart := ⟨G.dart_of_neighbor_set (default _) (default _)⟩ section degree_sum variables [fintype V] [decidable_rel G.adj] lemma dart_fst_fiber [decidable_eq V] (v : V) : univ.filter (Ξ» d : G.dart, d.fst = v) = univ.image (G.dart_of_neighbor_set v) := begin ext d, simp only [mem_image, true_and, mem_filter, set_coe.exists, mem_univ, exists_prop_of_true], split, { rintro rfl, exact ⟨_, d.is_adj, dart.ext _ _ rfl rfl⟩, }, { rintro ⟨e, he, rfl⟩, refl, }, end lemma dart_fst_fiber_card_eq_degree [decidable_eq V] (v : V) : (univ.filter (Ξ» d : G.dart, d.fst = v)).card = G.degree v := begin have hh := card_image_of_injective univ (G.dart_of_neighbor_set_injective v), rw [finset.card_univ, card_neighbor_set_eq_degree] at hh, rwa dart_fst_fiber, end lemma dart_card_eq_sum_degrees : fintype.card G.dart = βˆ‘ v, G.degree v := begin haveI h : decidable_eq V := by { classical, apply_instance }, simp only [←card_univ, ←dart_fst_fiber_card_eq_degree], exact card_eq_sum_card_fiberwise (by simp), end variables {G} [decidable_eq V] lemma dart.edge_fiber (d : G.dart) : (univ.filter (Ξ» (d' : G.dart), d'.edge = d.edge)) = {d, d.rev} := finset.ext (Ξ» d', by simpa using dart_edge_eq_iff d' d) variables (G) lemma dart_edge_fiber_card (e : sym2 V) (h : e ∈ G.edge_set) : (univ.filter (Ξ» (d : G.dart), d.edge = e)).card = 2 := begin refine quotient.ind (Ξ» p h, _) e h, cases p with v w, let d : G.dart := ⟨v, w, h⟩, convert congr_arg card d.edge_fiber, rw [card_insert_of_not_mem, card_singleton], rw [mem_singleton], exact d.rev_ne.symm, end lemma dart_card_eq_twice_card_edges : fintype.card G.dart = 2 * G.edge_finset.card := begin rw ←card_univ, rw @card_eq_sum_card_fiberwise _ _ _ dart.edge _ G.edge_finset (Ξ» d h, by { rw mem_edge_finset, apply dart.edge_mem }), rw [←mul_comm, sum_const_nat], intros e h, apply G.dart_edge_fiber_card e, rwa ←mem_edge_finset, end /-- The degree-sum formula. This is also known as the handshaking lemma, which might more specifically refer to `simple_graph.even_card_odd_degree_vertices`. -/ theorem sum_degrees_eq_twice_card_edges : βˆ‘ v, G.degree v = 2 * G.edge_finset.card := G.dart_card_eq_sum_degrees.symm.trans G.dart_card_eq_twice_card_edges end degree_sum /-- The handshaking lemma. See also `simple_graph.sum_degrees_eq_twice_card_edges`. -/ theorem even_card_odd_degree_vertices [fintype V] [decidable_rel G.adj] : even (univ.filter (Ξ» v, odd (G.degree v))).card := begin classical, have h := congr_arg ((Ξ» n, ↑n) : β„• β†’ zmod 2) G.sum_degrees_eq_twice_card_edges, simp only [zmod.nat_cast_self, zero_mul, nat.cast_mul] at h, rw [nat.cast_sum, ←sum_filter_ne_zero] at h, rw @sum_congr _ _ _ _ (Ξ» v, (G.degree v : zmod 2)) (Ξ» v, (1 : zmod 2)) _ rfl at h, { simp only [filter_congr_decidable, mul_one, nsmul_eq_mul, sum_const, ne.def] at h, rw ←zmod.eq_zero_iff_even, convert h, ext v, rw ←zmod.ne_zero_iff_odd, congr' }, { intros v, simp only [true_and, mem_filter, mem_univ, ne.def], rw [zmod.eq_zero_iff_even, zmod.eq_one_iff_odd, nat.odd_iff_not_even, imp_self], trivial } end lemma odd_card_odd_degree_vertices_ne [fintype V] [decidable_eq V] [decidable_rel G.adj] (v : V) (h : odd (G.degree v)) : odd (univ.filter (Ξ» w, w β‰  v ∧ odd (G.degree w))).card := begin rcases G.even_card_odd_degree_vertices with ⟨k, hg⟩, have hk : 0 < k, { have hh : (filter (Ξ» (v : V), odd (G.degree v)) univ).nonempty, { use v, simp only [true_and, mem_filter, mem_univ], use h, }, rwa [←card_pos, hg, zero_lt_mul_left] at hh, exact zero_lt_two, }, have hc : (Ξ» (w : V), w β‰  v ∧ odd (G.degree w)) = (Ξ» (w : V), odd (G.degree w) ∧ w β‰  v), { ext w, rw and_comm, }, simp only [hc, filter_congr_decidable], rw [←filter_filter, filter_ne', card_erase_of_mem], { use k - 1, rw [nat.pred_eq_succ_iff, hg, nat.mul_sub_left_distrib, ← nat.sub_add_comm, eq_comm, ← (nat.sub_eq_iff_eq_add _).symm], { ring }, { exact add_le_add_right (zero_le (2 * k)) 2 }, { exact nat.mul_le_mul_left _ hk } }, { simpa only [true_and, mem_filter, mem_univ] }, end lemma exists_ne_odd_degree_of_exists_odd_degree [fintype V] [decidable_rel G.adj] (v : V) (h : odd (G.degree v)) : βˆƒ (w : V), w β‰  v ∧ odd (G.degree w) := begin haveI : decidable_eq V := by { classical, apply_instance }, rcases G.odd_card_odd_degree_vertices_ne v h with ⟨k, hg⟩, have hg' : (filter (Ξ» (w : V), w β‰  v ∧ odd (G.degree w)) univ).card > 0, { rw hg, apply nat.succ_pos, }, rcases card_pos.mp hg' with ⟨w, hw⟩, simp only [true_and, mem_filter, mem_univ, ne.def] at hw, exact ⟨w, hw⟩, end end simple_graph
aea3e7739451bad500a859362fc70d864690645c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/succ_pred/limit.lean
f3033b25fb13db6a0c4f659ab9d66d26d0859317
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
10,453
lean
/- Copyright (c) 2022 Violeta HernΓ‘ndez Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta HernΓ‘ndez Palacios -/ import order.succ_pred.basic /-! # Successor and predecessor limits We define the predicate `order.is_succ_limit` for "successor limits", values that aren't successors, except possibly of themselves. We define `order.is_pred_limit` analogously, and prove basic results. ## Todo The plan is to eventually replace `ordinal.is_limit` and `cardinal.is_limit` with the common predicate `order.is_succ_limit`. -/ variables {Ξ± : Type*} {a b : Ξ±} open function set /-! ### Successor limits -/ namespace order section preorder variables [preorder Ξ±] [succ_order Ξ±] /-- A successor limit is a value that isn't a successor, except possibly of itself. -/ def is_succ_limit (a : Ξ±) : Prop := βˆ€ b, succ b = a β†’ is_max b protected lemma is_succ_limit.is_max (h : is_succ_limit (succ a)) : is_max a := h a rfl lemma not_is_succ_limit_succ_of_not_is_max (ha : Β¬ is_max a) : Β¬ is_succ_limit (succ a) := Ξ» h, ha (h a rfl) protected lemma _root_.is_min.is_succ_limit (h : is_min a) : is_succ_limit a := by { rintros b rfl, exact max_of_succ_le (h $ le_succ b) } lemma is_succ_limit_of_succ_ne (h : βˆ€ b, succ b β‰  a) : is_succ_limit a := Ξ» b hb, (h _ hb).elim lemma not_is_succ_limit_iff : Β¬ is_succ_limit a ↔ βˆƒ b, Β¬ is_max b ∧ succ b = a := by simp [is_succ_limit, and_comm] /-- See `order.not_is_succ_limit_iff` for a version that states that `a` is a successor of a value other than itself. -/ lemma mem_range_succ_of_not_is_succ_limit (h : Β¬ is_succ_limit a) : a ∈ range (@succ Ξ± _ _) := by { cases not_is_succ_limit_iff.1 h with b hb, exact ⟨b, hb.2⟩ } lemma is_succ_limit_of_succ_lt (H : βˆ€ a < b, succ a < b) : is_succ_limit b := by { rintros a rfl, by_contra ha, exact (H a $ lt_succ_of_not_is_max ha).false } /-- A value can be built by building it on successors and successor limits. Note that you need a partial order for data built using this to behave nicely on successors. -/ @[elab_as_eliminator] noncomputable def is_succ_limit_rec_on {C : Ξ± β†’ Sort*} (b) (hs : Ξ  a, Β¬ is_max a β†’ C (succ a)) (hl : Ξ  a, is_succ_limit a β†’ C a) : C b := begin by_cases hb : is_succ_limit b, { exact hl b hb }, { have H := classical.some_spec (not_is_succ_limit_iff.1 hb), rw ←H.2, exact hs _ H.1 } end lemma is_succ_limit_rec_on_limit {C : Ξ± β†’ Sort*} (hs : Ξ  a, Β¬ is_max a β†’ C (succ a)) (hl : Ξ  a, is_succ_limit a β†’ C a) (hb : is_succ_limit b) : @is_succ_limit_rec_on Ξ± _ _ C b hs hl = hl b hb := by { classical, exact dif_pos hb } section no_max_order variables [no_max_order Ξ±] lemma is_succ_limit.succ_ne (h : is_succ_limit a) (b) : succ b β‰  a := Ξ» hb, not_is_max b (h b hb) @[simp] lemma not_is_succ_limit_succ (a : Ξ±) : Β¬ is_succ_limit (succ a) := Ξ» h, h.succ_ne _ rfl lemma is_succ_limit_iff_succ_ne : is_succ_limit a ↔ βˆ€ b, succ b β‰  a := ⟨is_succ_limit.succ_ne, is_succ_limit_of_succ_ne⟩ lemma not_is_succ_limit_iff' : Β¬ is_succ_limit a ↔ a ∈ range (@succ Ξ± _ _) := by { simp_rw [is_succ_limit_iff_succ_ne, not_forall, not_ne_iff], refl } end no_max_order section order_bot variable [order_bot Ξ±] lemma is_succ_limit_bot : is_succ_limit (βŠ₯ : Ξ±) := is_min_bot.is_succ_limit end order_bot section is_succ_archimedean variable [is_succ_archimedean Ξ±] lemma is_succ_limit.is_min_of_no_max [no_max_order Ξ±] (h : is_succ_limit a) : is_min a := Ξ» b hb, begin rcases hb.exists_succ_iterate with ⟨_ | n, rfl⟩, { exact le_rfl }, { rw iterate_succ_apply' at h, exact (not_is_succ_limit_succ _ h).elim } end @[simp] lemma is_succ_limit_iff_of_no_max [no_max_order Ξ±] : is_succ_limit a ↔ is_min a := ⟨is_succ_limit.is_min_of_no_max, is_min.is_succ_limit⟩ lemma not_is_succ_limit_of_no_max [no_min_order Ξ±] [no_max_order Ξ±] : Β¬ is_succ_limit a := by simp end is_succ_archimedean end preorder section partial_order variables [partial_order Ξ±] [succ_order Ξ±] lemma is_succ_limit.succ_lt (hb : is_succ_limit b) (ha : a < b) : succ a < b := begin by_cases h : is_max a, { rwa h.succ_eq }, { rw [lt_iff_le_and_ne, succ_le_iff_of_not_is_max h], refine ⟨ha, Ξ» hab, _⟩, subst hab, exact (h hb.is_max).elim } end lemma is_succ_limit.succ_lt_iff (hb : is_succ_limit b) : succ a < b ↔ a < b := ⟨λ h, (le_succ a).trans_lt h, hb.succ_lt⟩ lemma is_succ_limit_iff_succ_lt : is_succ_limit b ↔ βˆ€ a < b, succ a < b := ⟨λ hb a, hb.succ_lt, is_succ_limit_of_succ_lt⟩ lemma is_succ_limit_rec_on_succ' {C : Ξ± β†’ Sort*} (hs : Ξ  a, Β¬ is_max a β†’ C (succ a)) (hl : Ξ  a, is_succ_limit a β†’ C a) {b : Ξ±} (hb : Β¬ is_max b) : @is_succ_limit_rec_on Ξ± _ _ C (succ b) hs hl = hs b hb := begin have hb' := not_is_succ_limit_succ_of_not_is_max hb, have H := classical.some_spec (not_is_succ_limit_iff.1 hb'), rw is_succ_limit_rec_on, simp only [cast_eq_iff_heq, hb', not_false_iff, eq_mpr_eq_cast, dif_neg], congr, { exact (succ_eq_succ_iff_of_not_is_max H.1 hb).1 H.2 }, { apply proof_irrel_heq } end section no_max_order variables [no_max_order Ξ±] @[simp] lemma is_succ_limit_rec_on_succ {C : Ξ± β†’ Sort*} (hs : Ξ  a, Β¬ is_max a β†’ C (succ a)) (hl : Ξ  a, is_succ_limit a β†’ C a) (b : Ξ±) : @is_succ_limit_rec_on Ξ± _ _ C (succ b) hs hl = hs b (not_is_max b) := is_succ_limit_rec_on_succ' _ _ _ end no_max_order section is_succ_archimedean variable [is_succ_archimedean Ξ±] protected lemma is_succ_limit.is_min (h : is_succ_limit a) : is_min a := Ξ» b hb, begin revert h, refine succ.rec (Ξ» _, le_rfl) (Ξ» c hbc H hc, _) hb, have := hc.is_max.succ_eq, rw this at hc ⊒, exact H hc end @[simp] lemma is_succ_limit_iff : is_succ_limit a ↔ is_min a := ⟨is_succ_limit.is_min, is_min.is_succ_limit⟩ lemma not_is_succ_limit [no_min_order Ξ±] : Β¬ is_succ_limit a := by simp end is_succ_archimedean end partial_order /-! ### Predecessor limits -/ section preorder variables [preorder Ξ±] [pred_order Ξ±] /-- A predecessor limit is a value that isn't a predecessor, except possibly of itself. -/ def is_pred_limit (a : Ξ±) : Prop := βˆ€ b, pred b = a β†’ is_min b protected lemma is_pred_limit.is_min (h : is_pred_limit (pred a)) : is_min a := h a rfl lemma not_is_pred_limit_pred_of_not_is_min (ha : Β¬ is_min a) : Β¬ is_pred_limit (pred a) := Ξ» h, ha (h a rfl) protected lemma _root_.is_max.is_pred_limit : is_max a β†’ is_pred_limit a := @is_min.is_succ_limit Ξ±α΅’α΅ˆ a _ _ lemma is_pred_limit_of_pred_ne (h : βˆ€ b, pred b β‰  a) : is_pred_limit a := Ξ» b hb, (h _ hb).elim lemma not_is_pred_limit_iff : Β¬ is_pred_limit a ↔ βˆƒ b, Β¬ is_min b ∧ pred b = a := @not_is_succ_limit_iff Ξ±α΅’α΅ˆ _ _ _ /-- See `order.not_is_pred_limit_iff` for a version that states that `a` is a predecessor of a value other than itself. -/ lemma mem_range_pred_of_not_is_pred_limit : Β¬ is_pred_limit a β†’ a ∈ range (@pred Ξ± _ _) := @mem_range_succ_of_not_is_succ_limit Ξ±α΅’α΅ˆ _ _ _ lemma is_pred_limit_of_lt_pred : (βˆ€ b > a, a < pred b) β†’ is_pred_limit a := @is_succ_limit_of_succ_lt Ξ±α΅’α΅ˆ a _ _ /-- A value can be built by building it on predecessors and predecessor limits. Note that you need a partial order for data built using this to behave nicely on successors. -/ @[elab_as_eliminator] noncomputable def is_pred_limit_rec_on : Ξ  {C : Ξ± β†’ Sort*} (b) (hs : Ξ  a, Β¬ is_min a β†’ C (pred a)) (hl : Ξ  a, is_pred_limit a β†’ C a), C b := @is_succ_limit_rec_on Ξ±α΅’α΅ˆ _ _ theorem is_pred_limit_rec_on_limit : Ξ  {C : Ξ± β†’ Sort*} (hs : Ξ  a, Β¬ is_min a β†’ C (pred a)) (hl : Ξ  a, is_pred_limit a β†’ C a) (hb : is_pred_limit b), @is_pred_limit_rec_on Ξ± _ _ C b hs hl = hl b hb := @is_succ_limit_rec_on_limit Ξ±α΅’α΅ˆ b _ _ section no_min_order variables [no_min_order Ξ±] lemma is_pred_limit.pred_ne (h : is_pred_limit a) (b) : pred b β‰  a := Ξ» hb, not_is_min b (h b hb) @[simp] lemma not_is_pred_limit_pred (a : Ξ±) : Β¬ is_pred_limit (pred a) := Ξ» h, h.pred_ne _ rfl lemma is_pred_limit_iff_pred_ne : is_pred_limit a ↔ βˆ€ b, pred b β‰  a := @is_succ_limit_iff_succ_ne Ξ±α΅’α΅ˆ a _ _ _ lemma not_is_pred_limit_iff' : Β¬ is_pred_limit a ↔ a ∈ range (@pred Ξ± _ _) := @not_is_succ_limit_iff' Ξ±α΅’α΅ˆ a _ _ _ end no_min_order section order_top variable [order_top Ξ±] lemma is_pred_limit_top : is_pred_limit (⊀ : Ξ±) := is_max_top.is_pred_limit end order_top section is_pred_archimedean variable [is_pred_archimedean Ξ±] protected lemma is_pred_limit.is_max_of_no_min [no_min_order Ξ±] : is_pred_limit a β†’ is_max a := @is_succ_limit.is_min_of_no_max Ξ±α΅’α΅ˆ a _ _ _ _ @[simp] lemma is_pred_limit_iff_of_no_min [no_min_order Ξ±] : is_pred_limit a ↔ is_max a := @is_succ_limit_iff_of_no_max Ξ±α΅’α΅ˆ a _ _ _ _ lemma not_is_pred_limit_of_no_min [no_min_order Ξ±] [no_max_order Ξ±] : Β¬ is_pred_limit a := by simp end is_pred_archimedean end preorder section partial_order variables [partial_order Ξ±] [pred_order Ξ±] lemma is_pred_limit.lt_pred : βˆ€ (ha : is_pred_limit a), a < b β†’ a < pred b := @is_succ_limit.succ_lt Ξ±α΅’α΅ˆ b a _ _ lemma is_pred_limit.lt_pred_iff : βˆ€ (ha : is_pred_limit a), a < pred b ↔ a < b := @is_succ_limit.succ_lt_iff Ξ±α΅’α΅ˆ b a _ _ lemma is_pred_limit_iff_lt_pred : is_pred_limit a ↔ βˆ€ b > a, a < pred b := @is_succ_limit_iff_succ_lt Ξ±α΅’α΅ˆ a _ _ lemma is_pred_limit_rec_on_pred' : βˆ€ {C : Ξ± β†’ Sort*} (hs : Ξ  a, Β¬ is_min a β†’ C (pred a)) (hl : Ξ  a, is_pred_limit a β†’ C a) {b : Ξ±} (hb : Β¬ is_min b), @is_pred_limit_rec_on Ξ± _ _ C (pred b) hs hl = hs b hb := @is_succ_limit_rec_on_succ' Ξ±α΅’α΅ˆ _ _ section no_min_order variables [no_min_order Ξ±] @[simp] theorem is_pred_limit_rec_on_pred : βˆ€ {C : Ξ± β†’ Sort*} (hs : Ξ  a, Β¬ is_min a β†’ C (pred a)) (hl : Ξ  a, is_pred_limit a β†’ C a) (b : Ξ±), @is_pred_limit_rec_on Ξ± _ _ C (pred b) hs hl = hs b (not_is_min b) := @is_succ_limit_rec_on_succ Ξ±α΅’α΅ˆ _ _ _ end no_min_order section is_pred_archimedean variable [is_pred_archimedean Ξ±] protected lemma is_pred_limit.is_max : is_pred_limit a β†’ is_max a := @is_succ_limit.is_min Ξ±α΅’α΅ˆ a _ _ _ @[simp] lemma is_pred_limit_iff : is_pred_limit a ↔ is_max a := @is_succ_limit_iff Ξ±α΅’α΅ˆ a _ _ _ lemma not_is_pred_limit [no_max_order Ξ±] : Β¬ is_pred_limit a := by simp end is_pred_archimedean end partial_order end order
cf64a15e5edb033c476aa769a2327f2cd2898f39
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170802-decidable_prime.lean
5021f95e390fb16ac8c9bdbe9532cee70e82f290
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
443
lean
def decidable_and ( P Q : Prop ) [decidable P] [decidable Q]: decidable (P ∧ Q) := begin induction _inst_1, let b : ¬ (P ∧ Q) := by cc, exact (is_false b), induction _inst_2, let b : ¬ (P ∧ Q) := by cc, exact (is_false b), let b : P ∧ Q := by cc, exact (is_true b) end instance decidable_prime : decidable_pred prime := begin unfold decidable_pred, intros, unfold prime, apply @decidable_and _ _ _ _, end
3191baaeea691c7924903cdad67713a941d78526
bdb33f8b7ea65f7705fc342a178508e2722eb851
/tactic/interactive.lean
3d768afc7a055c72e02ca82bb3cdb8e7004f8432
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
12,880
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.dlist tactic.basic tactic.rcases tactic.generalize_proofs meta.expr open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr meta def rcases_parse : parser (list rcases_patt) := with_desc "patt" $ let p := (rcases_patt.one <$> ident_) <|> (rcases_patt.many <$> brackets "⟨" "⟩" (sep_by (tk ",") rcases_parse)) in list.cons <$> p <*> (tk "|" *> p)* meta def rcases_parse.invert : list rcases_patt β†’ list (list rcases_patt) := let invert' (l : list rcases_patt) : rcases_patt := match l with | [k] := k | _ := rcases_patt.many (rcases_parse.invert l) end in list.map $ Ξ» p, match p with | rcases_patt.one n := [rcases_patt.one n] | rcases_patt.many l := invert' <$> l end /-- The `rcases` tactic is the same as `cases`, but with more flexibility in the `with` pattern syntax to allow for recursive case splitting. The pattern syntax uses the following recursive grammar: ``` patt ::= (patt_list "|")* patt_list patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩" ``` A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `βˆƒ x, βˆƒ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. -/ meta def rcases (p : parse texpr) (ids : parse (tk "with" *> rcases_parse)?) : tactic unit := tactic.rcases p $ rcases_parse.invert $ ids.get_or_else [default _] /-- This is a "finishing" tactic modification of `simp`. The tactic `simpa [rules, ...] using e` will simplify the hypothesis `e` using `rules`, then simplify the goal using `rules`, and try to close the goal using `assumption`. If `e` is a term instead of a local constant, it is first added to the local context using `have`. -/ meta def simpa (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit := let simp_at (lc) := simp use_iota_eqn no_dflt hs attr_names (loc.ns lc) cfg >> try (assumption <|> trivial) in match tgt with | none := get_local `this >> simp_at [some `this, none] <|> simp_at [none] | some e := (do e ← i_to_expr e, match e with | local_const _ lc _ _ := simp_at [some lc, none] | e := do t ← infer_type e, assertv `this t e >> simp_at [some `this, none] end) <|> (do simp_at [none], ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), -- for positional error messages, don't care about the result pty ← pp ty, ptgt ← pp e, -- Fail deliberately, to advise regarding `simp; exact` usage fail ("simpa failed, 'using' expression type not directly " ++ "inferrable. Try:\n\nsimpa ... using\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format)) end /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, tactic.try_for max tac <|> (tactic.trace "try_for timeout, using sorry" >> admit) /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (Ξ» h, get_local h >>= tactic.subst) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [``coe,``lift_t,``has_lift_t.lift,``coe_t,``has_coe_t.coe,``coe_b,``has_coe.coe, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := do r ← tactic.result, tactic.set_goals $ r.fold [] $ Ξ» e _ l, match e with | expr.mvar _ _ _ := insert e l | _ := l end /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := Ξ» s, result.cases_on (tac s) (Ξ» a, result.success ()) (Ξ» e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := if n = 2 then tactic.swap else tactic.rotate (n-1) /-- Generalize proofs in the goal, naming them with the provided list. -/ meta def generalize_proofs : parse ident_* β†’ tactic unit := tactic.generalize_proofs /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ Ξ» h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (Β¬ cl), tactic.clear h /-- Same as the `congr` tactic, but only works up to depth `n`. This is useful when the `congr` tactic is too aggressive in breaking down the goal. For example, given `⊒ f (g (x + y)) = f (g (y + x))`, `congr` produces the goals `⊒ x = y` and `⊒ y = x`, while `congr_n 2` produces the intended `⊒ x + y = y + x`. -/ meta def congr_n : nat β†’ tactic unit | 0 := failed | (n+1) := focus1 (try assumption >> congr_core >> all_goals (try reflexivity >> try (congr_n n))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊒ goal` and `f : p β†’ q`, then after `replace h := f h` the goal will be `h : q ⊒ goal`, where `have h := f h` would result in the state `h : p, h : q ⊒ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (qβ‚‚ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), Β«haveΒ» h q₁ qβ‚‚, match old, qβ‚‚ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- Unfreeze local instances, which allows us to revert instances in the context. -/ meta def unfreezeI := tactic.unfreeze_local_instances /-- Reset the instance cache. This allows any new instances added to the context to be used in typeclass inference. -/ meta def resetI := reset_instance_cache /-- Like `intro`, but uses the introduced variable in typeclass inference. -/ meta def introI (p : parse ident_?) : tactic unit := intro p >> reset_instance_cache /-- Like `intros`, but uses the introduced variable(s) in typeclass inference. -/ meta def introsI (p : parse ident_*) : tactic unit := intros p >> reset_instance_cache /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `have`, but the proof-omitted version is not supported. For this one must write `have : t, { <proof> }, resetI, <proof>`. -/ meta def haveI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (qβ‚‚ : parse (tk ":=" *> texpr)) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, Β«haveΒ» (some h) q₁ (some qβ‚‚), match q₁ with | none := swap >> reset_instance_cache >> swap | some pβ‚‚ := reset_instance_cache end /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `let`. -/ meta def letI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (qβ‚‚ : parse $ (tk ":=" *> texpr)?) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, Β«letΒ» (some h) q₁ qβ‚‚, match q₁ with | none := swap >> reset_instance_cache >> swap | some pβ‚‚ := reset_instance_cache end /-- Like `exact`, but uses all variables in the context for typeclass inference. -/ meta def exactI (q : parse texpr) : tactic unit := reset_instance_cache >> exact q /-- `apply_assumption` looks for an assumption of the form `... β†’ βˆ€ _, ... β†’ head` where `head` matches the current goal. alternatively, when encountering an assumption of the form `sgβ‚€ β†’ Β¬ sg₁`, after the main approach failed, the goal is dismissed and `sgβ‚€` and `sg₁` are made into the new goal. optional arguments: - asms: list of rules to consider instead of the local constants - tac: a tactic to run on each subgoals after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (asms : option (list expr) := none) (tac : tactic unit := return ()) : tactic unit := do { ctx ← asms.to_monad <|> local_context, t ← target, hs ← find_matching_head t ctx, hs.any_of (Ξ» H, () <$ tactic.apply H ; tac) } <|> do { exfalso, ctx ← asms.to_monad <|> local_context, t ← target, hs ← find_matching_head t ctx, hs.any_of (Ξ» H, () <$ tactic.apply H ; tac) } <|> fail "assumption tactic failed" open nat /-- `solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches and repeated calls `apply_assumption` on the generated subgoals until no subgoals remains or up to `depth` times. `solve_by_elim` discharges the current goal or fails `solve_by_elim` does some back-tracking if `apply_assumption` chooses an unproductive assumption optional arguments: - asms: list of assumptions / rules to consider instead of local constants - depth: number of attempts at discharging generated sub-goals -/ meta def solve_by_elim (asms : option (list expr) := none) : opt_param β„• 3 β†’ tactic unit | 0 := done | (succ n) := apply_assumption asms $ solve_by_elim n /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `βˆƒ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `βˆƒ _, _` until it can be discharged using `reflexivity` or `solve_by_elim` -/ meta def tautology : tactic unit := repeat (do gs ← get_goals, () <$ tactic.intros ; casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _)] ; constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _)], gs' ← get_goals, guard (gs β‰  gs') ) ; repeat (reflexivity <|> solve_by_elim <|> constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _)]) ; done /-- Shorter name for the tactic `tautology`. -/ meta def tauto := tautology /-- `wlog h : i ≀ j using i j`: without loss of generality, let us assume `h : i ≀ j` If `using i j` is omitted, the last two free variables found in `i ≀ j` will be used. `wlog : R x y` (synonymous with `wlog : R x y using x y`) adds `R x y` to the assumptions and the goal `⊒ R x y ∨ R y x`. A special case is made for total order relations `≀` where `⊒ R x y ∨ R y x` is discharged automatically. TODO(Simon): Generalize to multiple pairs of variables -/ meta def wlog (h : parse ident?) (p : parse (tk ":" *> texpr)) (xy : parse (tk "using" *> monad.sequence [ident,ident])?) : tactic unit := do p' ← to_expr p, (x :: y :: _) ← xy.to_monad >>= mmap get_local <|> pure p'.list_local_const, n ← tactic.revert_lst [x,y], x ← intro1, y ← intro1, p ← to_expr p, when (Β¬ x.occurs p ∨ Β¬ x.occurs p) (do p ← pp p, fail format!"{p} should reference {x} and {y}"), let p' := subst_locals [(x,y),(y,x)] p, t ← target, let g := p.imp t, g ← tactic.pis [x,y] g, this ← assert `this (set_binder g [binder_info.default,binder_info.default]), tactic.clear x, tactic.clear y, intron 2, intro $ h.get_or_else `a, intron (n-2), tactic.swap, let h := h.get_or_else `this, h' ← to_expr ``(%%p ∨ %%p') >>= assert h, tactic.clear this, assumption <|> `[exact le_total _ _] <|> tactic.swap, (() <$ tactic.cases h' [`h,`h]) ; specialize ```(%%this _ _ h) ; intron (n-2) ; try (solve_by_elim <|> tauto <|> (tactic.intros >> cc)), return () end interactive end tactic
537e3798ce8737bfe3d6f49c63c1010859aed62c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/2299.lean
9a6c372bfc83ca0547ea3c6b8970dc266f048465
[ "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
225
lean
class Abs (Ξ± : Type _) where abs : Ξ± β†’ Ξ± macro:max atomic("|" noWs) a:term noWs "|" : term => `(Abs.abs $a) -- check that `|-` is not parsed as a single token. example [Abs Ξ±] [Neg Ξ±] (n : Ξ±) : |-n| = |-n| := rfl
b93d26f8bd1ca5c18c46ad560cc5793dfe79ee03
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/ring.lean
2d75a2894a5c55334b8572412a19fcc98f5cc212
[ "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
28,707
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 import data.int.range /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {Ξ±} [comm_semiring Ξ±] (a x : Ξ±) (n : β„•) (b : Ξ±) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (Ξ± : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (Ξ± : Type) : Type := reader_t cache tactic Ξ± /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : β„•) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m β„• := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (Ξ» n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {Ξ±} (m : tactic Ξ±) : ring_m Ξ± := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {Ξ±} (m : ring_m Ξ±) : tactic Ξ± := do Ξ± ← infer_type e, u ← mk_meta_univ, infer_type Ξ± >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache Ξ±, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(β„•), using_new_ref ic $ Ξ» r, using_new_ref nc $ Ξ» nr, using_new_ref mk_buffer $ Ξ» atoms, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `Ξ±`, or `β„•` for exponents). -/ @[inline] meta def ic_lift' (icf : cache β†’ ref instance_cache) {Ξ±} (f : instance_cache β†’ tactic (instance_cache Γ— Ξ±)) : ring_m Ξ± := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `Ξ±`. -/ @[inline] meta def ic_lift {Ξ±} : (instance_cache β†’ tactic (instance_cache Γ— Ξ±)) β†’ ring_m Ξ± := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `β„•`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {Ξ±} : (instance_cache β†’ tactic (instance_cache Γ— Ξ±)) β†’ ring_m Ξ± := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr β†’ expr := (@expr.const tt n [c.univ] c.Ξ± c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `β„•` and `β„š` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : β„š) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr β†’ expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr β†’ bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, Ξ» e, ((e : expr) : expr β†’ expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr β†’ string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr β†’ tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr Γ— expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {Ξ±} [comm_semiring Ξ±] (x n b) : @horner Ξ± _ 0 x n b = b := by simp [horner] theorem horner_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ nβ‚‚ b n') (h : n₁ + nβ‚‚ = n') : @horner Ξ± _ (horner a₁ x n₁ 0) x nβ‚‚ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr β†’ expr Γ— β„• β†’ expr Γ— β„• β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ Ξ» nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {Ξ±} [comm_semiring Ξ±] (k a x n b b') (h : k + b = b') : k + @horner Ξ± _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {Ξ±} [comm_semiring Ξ±] (a x n b k b') (h : b + k = b') : @horner Ξ± _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : n₁ + k = nβ‚‚) (hβ‚‚ : (a₁ + horner aβ‚‚ x k 0 : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x n₁ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : nβ‚‚ + k = n₁) (hβ‚‚ : (horner a₁ x k 0 + aβ‚‚ : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x nβ‚‚ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {Ξ±} [comm_semiring Ξ±] (a₁ x n b₁ aβ‚‚ bβ‚‚ a' b' t) (h₁ : a₁ + aβ‚‚ = a') (hβ‚‚ : b₁ + bβ‚‚ = b') (h₃ : horner a' x n b' = t) : @horner Ξ± _ a₁ x n b₁ + horner aβ‚‚ x n bβ‚‚ = t := by simp [h₃.symm, hβ‚‚.symm, h₁.symm, horner, add_mul, mul_comm]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁ c₁) (const eβ‚‚ cβ‚‚) := ic_lift $ Ξ» ic, do let n := c₁ + cβ‚‚, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ eβ‚‚ e c₁ cβ‚‚ n, return (ic, const e n, p) | he₁@(const e₁ c₁) heβ‚‚@(xadd eβ‚‚ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ Ξ» ic, do (ic, p) ← ic.mk_app ``zero_add [eβ‚‚], return (ic, heβ‚‚, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) heβ‚‚@(const eβ‚‚ cβ‚‚) := do c ← get_cache, if cβ‚‚ = 0 then ic_lift $ Ξ» ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b heβ‚‚, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, eβ‚‚, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (b', h) ← eval_add b₁ heβ‚‚, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, b', h]) else if x₁.2 β‰  xβ‚‚.2 then do (b', h) ← eval_add he₁ bβ‚‚, return (xadd' c aβ‚‚ xβ‚‚ nβ‚‚ b', c.cs_app ``const_add_horner [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, b', h]) else if n₁.2 < nβ‚‚.2 then do let k := nβ‚‚.2 - n₁.2, (ek, h₁) ← nc_lift (Ξ» nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek nβ‚‚.1, return (nc, ek, h₁)), Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (a', hβ‚‚) ← eval_add a₁ (xadd' c aβ‚‚ x₁ (ek, k) (const Ξ±0 0)), (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else if n₁.2 β‰  nβ‚‚.2 then do let k := n₁.2 - nβ‚‚.2, (ek, h₁) ← nc_lift (Ξ» nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc nβ‚‚.1 ek n₁.1, return (nc, ek, h₁)), Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (a', hβ‚‚) ← eval_add (xadd' c a₁ x₁ (ek, k) (const Ξ±0 0)) aβ‚‚, (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ nβ‚‚ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else do (a', h₁) ← eval_add a₁ aβ‚‚, (b', hβ‚‚) ← eval_add b₁ bβ‚‚, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, aβ‚‚, bβ‚‚, a', b', t, h₁, hβ‚‚, h₃]) theorem horner_neg {Ξ±} [comm_ring Ξ±] (a x n b a' b') (h₁ : -a = a') (hβ‚‚ : -b = b') : -@horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e coeff) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', hβ‚‚) ← eval_neg b, p ← ic_lift $ Ξ» ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, hβ‚‚], return (xadd' c a' x n b', p) theorem horner_const_mul {Ξ±} [comm_semiring Ξ±] (c a x n b a' b') (h₁ : c * a = a') (hβ‚‚ : c * b = b') : c * @horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {Ξ±} [comm_semiring Ξ±] (a x n b c a' b') (h₁ : a * c = a') (hβ‚‚ : b * c = b') : @horner Ξ± _ a x n b * c = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr Γ— β„š) : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e coeff) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', hβ‚‚) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, hβ‚‚]) theorem horner_mul_horner_zero {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ aa t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ 0 = t := by rw [← hβ‚‚, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ aa haa ab bb t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = haa) (h₃ : a₁ * bβ‚‚ = ab) (hβ‚„ : b₁ * bβ‚‚ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ bβ‚‚ = t := by rw [← H, ← hβ‚‚, ← h₁, ← h₃, ← hβ‚„]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁ c₁) (const eβ‚‚ cβ‚‚) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_mul_rat ic e₁ eβ‚‚ c₁ cβ‚‚, return (const e' (c₁ * cβ‚‚), p) | (const e₁ c₁) eβ‚‚ := if c₁ = 0 then do c ← get_cache, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ Ξ» ic, ic.mk_app ``zero_mul [eβ‚‚], return (const Ξ±0 0, p) else if c₁ = 1 then do p ← ic_lift $ Ξ» ic, ic.mk_app ``one_mul [eβ‚‚], return (eβ‚‚, p) else eval_const_mul (e₁, c₁) eβ‚‚ | e₁ heβ‚‚@(const eβ‚‚ cβ‚‚) := do p₁ ← ic_lift $ Ξ» ic, ic.mk_app ``mul_comm [e₁, eβ‚‚], (e', pβ‚‚) ← eval_mul heβ‚‚ e₁, p ← lift $ mk_eq_trans p₁ pβ‚‚, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (a', h₁) ← eval_mul a₁ heβ‚‚, (b', hβ‚‚) ← eval_mul b₁ heβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, a', b', h₁, hβ‚‚]) else if x₁.2 β‰  xβ‚‚.2 then do (a', h₁) ← eval_mul he₁ aβ‚‚, (b', hβ‚‚) ← eval_mul he₁ bβ‚‚, return (xadd' c a' xβ‚‚ nβ‚‚ b', c.cs_app ``horner_const_mul [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, a', b', h₁, hβ‚‚]) else do (aa, h₁) ← eval_mul he₁ aβ‚‚, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (haa, hβ‚‚) ← eval_horner aa x₁ nβ‚‚ (const Ξ±0 0), if bβ‚‚.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, aa, haa, h₁, hβ‚‚]) else do (ab, h₃) ← eval_mul a₁ bβ‚‚, (bb, hβ‚„) ← eval_mul b₁ bβ‚‚, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, aa, haa, ab, bb, t, h₁, hβ‚‚, h₃, hβ‚„, H]) theorem horner_pow {Ξ±} [comm_semiring Ξ±] (a x n m n' a') (h₁ : n * m = n') (hβ‚‚ : a ^ m = a') : @horner Ξ± _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, hβ‚‚.symm, horner, mul_pow, pow_mul] theorem pow_succ {Ξ±} [comm_semiring Ξ±] (a n b c) (h₁ : (a:Ξ±) ^ n = b) (hβ‚‚ : b * a = c) : a ^ (n + 1) = c := by rw [← hβ‚‚, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr β†’ expr Γ— β„• β†’ ring_m (horner_expr Γ— expr) | e (_, 0) := do c ← get_cache, Ξ±1 ← ic_lift $ Ξ» ic, ic.mk_app ``has_one.one [], p ← ic_lift $ Ξ» ic, ic.mk_app ``pow_zero [e], return (const Ξ±1 1, p) | e (_, 1) := do p ← ic_lift $ Ξ» ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (eβ‚‚, m) := ic_lift $ Ξ» ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic eβ‚‚, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ Ξ» nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', hβ‚‚) ← eval_pow a m, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const Ξ±0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, hβ‚‚]) | _ := do eβ‚‚ ← nc_lift $ Ξ» nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (eβ‚‚, m.2-1), (t, pβ‚‚) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, eβ‚‚, tl, t, hl, pβ‚‚]) end theorem horner_atom {Ξ±} [comm_semiring Ξ±] (x : Ξ±) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr Γ— expr) := do c ← get_cache, i ← add_atom e, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], Ξ±1 ← ic_lift $ Ξ» ic, ic.mk_app ``has_one.one [], return (xadd' c (const Ξ±1 1) (e, i) (`(1), 1) (const Ξ±0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {Ξ±} [monoid Ξ±] (l r tl tr t) (prl : (l : Ξ±) = tl) (prr : (r : β„•) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : a + -b = c) : a - b = c := h lemma unfold_div {Ξ±} [division_ring Ξ±] (a b c : Ξ±) (h : a * b⁻¹ = c) : a / b = c := h /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr β†’ ring_m (horner_expr Γ— expr) | `(%%e₁ + %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_add e₁' eβ‚‚', p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_add [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(@has_sub.sub %%Ξ± %%inst %%e₁ %%eβ‚‚) := mcond (succeeds (lift $ mk_app ``comm_ring [Ξ±] >>= mk_instance)) (do eβ‚‚' ← ic_lift $ Ξ» ic, ic.mk_app ``has_neg.neg [eβ‚‚], e ← ic_lift $ Ξ» ic, ic.mk_app ``has_add.add [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ic_lift $ Ξ» ic, ic.mk_app ``unfold_sub [e₁, eβ‚‚, e', p], return (e', if inst.const_name = `int.has_sub then `(norm_num.int_sub_hack).mk_app [e₁, eβ‚‚, e', p'] else p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (eβ‚‚, pβ‚‚) ← eval_neg e₁, p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, eβ‚‚, p₁, pβ‚‚], return (eβ‚‚, p) | `(%%e₁ * %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_mul e₁' eβ‚‚', p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_mul [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%eβ‚‚) := mcond (succeeds (do inst' ← ic_lift $ Ξ» ic, ic.mk_app ``division_ring_has_div [], lift $ is_def_eq inst inst')) (do eβ‚‚' ← ic_lift $ Ξ» ic, ic.mk_app ``has_inv.inv [eβ‚‚], e ← ic_lift $ Ξ» ic, ic.mk_app ``has_mul.mul [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ic_lift $ Ξ» ic, ic.mk_app ``unfold_div [e₁, eβ‚‚, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%eβ‚‚) := do (eβ‚‚', pβ‚‚) ← lift $ norm_num.derive eβ‚‚ <|> refl_conv eβ‚‚, match eβ‚‚'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (eβ‚‚, k), p ← ic_lift $ Ξ» ic, ic.mk_app ``subst_into_pow [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (e : expr) : tactic (expr Γ— expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {Ξ±} [comm_semiring Ξ±] (a x n b) : @horner Ξ± _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {Ξ±} [semigroup Ξ±] (a b c : Ξ±) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {Ξ±} [monoid Ξ±] (a : Ξ±) (m n : β„•) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {Ξ±} [monoid Ξ±] (a b : Ξ±) (m n : β„•) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {Ξ±} [add_group Ξ±] (a b : Ξ±) : a + -b = a - b := rfl /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr Γ— expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (Ξ» _, failed) (Ξ» _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (Ξ» e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (Β¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (Ξ» _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%eβ‚‚) ← target, ((e₁', p₁), (eβ‚‚', pβ‚‚)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval eβ‚‚, is_def_eq e₁' eβ‚‚', p ← mk_eq_symm pβ‚‚ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. 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 ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin GrΓ©goire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
891ae46af29c37e58dca9361d8ddec3f76cf1c82
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/doc_commands.lean
d188b48d5677371cb76b658846665d6e65f1d96a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
17,283
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.fix_reflect_string /-! # Documentation commands We generate html documentation from mathlib. It is convenient to collect lists of tactics, commands, notes, etc. To facilitate this, we declare these documentation entries in the library using special commands. * `library_note` adds a note describing a certain feature or design decision. These can be referenced in doc strings with the text `note [name of note]`. * `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or attribute. Since these commands are used in files imported by `tactic.core`, this file has no imports. ## Implementation details `library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`. This declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the `library_note` attribute. Similarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided information. -/ /-- A rudimentary hash function on strings. -/ def string.hash (s : string) : β„• := s.fold 1 (Ξ» h c, (33*h + c.val) % unsigned_sz) /-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name `nspace._i` -/ meta def string.mk_hashed_name (nspace : name) (id : string) : name := nspace <.> ("_" ++ to_string id.hash) open tactic /-- `copy_doc_string fr to` copies the docstring from the declaration named `fr` to each declaration named in the list `to`. -/ meta def tactic.copy_doc_string (fr : name) (to : list name) : tactic unit := do fr_ds ← doc_string fr, to.mmap' $ Ξ» tgt, add_doc_string tgt fr_ds open lean lean.parser interactive /-- `copy_doc_string source β†’ target_1 target_2 ... target_n` copies the doc string of the declaration named `source` to each of `target_1`, `target_2`, ..., `target_n`. -/ @[user_command] meta def copy_doc_string_cmd (_ : parse (tk "copy_doc_string")) : parser unit := do fr ← parser.ident, tk "->", to ← parser.many parser.ident, expr.const fr _ ← resolve_name fr, to ← parser.of_tactic (to.mmap $ Ξ» n, expr.const_name <$> resolve_name n), tactic.copy_doc_string fr to /-! ### The `library_note` command -/ /-- A user attribute `library_note` for tagging decls of type `string Γ— string` for use in note output. -/ @[user_attribute] meta def library_note_attr : user_attribute := { name := `library_note, descr := "Notes about library features to be included in documentation" } /-- `mk_reflected_definition name val` constructs a definition declaration by reflection. Example: ``mk_reflected_definition `foo 17`` constructs the definition declaration corresponding to `def foo : β„• := 17` -/ meta def mk_reflected_definition (decl_name : name) {type} [reflected type] (body : type) [reflected body] : declaration := mk_definition decl_name (reflect type).collect_univ_params (reflect type) (reflect body) /-- If `note_name` and `note` are `pexpr`s representing strings, `add_library_note note_name note` adds a declaration of type `string Γ— string` and tags it with the `library_note` attribute. -/ meta def tactic.add_library_note (note_name note : string) : tactic unit := do let decl_name := note_name.mk_hashed_name `library_note, add_decl $ mk_reflected_definition decl_name (note_name, note), library_note_attr.set decl_name () tt none open tactic /-- A command to add library notes. Syntax: ``` /-- note message -/ library_note "note id" ``` -/ @[user_command] meta def library_note (mi : interactive.decl_meta_info) (_ : parse (tk "library_note")) : parser unit := do note_name ← parser.pexpr, note_name ← eval_pexpr string note_name, some doc_string ← pure mi.doc_string | fail "library_note requires a doc string", add_library_note note_name doc_string /-- Collects all notes in the current environment. Returns a list of pairs `(note_id, note_content)` -/ meta def tactic.get_library_notes : tactic (list (string Γ— string)) := attribute.get_instances `library_note >>= list.mmap (Ξ» dcl, mk_const dcl >>= eval_expr (string Γ— string)) /-! ### The `add_tactic_doc_entry` command -/ /-- The categories of tactic doc entry. -/ @[derive [decidable_eq, has_reflect]] inductive doc_category | tactic | cmd | hole_cmd | attr /-- Format a `doc_category` -/ meta def doc_category.to_string : doc_category β†’ string | doc_category.tactic := "tactic" | doc_category.cmd := "command" | doc_category.hole_cmd := "hole_command" | doc_category.attr := "attribute" meta instance : has_to_format doc_category := βŸ¨β†‘doc_category.to_string⟩ /-- The information used to generate a tactic doc entry -/ @[derive has_reflect] structure tactic_doc_entry := (name : string) (category : doc_category) (decl_names : list _root_.name) (tags : list string := []) (description : string := "") (inherit_description_from : option _root_.name := none) /-- Turns a `tactic_doc_entry` into a JSON representation. -/ meta def tactic_doc_entry.to_json (d : tactic_doc_entry) : json := json.object [ ("name", d.name), ("category", d.category.to_string), ("decl_names", d.decl_names.map (json.of_string ∘ to_string)), ("tags", d.tags.map json.of_string), ("description", d.description) ] meta instance : has_to_string tactic_doc_entry := ⟨json.unparse ∘ tactic_doc_entry.to_json⟩ /-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the doc string of the declaration named `inh_id`. -/ meta def tactic_doc_entry.update_description_from (tde : tactic_doc_entry) (inh_id : name) : tactic tactic_doc_entry := do ds ← doc_string inh_id <|> fail (to_string inh_id ++ " has no doc string"), return { description := ds .. tde } /-- `update_description tde` replaces the `description` field of `tde` with: * the doc string of `tde.inherit_description_from`, if this field has a value * the doc string of the entry in `tde.decl_names`, if this field has length 1 If neither of these conditions are met, it returns `tde`. -/ meta def tactic_doc_entry.update_description (tde : tactic_doc_entry) : tactic tactic_doc_entry := match tde.inherit_description_from, tde.decl_names with | some inh_id, _ := tde.update_description_from inh_id | none, [inh_id] := tde.update_description_from inh_id | none, _ := return tde end /-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry` for use in doc output -/ @[user_attribute] meta def tactic_doc_entry_attr : user_attribute := { name := `tactic_doc, descr := "Information about a tactic to be included in documentation" } /-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/ meta def tactic.get_tactic_doc_entries : tactic (list tactic_doc_entry) := attribute.get_instances `tactic_doc >>= list.mmap (Ξ» dcl, mk_const dcl >>= eval_expr tactic_doc_entry) /-- `add_tactic_doc tde` adds a declaration to the environment with `tde` as its body and tags it with the `tactic_doc` attribute. If `tde.decl_names` has exactly one entry `` `decl`` and if `tde.description` is the empty string, `add_tactic_doc` uses the doc string of `decl` as the description. -/ meta def tactic.add_tactic_doc (tde : tactic_doc_entry) : tactic unit := do when (tde.description = "" ∧ tde.inherit_description_from.is_none ∧ tde.decl_names.length β‰  1) $ fail "A tactic doc entry must either: 1. have a description written as a doc-string for the `add_tactic_doc` invocation, or 2. have a single declaration in the `decl_names` field, to inherit a description from, or 3. explicitly indicate the declaration to inherit the description from using `inherit_description_from`.", tde ← if tde.description = "" then tde.update_description else return tde, let decl_name := (tde.name ++ tde.category.to_string).mk_hashed_name `tactic_doc, add_decl $ mk_definition decl_name [] `(tactic_doc_entry) (reflect tde), tactic_doc_entry_attr.set decl_name () tt none /-- A command used to add documentation for a tactic, command, hole command, or attribute. Usage: after defining an interactive tactic, command, or attribute, add its documentation as follows. ```lean /-- describe what the command does here -/ add_tactic_doc { name := "display name of the tactic", category := cat, decl_names := [`dcl_1, `dcl_2], tags := ["tag_1", "tag_2"] } ``` The argument to `add_tactic_doc` is a structure of type `tactic_doc_entry`. * `name` refers to the display name of the tactic; it is used as the header of the doc entry. * `cat` refers to the category of doc entry. Options: `doc_category.tactic`, `doc_category.cmd`, `doc_category.hole_cmd`, `doc_category.attr` * `decl_names` is a list of the declarations associated with this doc. For instance, the entry for `linarith` would set ``decl_names := [`tactic.interactive.linarith]``. Some entries may cover multiple declarations. It is only necessary to list the interactive versions of tactics. * `tags` is an optional list of strings used to categorize entries. * The doc string is the body of the entry. It can be formatted with markdown. What you are reading now is the description of `add_tactic_doc`. If only one related declaration is listed in `decl_names` and if this invocation of `add_tactic_doc` does not have a doc string, the doc string of that declaration will become the body of the tactic doc entry. If there are multiple declarations, you can select the one to be used by passing a name to the `inherit_description_from` field. If you prefer a tactic to have a doc string that is different then the doc entry, you should write the doc entry as a doc string for the `add_tactic_doc` invocation. Note that providing a badly formed `tactic_doc_entry` to the command can result in strange error messages. -/ @[user_command] meta def add_tactic_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_tactic_doc") : parser unit := do pe ← parser.pexpr, e ← eval_pexpr tactic_doc_entry pe, let e : tactic_doc_entry := match mi.doc_string with | some desc := { description := desc, ..e } | none := e end, tactic.add_tactic_doc e . /-- At various places in mathlib, we leave implementation notes that are referenced from many other files. To keep track of these notes, we use the command `library_note`. This makes it easy to retrieve a list of all notes, e.g. for documentation output. These notes can be referenced in mathlib with the syntax `Note [note id]`. Often, these references will be made in code comments (`--`) that won't be displayed in docs. If such a reference is made in a doc string or module doc, it will be linked to the corresponding note in the doc display. Syntax: ``` /-- note message -/ library_note "note id" ``` An example from `meta.expr`: ``` /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" ``` This note can be referenced near a usage of `pi_binders`: ``` -- See Note [open expressions] /-- behavior of f -/ def f := pi_binders ... ``` -/ add_tactic_doc { name := "library_note", category := doc_category.cmd, decl_names := [`library_note, `tactic.add_library_note], tags := ["documentation"], inherit_description_from := `library_note } add_tactic_doc { name := "add_tactic_doc", category := doc_category.cmd, decl_names := [`add_tactic_doc_command, `tactic.add_tactic_doc], tags := ["documentation"], inherit_description_from := `add_tactic_doc_command } add_tactic_doc { name := "copy_doc_string", category := doc_category.cmd, decl_names := [`copy_doc_string_cmd, `tactic.copy_doc_string], tags := ["documentation"], inherit_description_from := `copy_doc_string_cmd } -- add docs to core tactics /-- The congruence closure tactic `cc` tries to solve the goal by chaining equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`). It is a finishing tactic, i.e. it is meant to close the current goal, not to make some inconclusive progress. A mostly trivial example would be: ```lean example (a b c : β„•) (f : β„• β†’ β„•) (h: a = b) (h' : b = c) : f a = f c := by cc ``` As an example requiring some thinking to do by hand, consider: ```lean example (f : β„• β†’ β„•) (x : β„•) (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) : f x = x := by cc ``` The tactic works by building an equality matching graph. It's a graph where the vertices are terms and they are linked by edges if they are known to be equal. Once you've added all the equalities in your context, you take the transitive closure of the graph and, for each connected component (i.e. equivalence class) you can elect a term that will represent the whole class and store proofs that the other elements are equal to it. You then take the transitive closure of these equalities under the congruence lemmas. The `cc` implementation in Lean does a few more tricks: for example it derives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a != nat.zero` for any `a`. * The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence closure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf), Journal of the ACM (1980) * The congruence lemmas for dependent type theory as used in Lean are described in [Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf) (de Moura, Selsam IJCAR 2016). -/ add_tactic_doc { name := "cc (congruence closure)", category := doc_category.tactic, decl_names := [`tactic.interactive.cc], tags := ["core", "finishing"] } /-- `conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis, by focusing on particular subexpressions. See <https://leanprover-community.github.io/extras/conv.html> for more details. Inside `conv` blocks, mathlib currently additionally provides * `erw`, * `ring`, `ring2` and `ring_exp`, * `norm_num`, * `norm_cast`, * `apply_congr`, and * `conv` (within another `conv`). `apply_congr` applies congruence lemmas to step further inside expressions, and sometimes gives between results than the automatically generated congruence lemmas used by `congr`. Using `conv` inside a `conv` block allows the user to return to the previous state of the outer `conv` block after it is finished. Thus you can continue editing an expression without having to start a new `conv` block and re-scoping everything. For example: ```lean example (a b c d : β„•) (h₁ : b = c) (hβ‚‚ : a + c = a + d) : a + b = a + d := by conv { to_lhs, conv { congr, skip, rw h₁, }, rw hβ‚‚, } ``` Without `conv`, the above example would need to be proved using two successive `conv` blocks, each beginning with `to_lhs`. Also, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that ```lean example : 0 + 0 = 0 := begin conv_lhs { simp } end ``` just means ```lean example : 0 + 0 = 0 := begin conv { to_lhs, simp } end ``` and likewise for `to_rhs`. -/ add_tactic_doc { name := "conv", category := doc_category.tactic, decl_names := [`tactic.interactive.conv], tags := ["core"] } add_tactic_doc { name := "simp", category := doc_category.tactic, decl_names := [`tactic.interactive.simp], tags := ["core", "simplification"] } /-- Accepts terms with the type `component tactic_state string` or `html empty` and renders them interactively. Requires a compatible version of the vscode extension to view the resulting widget. ### Example: ```lean /-- A simple counter that can be incremented or decremented with some buttons. -/ meta def counter_widget {Ο€ Ξ± : Type} : component Ο€ Ξ± := component.ignore_props $ component.mk_simple int int 0 (Ξ» _ x y, (x + y, none)) (Ξ» _ s, h "div" [] [ button "+" (1 : int), html.of_string $ to_string $ s, button "-" (-1) ] ) #html counter_widget ``` -/ add_tactic_doc { name := "#html", category := doc_category.cmd, decl_names := [`show_widget_cmd], tags := ["core", "widgets"] } /-- The `add_decl_doc` command is used to add a doc string to an existing declaration. ```lean def foo := 5 /-- Doc string for foo. -/ add_decl_doc foo ``` -/ @[user_command] meta def add_decl_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_decl_doc") : parser unit := do n ← parser.ident, n ← resolve_constant n, some doc ← pure mi.doc_string | fail "add_decl_doc requires a doc string", add_doc_string n doc add_tactic_doc { name := "add_decl_doc", category := doc_category.cmd, decl_names := [``add_decl_doc_command], tags := ["documentation"] }
fad95cba99da9c6698779fd8467b9574697ca363
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/algebra/bilinear.lean
9bf8544fe969b59e9f49cafc2443cbb059ea5399
[ "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
5,048
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.algebra.basic import linear_algebra.tensor_product /-! # Facts about algebras involving bilinear maps and tensor products We move a few basic statements about algebras out of `algebra.algebra.basic`, in order to avoid importing `linear_algebra.bilinear_map` and `linear_algebra.tensor_product` unnecessarily. -/ universes u v w namespace algebra open_locale tensor_product open module section variables (R A : Type*) [comm_semiring R] [semiring A] [algebra R A] /-- The multiplication in an algebra is a bilinear map. A weaker version of this for semirings exists as `add_monoid_hom.mul`. -/ def lmul : A →ₐ[R] (End R A) := { map_one' := by { ext a, exact one_mul a }, map_mul' := by { intros a b, ext c, exact mul_assoc a b c }, map_zero' := by { ext a, exact zero_mul a }, commutes' := by { intro r, ext a, dsimp, rw [smul_def] }, .. (show A β†’β‚—[R] A β†’β‚—[R] A, from linear_map.mkβ‚‚ R (*) (Ξ» x y z, add_mul x y z) (Ξ» c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (Ξ» x y z, mul_add x y z) (Ξ» c x y, by rw [smul_def, smul_def, left_comm])) } variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl variables (R) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A β†’β‚—[R] A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A β†’β‚—[R] A := (lmul R A).to_linear_map.flip r /-- Simultaneous multiplication on the left and right is a linear map. -/ def lmul_left_right (vw: A Γ— A) : A β†’β‚—[R] A := (lmul_right R vw.2).comp (lmul_left R vw.1) lemma commute_lmul_left_right (a b : A) : commute (lmul_left R a) (lmul_right R b) := by { ext c, exact (mul_assoc a c b).symm, } /-- The multiplication map on an algebra, as an `R`-linear map from `A βŠ—[R] A` to `A`. -/ def lmul' : A βŠ—[R] A β†’β‚—[R] A := tensor_product.lift (lmul R A).to_linear_map variables {R A} @[simp] lemma lmul'_apply {x y : A} : lmul' R (x βŠ—β‚œ y) = x * y := by simp only [algebra.lmul', tensor_product.lift.tmul, alg_hom.to_linear_map_apply, lmul_apply] @[simp] lemma lmul_left_apply (p q : A) : lmul_left R p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R p q = q * p := rfl @[simp] lemma lmul_left_right_apply (vw : A Γ— A) (p : A) : lmul_left_right R vw p = vw.1 * p * vw.2 := rfl @[simp] lemma lmul_left_one : lmul_left R (1:A) = linear_map.id := by { ext, simp only [linear_map.id_coe, one_mul, id.def, lmul_left_apply] } @[simp] lemma lmul_left_mul (a b : A) : lmul_left R (a * b) = (lmul_left R a).comp (lmul_left R b) := by { ext, simp only [lmul_left_apply, linear_map.comp_apply, mul_assoc] } @[simp] lemma lmul_right_one : lmul_right R (1:A) = linear_map.id := by { ext, simp only [linear_map.id_coe, mul_one, id.def, lmul_right_apply] } @[simp] lemma lmul_right_mul (a b : A) : lmul_right R (a * b) = (lmul_right R b).comp (lmul_right R a) := by { ext, simp only [lmul_right_apply, linear_map.comp_apply, mul_assoc] } @[simp] lemma lmul_left_zero_eq_zero : lmul_left R (0 : A) = 0 := (lmul R A).map_zero @[simp] lemma lmul_right_zero_eq_zero : lmul_right R (0 : A) = 0 := (lmul R A).to_linear_map.flip.map_zero @[simp] lemma lmul_left_eq_zero_iff (a : A) : lmul_left R a = 0 ↔ a = 0 := begin split; intros h, { rw [← mul_one a, ← lmul_left_apply a 1, h, linear_map.zero_apply], }, { rw h, exact lmul_left_zero_eq_zero, }, end @[simp] lemma lmul_right_eq_zero_iff (a : A) : lmul_right R a = 0 ↔ a = 0 := begin split; intros h, { rw [← one_mul a, ← lmul_right_apply a 1, h, linear_map.zero_apply], }, { rw h, exact lmul_right_zero_eq_zero, }, end @[simp] lemma pow_lmul_left (a : A) (n : β„•) : (lmul_left R a) ^ n = lmul_left R (a ^ n) := ((lmul R A).map_pow a n).symm @[simp] lemma pow_lmul_right (a : A) (n : β„•) : (lmul_right R a) ^ n = lmul_right R (a ^ n) := linear_map.coe_injective $ ((lmul_right R a).coe_pow n).symm β–Έ (mul_right_iterate a n) end section variables {R A : Type*} [comm_semiring R] [ring A] [algebra R A] lemma lmul_left_injective [no_zero_divisors A] {x : A} (hx : x β‰  0) : function.injective (lmul_left R x) := by { letI : domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..β€Ήring Aβ€Ί, ..β€Ήno_zero_divisors Aβ€Ί }, exact mul_right_injectiveβ‚€ hx } lemma lmul_right_injective [no_zero_divisors A] {x : A} (hx : x β‰  0) : function.injective (lmul_right R x) := by { letI : domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..β€Ήring Aβ€Ί, ..β€Ήno_zero_divisors Aβ€Ί }, exact mul_left_injectiveβ‚€ hx } lemma lmul_injective [no_zero_divisors A] {x : A} (hx : x β‰  0) : function.injective (lmul R A x) := by { letI : domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..β€Ήring Aβ€Ί, ..β€Ήno_zero_divisors Aβ€Ί }, exact mul_right_injectiveβ‚€ hx } end end algebra
b1b804cdc47411962b0700a149a2f78524b59e1d
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/order/directed.lean
627ac286a3896fff983aa06ffa64282ba3b4b256
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,054
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 order.lattice import data.set.basic universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {ΞΉ : Sort w} (r : Ξ± β†’ Ξ± β†’ Prop) local infix ` β‰Ό ` : 50 := r /-- A family of elements of Ξ± is directed (with respect to a relation `β‰Ό` on Ξ±) if there is a member of the family `β‰Ό`-above any pair in the family. -/ def directed (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 variables {r} 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) alias directed_on_iff_directed ↔ directed_on.directed_coe _ 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 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.2 $ hf.mono hg /-- A monotone function on a sup-semilattice is directed. -/ lemma directed_of_sup [semilattice_sup Ξ±] {f : Ξ± β†’ Ξ²} {r : Ξ² β†’ Ξ² β†’ Prop} (H : βˆ€ ⦃i j⦄, i ≀ j β†’ r (f i) (f j)) : directed r f := Ξ» a b, ⟨a βŠ” b, H le_sup_left, H le_sup_right⟩ /-- An antimonotone function on an inf-semilattice is directed. -/ lemma directed_of_inf [semilattice_inf Ξ±] {r : Ξ² β†’ Ξ² β†’ Prop} {f : Ξ± β†’ Ξ²} (hf : βˆ€a₁ aβ‚‚, a₁ ≀ aβ‚‚ β†’ r (f aβ‚‚) (f a₁)) : directed r f := assume x y, ⟨x βŠ“ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩ /-- A `preorder` is a `directed_order` if for any two elements `i`, `j` there is an element `k` such that `i ≀ k` and `j ≀ k`. -/ class directed_order (Ξ± : Type u) extends preorder Ξ± := (directed : βˆ€ i j : Ξ±, βˆƒ k, i ≀ k ∧ j ≀ k) @[priority 100] -- see Note [lower instance priority] instance linear_order.to_directed_order (Ξ±) [linear_order Ξ±] : directed_order Ξ± := ⟨λ i j, or.cases_on (le_total i j) (Ξ» hij, ⟨j, hij, le_refl j⟩) (Ξ» hji, ⟨i, le_refl i, hji⟩)⟩
0e4fa5863f0bafa5fe7f9c64495ccd1bb24c7543
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/analysis/normed_space/banach.lean
e7a51b13180ef4768c54bfece6444ed99925c25b
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,833
lean
/- Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import topology.metric_space.baire import analysis.normed_space.operator_norm /-! # Banach open mapping theorem This file contains the Banach open mapping theorem, i.e., the fact that a bijective bounded linear map between Banach spaces has a bounded inverse. -/ open function metric set filter finset open_locale classical topological_space big_operators variables {π•œ : Type*} [nondiscrete_normed_field π•œ] {E : Type*} [normed_group E] [normed_space π•œ E] {F : Type*} [normed_group F] [normed_space π•œ F] (f : E β†’L[π•œ] F) include π•œ variable [complete_space F] /-- First step of the proof of the Banach open mapping theorem (using completeness of `F`): by Baire's theorem, there exists a ball in `E` whose image closure has nonempty interior. Rescaling everything, it follows that any `y ∈ F` is arbitrarily well approached by images of elements of norm at most `C * βˆ₯yβˆ₯`. For further use, we will only need such an element whose image is within distance `βˆ₯yβˆ₯/2` of `y`, to apply an iterative process. -/ lemma exists_approx_preimage_norm_le (surj : surjective f) : βˆƒC β‰₯ 0, βˆ€y, βˆƒx, dist (f x) y ≀ 1/2 * βˆ₯yβˆ₯ ∧ βˆ₯xβˆ₯ ≀ C * βˆ₯yβˆ₯ := begin have A : (⋃n:β„•, closure (f '' (ball 0 n))) = univ, { refine subset.antisymm (subset_univ _) (Ξ»y hy, _), rcases surj y with ⟨x, hx⟩, rcases exists_nat_gt (βˆ₯xβˆ₯) with ⟨n, hn⟩, refine mem_Union.2 ⟨n, subset_closure _⟩, refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩, rwa [mem_ball, dist_eq_norm, sub_zero] }, have : βˆƒ (n : β„•) x, x ∈ interior (closure (f '' (ball 0 n))) := nonempty_interior_of_Union_of_closed (Ξ»n, is_closed_closure) A, simp only [mem_interior_iff_mem_nhds, mem_nhds_iff] at this, rcases this with ⟨n, a, Ξ΅, ⟨Ρpos, H⟩⟩, rcases normed_field.exists_one_lt_norm π•œ with ⟨c, hc⟩, refine ⟨(Ξ΅/2)⁻¹ * βˆ₯cβˆ₯ * 2 * n, _, Ξ»y, _⟩, { refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _, exacts [inv_nonneg.2 (div_nonneg (le_of_lt Ξ΅pos) (by norm_num)), n.cast_nonneg] }, { by_cases hy : y = 0, { use 0, simp [hy] }, { rcases rescale_to_shell hc (half_pos Ξ΅pos) hy with ⟨d, hd, ydlt, leyd, dinv⟩, let Ξ΄ := βˆ₯dβˆ₯ * βˆ₯yβˆ₯/4, have Ξ΄pos : 0 < Ξ΄ := div_pos (mul_pos (norm_pos_iff.2 hd) (norm_pos_iff.2 hy)) (by norm_num), have : a + d β€’ y ∈ ball a Ξ΅, by simp [dist_eq_norm, lt_of_le_of_lt ydlt.le (half_lt_self Ξ΅pos)], rcases metric.mem_closure_iff.1 (H this) _ Ξ΄pos with ⟨z₁, z₁im, hβ‚βŸ©, rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xzβ‚βŸ©, rw ← xz₁ at h₁, rw [mem_ball, dist_eq_norm, sub_zero] at hx₁, have : a ∈ ball a Ξ΅, by { simp, exact Ξ΅pos }, rcases metric.mem_closure_iff.1 (H this) _ Ξ΄pos with ⟨zβ‚‚, zβ‚‚im, hβ‚‚βŸ©, rcases (mem_image _ _ _).1 zβ‚‚im with ⟨xβ‚‚, hxβ‚‚, xzβ‚‚βŸ©, rw ← xzβ‚‚ at hβ‚‚, rw [mem_ball, dist_eq_norm, sub_zero] at hxβ‚‚, let x := x₁ - xβ‚‚, have I : βˆ₯f x - d β€’ yβˆ₯ ≀ 2 * Ξ΄ := calc βˆ₯f x - d β€’ yβˆ₯ = βˆ₯f x₁ - (a + d β€’ y) - (f xβ‚‚ - a)βˆ₯ : by { congr' 1, simp only [x, f.map_sub], abel } ... ≀ βˆ₯f x₁ - (a + d β€’ y)βˆ₯ + βˆ₯f xβ‚‚ - aβˆ₯ : norm_sub_le _ _ ... ≀ Ξ΄ + Ξ΄ : begin apply add_le_add, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ }, { rw [← dist_eq_norm, dist_comm], exact le_of_lt hβ‚‚ } end ... = 2 * Ξ΄ : (two_mul _).symm, have J : βˆ₯f (d⁻¹ β€’ x) - yβˆ₯ ≀ 1/2 * βˆ₯yβˆ₯ := calc βˆ₯f (d⁻¹ β€’ x) - yβˆ₯ = βˆ₯d⁻¹ β€’ f x - (d⁻¹ * d) β€’ yβˆ₯ : by rwa [f.map_smul _, inv_mul_cancel, one_smul] ... = βˆ₯d⁻¹ β€’ (f x - d β€’ y)βˆ₯ : by rw [mul_smul, smul_sub] ... = βˆ₯dβˆ₯⁻¹ * βˆ₯f x - d β€’ yβˆ₯ : by rw [norm_smul, normed_field.norm_inv] ... ≀ βˆ₯dβˆ₯⁻¹ * (2 * Ξ΄) : begin apply mul_le_mul_of_nonneg_left I, rw inv_nonneg, exact norm_nonneg _ end ... = (βˆ₯dβˆ₯⁻¹ * βˆ₯dβˆ₯) * βˆ₯yβˆ₯ /2 : by { simp only [Ξ΄], ring } ... = βˆ₯yβˆ₯/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] } ... = (1/2) * βˆ₯yβˆ₯ : by ring, rw ← dist_eq_norm at J, have K : βˆ₯d⁻¹ β€’ xβˆ₯ ≀ (Ξ΅ / 2)⁻¹ * βˆ₯cβˆ₯ * 2 * ↑n * βˆ₯yβˆ₯ := calc βˆ₯d⁻¹ β€’ xβˆ₯ = βˆ₯dβˆ₯⁻¹ * βˆ₯x₁ - xβ‚‚βˆ₯ : by rw [norm_smul, normed_field.norm_inv] ... ≀ ((Ξ΅ / 2)⁻¹ * βˆ₯cβˆ₯ * βˆ₯yβˆ₯) * (n + n) : begin refine mul_le_mul dinv _ (norm_nonneg _) _, { exact le_trans (norm_sub_le _ _) (add_le_add (le_of_lt hx₁) (le_of_lt hxβ‚‚)) }, { apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _), exact inv_nonneg.2 (le_of_lt (half_pos Ξ΅pos)) } end ... = (Ξ΅ / 2)⁻¹ * βˆ₯cβˆ₯ * 2 * ↑n * βˆ₯yβˆ₯ : by ring, exact ⟨d⁻¹ β€’ x, J, K⟩ } }, end variable [complete_space E] /-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then any point has a preimage with controlled norm. -/ theorem exists_preimage_norm_le (surj : surjective f) : βˆƒC > 0, βˆ€y, βˆƒx, f x = y ∧ βˆ₯xβˆ₯ ≀ C * βˆ₯yβˆ₯ := begin obtain ⟨C, C0, hC⟩ := exists_approx_preimage_norm_le f surj, /- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`, leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a preimage of `y`. This uses completeness of `E`. -/ choose g hg using hC, let h := Ξ»y, y - f (g y), have hle : βˆ€y, βˆ₯h yβˆ₯ ≀ (1/2) * βˆ₯yβˆ₯, { assume y, rw [← dist_eq_norm, dist_comm], exact (hg y).1 }, refine ⟨2 * C + 1, by linarith, Ξ»y, _⟩, have hnle : βˆ€n:β„•, βˆ₯(h^[n]) yβˆ₯ ≀ (1/2)^n * βˆ₯yβˆ₯, { assume n, induction n with n IH, { simp only [one_div, nat.nat_zero_eq_zero, one_mul, iterate_zero_apply, pow_zero] }, { rw [iterate_succ'], apply le_trans (hle _) _, rw [pow_succ, mul_assoc], apply mul_le_mul_of_nonneg_left IH, norm_num } }, let u := Ξ»n, g((h^[n]) y), have ule : βˆ€n, βˆ₯u nβˆ₯ ≀ (1/2)^n * (C * βˆ₯yβˆ₯), { assume n, apply le_trans (hg _).2 _, calc C * βˆ₯(h^[n]) yβˆ₯ ≀ C * ((1/2)^n * βˆ₯yβˆ₯) : mul_le_mul_of_nonneg_left (hnle n) C0 ... = (1 / 2) ^ n * (C * βˆ₯yβˆ₯) : by ring }, have sNu : summable (Ξ»n, βˆ₯u nβˆ₯), { refine summable_of_nonneg_of_le (Ξ»n, norm_nonneg _) ule _, exact summable.mul_right _ (summable_geometric_of_lt_1 (by norm_num) (by norm_num)) }, have su : summable u := summable_of_summable_norm sNu, let x := tsum u, have x_ineq : βˆ₯xβˆ₯ ≀ (2 * C + 1) * βˆ₯yβˆ₯ := calc βˆ₯xβˆ₯ ≀ βˆ‘'n, βˆ₯u nβˆ₯ : norm_tsum_le_tsum_norm sNu ... ≀ βˆ‘'n, (1/2)^n * (C * βˆ₯yβˆ₯) : tsum_le_tsum ule sNu (summable.mul_right _ summable_geometric_two) ... = (βˆ‘'n, (1/2)^n) * (C * βˆ₯yβˆ₯) : tsum_mul_right ... = 2 * C * βˆ₯yβˆ₯ : by rw [tsum_geometric_two, mul_assoc] ... ≀ 2 * C * βˆ₯yβˆ₯ + βˆ₯yβˆ₯ : le_add_of_nonneg_right (norm_nonneg y) ... = (2 * C + 1) * βˆ₯yβˆ₯ : by ring, have fsumeq : βˆ€n:β„•, f (βˆ‘ i in finset.range n, u i) = y - (h^[n]) y, { assume n, induction n with n IH, { simp [f.map_zero] }, { rw [sum_range_succ, f.map_add, IH, iterate_succ'], simp [u, h, sub_eq_add_neg, add_comm, add_left_comm] } }, have : tendsto (Ξ»n, βˆ‘ i in range n, u i) at_top (𝓝 x) := su.has_sum.tendsto_sum_nat, have L₁ : tendsto (Ξ»n, f(βˆ‘ i in range n, u i)) at_top (𝓝 (f x)) := (f.continuous.tendsto _).comp this, simp only [fsumeq] at L₁, have Lβ‚‚ : tendsto (Ξ»n, y - (h^[n]) y) at_top (𝓝 (y - 0)), { refine tendsto_const_nhds.sub _, rw tendsto_iff_norm_tendsto_zero, simp only [sub_zero], refine squeeze_zero (Ξ»_, norm_nonneg _) hnle _, rw [← zero_mul βˆ₯yβˆ₯], refine (tendsto_pow_at_top_nhds_0_of_lt_1 _ _).mul tendsto_const_nhds; norm_num }, have feq : f x = y - 0 := tendsto_nhds_unique L₁ Lβ‚‚, rw sub_zero at feq, exact ⟨x, feq, x_ineq⟩ end /-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is open. -/ theorem open_mapping (surj : surjective f) : is_open_map f := begin assume s hs, rcases exists_preimage_norm_le f surj with ⟨C, Cpos, hC⟩, refine is_open_iff.2 (Ξ»y yfs, _), rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩, rcases is_open_iff.1 hs x xs with ⟨Ρ, Ξ΅pos, hΡ⟩, refine ⟨Ρ/C, div_pos Ξ΅pos Cpos, Ξ»z hz, _⟩, rcases hC (z-y) with ⟨w, wim, wnorm⟩, have : f (x + w) = z, by { rw [f.map_add, wim, fxy, add_sub_cancel'_right] }, rw ← this, have : x + w ∈ ball x Ξ΅ := calc dist (x+w) x = βˆ₯wβˆ₯ : by { rw dist_eq_norm, simp } ... ≀ C * βˆ₯z - yβˆ₯ : wnorm ... < C * (Ξ΅/C) : begin apply mul_lt_mul_of_pos_left _ Cpos, rwa [mem_ball, dist_eq_norm] at hz, end ... = Ξ΅ : mul_div_cancel' _ (ne_of_gt Cpos), exact set.mem_image_of_mem _ (hΞ΅ this) end namespace linear_equiv /-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/ @[continuity] theorem continuous_symm (e : E ≃ₗ[π•œ] F) (h : continuous e) : continuous e.symm := begin rw continuous_def, intros s hs, rw [← e.image_eq_preimage], rw [← e.coe_coe] at h ⊒, exact open_mapping βŸ¨β†‘e, h⟩ e.surjective s hs end /-- Associating to a linear equivalence between Banach spaces a continuous linear equivalence when the direct map is continuous, thanks to the Banach open mapping theorem that ensures that the inverse map is also continuous. -/ def to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[π•œ] F) (h : continuous e) : E ≃L[π•œ] F := { continuous_to_fun := h, continuous_inv_fun := e.continuous_symm h, ..e } @[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[π•œ] F) (h : continuous e) : ⇑(e.to_continuous_linear_equiv_of_continuous h) = e := rfl @[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous_symm (e : E ≃ₗ[π•œ] F) (h : continuous e) : ⇑(e.to_continuous_linear_equiv_of_continuous h).symm = e.symm := rfl end linear_equiv namespace continuous_linear_equiv /-- Convert a bijective continuous linear map `f : E β†’L[π•œ] F` between two Banach spaces to a continuous linear equivalence. -/ noncomputable def of_bijective (f : E β†’L[π•œ] F) (hinj : f.ker = βŠ₯) (hsurj : f.range = ⊀) : E ≃L[π•œ] F := (linear_equiv.of_bijective ↑f hinj hsurj).to_continuous_linear_equiv_of_continuous f.continuous @[simp] lemma coe_fn_of_bijective (f : E β†’L[π•œ] F) (hinj : f.ker = βŠ₯) (hsurj : f.range = ⊀) : ⇑(of_bijective f hinj hsurj) = f := rfl @[simp] lemma of_bijective_symm_apply_apply (f : E β†’L[π•œ] F) (hinj : f.ker = βŠ₯) (hsurj : f.range = ⊀) (x : E) : (of_bijective f hinj hsurj).symm (f x) = x := (of_bijective f hinj hsurj).symm_apply_apply x @[simp] lemma of_bijective_apply_symm_apply (f : E β†’L[π•œ] F) (hinj : f.ker = βŠ₯) (hsurj : f.range = ⊀) (y : F) : f ((of_bijective f hinj hsurj).symm y) = y := (of_bijective f hinj hsurj).apply_symm_apply y end continuous_linear_equiv
3658f9cd226106c313a6dace1930fb379bcb09c6
b147e1312077cdcfea8e6756207b3fa538982e12
/data/list/perm.lean
b5fdc705658bc29bd1ccb713f3e3d1358ed69d56
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,677
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro List permutations. -/ import data.list.basic namespace list universe variables uu vv variables {Ξ± : Type uu} {Ξ² : Type vv} /-- `perm l₁ lβ‚‚` or `l₁ ~ lβ‚‚` asserts that `l₁` and `lβ‚‚` are permutations of each other. This is defined by induction using pairwise swaps. -/ inductive perm : list Ξ± β†’ list Ξ± β†’ Prop | nil : perm [] [] | skip : Ξ  (x : Ξ±) {l₁ lβ‚‚ : list Ξ±}, perm l₁ lβ‚‚ β†’ perm (x::l₁) (x::lβ‚‚) | swap : Ξ  (x y : Ξ±) (l : list Ξ±), perm (y::x::l) (x::y::l) | trans : Ξ  {l₁ lβ‚‚ l₃ : list Ξ±}, perm l₁ lβ‚‚ β†’ perm lβ‚‚ l₃ β†’ perm l₁ l₃ open perm infix ~ := perm @[refl] protected theorem perm.refl : βˆ€ (l : list Ξ±), l ~ l | [] := perm.nil | (x::xs) := skip x (perm.refl xs) @[symm] protected theorem perm.symm {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : lβ‚‚ ~ l₁ := perm.rec_on p perm.nil (Ξ» x l₁ lβ‚‚ p₁ r₁, skip x r₁) (Ξ» x y l, swap y x l) (Ξ» l₁ lβ‚‚ l₃ p₁ pβ‚‚ r₁ rβ‚‚, trans rβ‚‚ r₁) attribute [trans] perm.trans theorem perm.eqv (Ξ± : Type) : equivalence (@perm Ξ±) := mk_equivalence (@perm Ξ±) (@perm.refl Ξ±) (@perm.symm Ξ±) (@perm.trans Ξ±) instance is_setoid (Ξ± : Type) : setoid (list Ξ±) := setoid.mk (@perm Ξ±) (perm.eqv Ξ±) theorem perm_subset {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : l₁ βŠ† lβ‚‚ := Ξ» a, perm.rec_on p (Ξ» h, h) (Ξ» x l₁ lβ‚‚ p₁ r₁ i, or.elim i (Ξ» ax, by simp [ax]) (Ξ» al₁, or.inr (r₁ al₁))) (Ξ» x y l ayxl, or.elim ayxl (Ξ» ay, by simp [ay]) (Ξ» axl, or.elim axl (Ξ» ax, by simp [ax]) (Ξ» al, or.inr (or.inr al)))) (Ξ» l₁ lβ‚‚ l₃ p₁ pβ‚‚ r₁ rβ‚‚ ainl₁, rβ‚‚ (r₁ ainl₁)) theorem mem_of_perm {a : Ξ±} {l₁ lβ‚‚ : list Ξ±} (h : l₁ ~ lβ‚‚) : a ∈ l₁ ↔ a ∈ lβ‚‚ := iff.intro (Ξ» m, perm_subset h m) (Ξ» m, perm_subset h.symm m) theorem perm_app_left {l₁ lβ‚‚ : list Ξ±} (t₁ : list Ξ±) (p : l₁ ~ lβ‚‚) : l₁++t₁ ~ lβ‚‚++t₁ := perm.rec_on p (perm.refl ([] ++ t₁)) (Ξ» x l₁ lβ‚‚ p₁ r₁, skip x r₁) (Ξ» x y l, swap x y _) (Ξ» l₁ lβ‚‚ l₃ p₁ pβ‚‚ r₁ rβ‚‚, trans r₁ rβ‚‚) theorem perm_app_right {t₁ tβ‚‚ : list Ξ±} : βˆ€ (l : list Ξ±), t₁ ~ tβ‚‚ β†’ l++t₁ ~ l++tβ‚‚ | [] p := p | (x::xs) p := skip x (perm_app_right xs p) theorem perm_app {l₁ lβ‚‚ t₁ tβ‚‚ : list Ξ±} (p₁ : l₁ ~ lβ‚‚) (pβ‚‚ : t₁ ~ tβ‚‚) : l₁++t₁ ~ lβ‚‚++tβ‚‚ := trans (perm_app_left t₁ p₁) (perm_app_right lβ‚‚ pβ‚‚) theorem perm_app_cons (a : Ξ±) {h₁ hβ‚‚ t₁ tβ‚‚ : list Ξ±} (p₁ : h₁ ~ hβ‚‚) (pβ‚‚ : t₁ ~ tβ‚‚) : h₁ ++ a::t₁ ~ hβ‚‚ ++ a::tβ‚‚ := perm_app p₁ (skip a pβ‚‚) @[simp] theorem perm_middle {a : Ξ±} : βˆ€ {l₁ lβ‚‚ : list Ξ±}, l₁++a::lβ‚‚ ~ a::(l₁++lβ‚‚) | [] lβ‚‚ := perm.refl _ | (b::l₁) lβ‚‚ := (skip b (@perm_middle l₁ lβ‚‚)).trans (swap a b _) @[simp] theorem perm_cons_app (a : Ξ±) (l : list Ξ±) : l ++ [a] ~ a::l := by simpa using @perm_middle _ a l [] @[simp] theorem perm_app_comm : βˆ€ {l₁ lβ‚‚ : list Ξ±}, (l₁++lβ‚‚) ~ (lβ‚‚++l₁) | [] lβ‚‚ := by simp | (a::t) lβ‚‚ := (skip a perm_app_comm).trans perm_middle.symm theorem concat_perm (l : list Ξ±) (a : Ξ±) : concat l a ~ a :: l := by simp theorem perm_length {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : length l₁ = length lβ‚‚ := perm.rec_on p rfl (Ξ» x l₁ lβ‚‚ p r, by simp[r]) (Ξ» x y l, by simp) (Ξ» l₁ lβ‚‚ l₃ p₁ pβ‚‚ r₁ rβ‚‚, eq.trans r₁ rβ‚‚) theorem eq_nil_of_perm_nil {l₁ : list Ξ±} (p : [] ~ l₁) : l₁ = [] := eq_nil_of_length_eq_zero (perm_length p).symm theorem perm_nil {l₁ : list Ξ±} : l₁ ~ [] ↔ l₁ = [] := ⟨λ p, eq_nil_of_perm_nil p.symm, Ξ» e, e β–Έ perm.refl _⟩ theorem not_perm_nil_cons (x : Ξ±) (l : list Ξ±) : Β¬ [] ~ x::l | p := by injection eq_nil_of_perm_nil p theorem eq_singleton_of_perm {a b : Ξ±} (p : [a] ~ [b]) : a = b := by simpa using perm_subset p (by simp) theorem eq_singleton_of_perm_inv {a : Ξ±} {l : list Ξ±} (p : [a] ~ l) : l = [a] := match l, show 1 = _, from perm_length p, p with | [a'], rfl, p := by rw [eq_singleton_of_perm p] end @[simp] theorem reverse_perm : βˆ€ (l : list Ξ±), reverse l ~ l | [] := perm.nil | (a::l) := by rw reverse_cons; exact (perm_cons_app _ _).trans (skip a $ reverse_perm l) theorem perm_cons_app_cons {l l₁ lβ‚‚ : list Ξ±} (a : Ξ±) (p : l ~ l₁++lβ‚‚) : a::l ~ l₁++(a::lβ‚‚) := trans (skip a p) perm_middle.symm @[simp] theorem perm_repeat {a : Ξ±} {n : β„•} {l : list Ξ±} : repeat a n ~ l ↔ repeat a n = l := ⟨λ p, (eq_repeat.2 $ by exact ⟨by simpa using (perm_length p).symm, Ξ» b m, eq_of_mem_repeat $ perm_subset p.symm m⟩).symm, Ξ» h, h β–Έ perm.refl _⟩ theorem perm_erase [decidable_eq Ξ±] {a : Ξ±} {l : list Ξ±} (h : a ∈ l) : l ~ a :: l.erase a := let ⟨l₁, lβ‚‚, _, e₁, eβ‚‚βŸ© := exists_erase_eq h in eβ‚‚.symm β–Έ e₁.symm β–Έ perm_middle @[elab_as_eliminator] theorem perm_induction_on {P : list Ξ± β†’ list Ξ± β†’ Prop} {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) (h₁ : P [] []) (hβ‚‚ : βˆ€ x l₁ lβ‚‚, l₁ ~ lβ‚‚ β†’ P l₁ lβ‚‚ β†’ P (x::l₁) (x::lβ‚‚)) (h₃ : βˆ€ x y l₁ lβ‚‚, l₁ ~ lβ‚‚ β†’ P l₁ lβ‚‚ β†’ P (y::x::l₁) (x::y::lβ‚‚)) (hβ‚„ : βˆ€ l₁ lβ‚‚ l₃, l₁ ~ lβ‚‚ β†’ lβ‚‚ ~ l₃ β†’ P l₁ lβ‚‚ β†’ P lβ‚‚ l₃ β†’ P l₁ l₃) : P l₁ lβ‚‚ := have P_refl : βˆ€ l, P l l, from assume l, list.rec_on l h₁ (Ξ» x xs ih, hβ‚‚ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ hβ‚‚ (Ξ» x y l, h₃ x y l l (perm.refl l) (P_refl l)) hβ‚„ @[congr] theorem perm_filter_map (f : Ξ± β†’ option Ξ²) {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : filter_map f l₁ ~ filter_map f lβ‚‚ := begin induction p with x lβ‚‚ lβ‚‚' p IH x y lβ‚‚ lβ‚‚ mβ‚‚ rβ‚‚ p₁ pβ‚‚ IH₁ IHβ‚‚, { simp }, { simp [filter_map], cases f x with a; simp [filter_map, IH, skip] }, { simp [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] }, { exact IH₁.trans IHβ‚‚ } end @[congr] theorem perm_map (f : Ξ± β†’ Ξ²) {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : map f l₁ ~ map f lβ‚‚ := by rw ← filter_map_eq_map; apply perm_filter_map _ p theorem perm_pmap {p : Ξ± β†’ Prop} (f : Ξ  a, p a β†’ Ξ²) {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) {H₁ Hβ‚‚} : pmap f l₁ H₁ ~ pmap f lβ‚‚ Hβ‚‚ := begin induction p with x lβ‚‚ lβ‚‚' p IH x y lβ‚‚ lβ‚‚ mβ‚‚ rβ‚‚ p₁ pβ‚‚ IH₁ IHβ‚‚, { simp }, { simp [IH, skip] }, { simp [swap] }, { refine IH₁.trans IHβ‚‚, exact Ξ» a m, Hβ‚‚ a (perm_subset pβ‚‚ m) } end theorem perm_filter (p : Ξ± β†’ Prop) [decidable_pred p] {l₁ lβ‚‚ : list Ξ±} (s : l₁ ~ lβ‚‚) : filter p l₁ ~ filter p lβ‚‚ := by rw ← filter_map_eq_filter; apply perm_filter_map _ s theorem exists_perm_sublist {l₁ lβ‚‚ lβ‚‚' : list Ξ±} (s : l₁ <+ lβ‚‚) (p : lβ‚‚ ~ lβ‚‚') : βˆƒ l₁' ~ l₁, l₁' <+ lβ‚‚' := begin induction p with x lβ‚‚ lβ‚‚' p IH x y lβ‚‚ lβ‚‚ mβ‚‚ rβ‚‚ p₁ pβ‚‚ IH₁ IHβ‚‚ generalizing l₁ s, { exact ⟨[], eq_nil_of_sublist_nil s β–Έ perm.refl _, nil_sublist _⟩ }, { cases s with _ _ _ s l₁ _ _ s, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ }, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', skip x p', s'.cons2 _ _ _⟩ } }, { cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s, { exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ }, { exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ }, { exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ }, { exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } }, { exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IHβ‚‚ sm in ⟨r₁, pr.trans pm, sr⟩ } end section rel open relator variables {Ξ³ : Type*} {Ξ΄ : Type*} {r : Ξ± β†’ Ξ² β†’ Prop} {p : Ξ³ β†’ Ξ΄ β†’ Prop} local infixr ` ∘r ` : 80 := relation.comp lemma perm_comp_perm : (perm ∘r perm : list Ξ± β†’ list Ξ± β†’ Prop) = perm := begin funext a c, apply propext, split, { exact assume ⟨b, hab, hba⟩, perm.trans hab hba }, { exact assume h, ⟨a, perm.refl a, h⟩ } end lemma perm_comp_forallβ‚‚ {l u v} (hlu : perm l u) (huv : forallβ‚‚ r u v) : (forallβ‚‚ r ∘r perm) l v := begin induction hlu generalizing v, case perm.nil { cases huv, exact ⟨[], forallβ‚‚.nil, perm.nil⟩ }, case perm.skip : a l u hlu ih { cases huv with _ b _ v hab huv', rcases ih huv' with ⟨lβ‚‚, h₁₂, hβ‚‚β‚ƒβŸ©, exact ⟨b::lβ‚‚, forallβ‚‚.cons hab h₁₂, perm.skip _ hβ‚‚β‚ƒβŸ© }, case perm.swap : a₁ aβ‚‚ l₁ lβ‚‚ h₂₃ { cases h₂₃ with _ b₁ _ lβ‚‚ h₁ hr_₂₃, cases hr_₂₃ with _ bβ‚‚ _ lβ‚‚ hβ‚‚ h₁₂, exact ⟨bβ‚‚::b₁::lβ‚‚, forallβ‚‚.cons hβ‚‚ (forallβ‚‚.cons h₁ h₁₂), perm.swap _ _ _⟩ }, case perm.trans : la₁ laβ‚‚ la₃ _ _ ih₁ ihβ‚‚ { rcases ihβ‚‚ huv with ⟨lbβ‚‚, habβ‚‚, hβ‚‚β‚ƒβŸ©, rcases ih₁ habβ‚‚ with ⟨lb₁, hab₁, hβ‚β‚‚βŸ©, exact ⟨lb₁, hab₁, perm.trans h₁₂ hβ‚‚β‚ƒβŸ© } end lemma forallβ‚‚_comp_perm_eq_perm_comp_forallβ‚‚ : forallβ‚‚ r ∘r perm = perm ∘r forallβ‚‚ r := begin funext l₁ l₃, apply propext, split, { assume h, rcases h with ⟨lβ‚‚, h₁₂, hβ‚‚β‚ƒβŸ©, have : forallβ‚‚ (flip r) lβ‚‚ l₁, from forallβ‚‚_flip h₁₂, rcases perm_comp_forallβ‚‚ h₂₃.symm this with ⟨l', h₁, hβ‚‚βŸ©, exact ⟨l', hβ‚‚.symm, forallβ‚‚_flip hβ‚βŸ© }, { exact assume ⟨lβ‚‚, h₁₂, hβ‚‚β‚ƒβŸ©, perm_comp_forallβ‚‚ h₁₂ h₂₃ } end lemma rel_perm_imp (hr : right_unique r) : (forallβ‚‚ r β‡’ forallβ‚‚ r β‡’ implies) perm perm := assume a b h₁ c d hβ‚‚ h, have (flip (forallβ‚‚ r) ∘r (perm ∘r forallβ‚‚ r)) b d, from ⟨a, h₁, c, h, hβ‚‚βŸ©, have ((flip (forallβ‚‚ r) ∘r forallβ‚‚ r) ∘r perm) b d, by rwa [← forallβ‚‚_comp_perm_eq_perm_comp_forallβ‚‚, ← relation.comp_assoc] at this, let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in have b' = b, from right_unique_forallβ‚‚ @hr hcb hbc, this β–Έ hbd lemma rel_perm (hr : bi_unique r) : (forallβ‚‚ r β‡’ forallβ‚‚ r β‡’ (↔)) perm perm := assume a b hab c d hcd, iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp (assume a b c, left_unique_flip hr.1) (forallβ‚‚_flip hab) (forallβ‚‚_flip hcd)) end rel section subperm /-- `subperm l₁ lβ‚‚`, denoted `l₁ <+~ lβ‚‚`, means that `l₁` is a sublist of a permutation of `lβ‚‚`. This is an analogue of `l₁ βŠ† lβ‚‚` which respects multiplicities of elements, and is used for the `≀` relation on multisets. -/ def subperm (l₁ lβ‚‚ : list Ξ±) : Prop := βˆƒ l ~ l₁, l <+ lβ‚‚ infix ` <+~ `:50 := subperm theorem perm.subperm_left {l l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : l <+~ l₁ ↔ l <+~ lβ‚‚ := suffices βˆ€ {l₁ lβ‚‚ : list Ξ±}, l₁ ~ lβ‚‚ β†’ l <+~ l₁ β†’ l <+~ lβ‚‚, from ⟨this p, this p.symm⟩, Ξ» l₁ lβ‚‚ p ⟨u, pu, su⟩, let ⟨v, pv, sv⟩ := exists_perm_sublist su p in ⟨v, pv.trans pu, sv⟩ theorem perm.subperm_right {l₁ lβ‚‚ l : list Ξ±} (p : l₁ ~ lβ‚‚) : l₁ <+~ l ↔ lβ‚‚ <+~ l := ⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩, Ξ» ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩ theorem subperm_of_sublist {l₁ lβ‚‚ : list Ξ±} (s : l₁ <+ lβ‚‚) : l₁ <+~ lβ‚‚ := ⟨l₁, perm.refl _, s⟩ theorem subperm_of_perm {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : l₁ <+~ lβ‚‚ := ⟨lβ‚‚, p.symm, sublist.refl _⟩ theorem subperm.refl (l : list Ξ±) : l <+~ l := subperm_of_perm (perm.refl _) theorem subperm.trans {l₁ lβ‚‚ l₃ : list Ξ±} : l₁ <+~ lβ‚‚ β†’ lβ‚‚ <+~ l₃ β†’ l₁ <+~ l₃ | s ⟨lβ‚‚', pβ‚‚, sβ‚‚βŸ© := let ⟨l₁', p₁, sβ‚βŸ© := pβ‚‚.subperm_left.2 s in ⟨l₁', p₁, s₁.trans sβ‚‚βŸ© theorem length_le_of_subperm {l₁ lβ‚‚ : list Ξ±} : l₁ <+~ lβ‚‚ β†’ length l₁ ≀ length lβ‚‚ | ⟨l, p, s⟩ := perm_length p β–Έ length_le_of_sublist s theorem subperm.perm_of_length_le {l₁ lβ‚‚ : list Ξ±} : l₁ <+~ lβ‚‚ β†’ length lβ‚‚ ≀ length l₁ β†’ l₁ ~ lβ‚‚ | ⟨l, p, s⟩ h := suffices l = lβ‚‚, from this β–Έ p.symm, eq_of_sublist_of_length_le s $ perm_length p.symm β–Έ h theorem subperm.antisymm {l₁ lβ‚‚ : list Ξ±} (h₁ : l₁ <+~ lβ‚‚) (hβ‚‚ : lβ‚‚ <+~ l₁) : l₁ ~ lβ‚‚ := h₁.perm_of_length_le (length_le_of_subperm hβ‚‚) theorem subset_of_subperm {l₁ lβ‚‚ : list Ξ±} : l₁ <+~ lβ‚‚ β†’ l₁ βŠ† lβ‚‚ | ⟨l, p, s⟩ := subset.trans (perm_subset p.symm) (subset_of_sublist s) end subperm theorem exists_perm_append_of_sublist : βˆ€ {l₁ lβ‚‚ : list Ξ±}, l₁ <+ lβ‚‚ β†’ βˆƒ l, lβ‚‚ ~ l₁ ++ l | ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩ | ._ ._ (sublist.cons l₁ lβ‚‚ a s) := let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨a::l, (skip a p).trans perm_middle.symm⟩ | ._ ._ (sublist.cons2 l₁ lβ‚‚ a s) := let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, skip a p⟩ theorem perm_countp (p : Ξ± β†’ Prop) [decidable_pred p] {l₁ lβ‚‚ : list Ξ±} (s : l₁ ~ lβ‚‚) : countp p l₁ = countp p lβ‚‚ := by rw [countp_eq_length_filter, countp_eq_length_filter]; exact perm_length (perm_filter _ s) theorem countp_le_of_subperm (p : Ξ± β†’ Prop) [decidable_pred p] {l₁ lβ‚‚ : list Ξ±} : l₁ <+~ lβ‚‚ β†’ countp p l₁ ≀ countp p lβ‚‚ | ⟨l, p', s⟩ := perm_countp p p' β–Έ countp_le_of_sublist s theorem perm_count [decidable_eq Ξ±] {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) (a) : count a l₁ = count a lβ‚‚ := perm_countp _ p theorem count_le_of_subperm [decidable_eq Ξ±] {l₁ lβ‚‚ : list Ξ±} (s : l₁ <+~ lβ‚‚) (a) : count a l₁ ≀ count a lβ‚‚ := countp_le_of_subperm _ s theorem foldl_eq_of_perm {f : Ξ² β†’ Ξ± β†’ Ξ²} {l₁ lβ‚‚ : list Ξ±} (rcomm : right_commutative f) (p : l₁ ~ lβ‚‚) : βˆ€ b, foldl f b l₁ = foldl f b lβ‚‚ := perm_induction_on p (Ξ» b, rfl) (Ξ» x t₁ tβ‚‚ p r b, r (f b x)) (Ξ» x y t₁ tβ‚‚ p r b, by simp; rw rcomm; exact r (f (f b x) y)) (Ξ» t₁ tβ‚‚ t₃ p₁ pβ‚‚ r₁ rβ‚‚ b, eq.trans (r₁ b) (rβ‚‚ b)) theorem foldr_eq_of_perm {f : Ξ± β†’ Ξ² β†’ Ξ²} {l₁ lβ‚‚ : list Ξ±} (lcomm : left_commutative f) (p : l₁ ~ lβ‚‚) : βˆ€ b, foldr f b l₁ = foldr f b lβ‚‚ := perm_induction_on p (Ξ» b, rfl) (Ξ» x t₁ tβ‚‚ p r b, by simp; rw [r b]) (Ξ» x y t₁ tβ‚‚ p r b, by simp; rw [lcomm, r b]) (Ξ» t₁ tβ‚‚ t₃ p₁ pβ‚‚ r₁ rβ‚‚ a, eq.trans (r₁ a) (rβ‚‚ a)) lemma rec_heq_of_perm {Ξ² : list Ξ± β†’ Sort*} {f : Ξ a l, Ξ² l β†’ Ξ² (a::l)} {b : Ξ² []} {l l' : list Ξ±} (hl : perm l l') (f_congr : βˆ€{a l l' b b'}, perm l l' β†’ b == b' β†’ f a l b == f a l' b') (f_swap : βˆ€{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) : @list.rec Ξ± Ξ² b f l == @list.rec Ξ± Ξ² b f l' := begin induction hl, case list.perm.nil { refl }, case list.perm.skip : a l l' h ih { exact f_congr h ih }, case list.perm.swap : a a' l { exact f_swap }, case list.perm.trans : l₁ lβ‚‚ l₃ h₁ hβ‚‚ ih₁ ihβ‚‚ { exact heq.trans ih₁ ihβ‚‚ } end section variables {op : Ξ± β†’ Ξ± β†’ Ξ±} [is_associative Ξ± op] [is_commutative Ξ± op] local notation a * b := op a b local notation l <*> a := foldl op a l lemma fold_op_eq_of_perm {l₁ lβ‚‚ : list Ξ±} {a : Ξ±} (h : l₁ ~ lβ‚‚) : l₁ <*> a = lβ‚‚ <*> a := foldl_eq_of_perm (right_comm _ (is_commutative.comm _) (is_associative.assoc _)) h _ end section comm_monoid open list variable [comm_monoid Ξ±] @[to_additive list.sum_eq_of_perm] lemma prod_eq_of_perm {l₁ lβ‚‚ : list Ξ±} (h : perm l₁ lβ‚‚) : prod l₁ = prod lβ‚‚ := by induction h; simp [*, mul_left_comm] @[to_additive list.sum_reverse] lemma prod_reverse (l : list Ξ±) : prod l.reverse = prod l := prod_eq_of_perm $ reverse_perm l end comm_monoid theorem perm_inv_core {a : Ξ±} {l₁ lβ‚‚ r₁ rβ‚‚ : list Ξ±} : l₁++a::r₁ ~ lβ‚‚++a::rβ‚‚ β†’ l₁++r₁ ~ lβ‚‚++rβ‚‚ := begin generalize e₁ : l₁++a::r₁ = s₁, generalize eβ‚‚ : lβ‚‚++a::rβ‚‚ = sβ‚‚, intro p, revert l₁ lβ‚‚ r₁ rβ‚‚ e₁ eβ‚‚, refine perm_induction_on p _ (Ξ» x t₁ tβ‚‚ p IH, _) (Ξ» x y t₁ tβ‚‚ p IH, _) (Ξ» t₁ tβ‚‚ t₃ p₁ pβ‚‚ IH₁ IHβ‚‚, _); intros l₁ lβ‚‚ r₁ rβ‚‚ e₁ eβ‚‚, { apply (not_mem_nil a).elim, rw ← e₁, simp }, { cases l₁ with y l₁; cases lβ‚‚ with z lβ‚‚; dsimp at e₁ eβ‚‚; injections; subst x, { substs t₁ tβ‚‚, exact p }, { substs z t₁ tβ‚‚, exact p.trans perm_middle }, { substs y t₁ tβ‚‚, exact perm_middle.symm.trans p }, { substs z t₁ tβ‚‚, exact skip y (IH rfl rfl) } }, { rcases l₁ with _|⟨y, _|⟨z, lβ‚βŸ©βŸ©; rcases lβ‚‚ with _|⟨u, _|⟨v, lβ‚‚βŸ©βŸ©; dsimp at e₁ eβ‚‚; injections; substs x y, { substs r₁ rβ‚‚, exact skip a p }, { substs r₁ rβ‚‚, exact skip u p }, { substs r₁ v tβ‚‚, exact skip u (p.trans perm_middle) }, { substs r₁ rβ‚‚, exact skip y p }, { substs r₁ rβ‚‚ y u, exact skip a p }, { substs r₁ u v tβ‚‚, exact (skip y $ p.trans perm_middle).trans (swap _ _ _) }, { substs rβ‚‚ z t₁, exact skip y (perm_middle.symm.trans p) }, { substs rβ‚‚ y z t₁, exact (swap _ _ _).trans (skip u $ perm_middle.symm.trans p) }, { substs u v t₁ tβ‚‚, exact (swap _ _ _).trans (skip z $ skip y $ IH rfl rfl) } }, { substs t₁ t₃, have : a ∈ tβ‚‚ := perm_subset p₁ (by simp), rcases mem_split this with ⟨lβ‚‚, rβ‚‚, eβ‚‚βŸ©, subst tβ‚‚, exact (IH₁ rfl rfl).trans (IHβ‚‚ rfl rfl) } end theorem perm_cons_inv {a : Ξ±} {l₁ lβ‚‚ : list Ξ±} : a::l₁ ~ a::lβ‚‚ β†’ l₁ ~ lβ‚‚ := @perm_inv_core _ _ [] [] _ _ theorem perm_cons (a : Ξ±) {l₁ lβ‚‚ : list Ξ±} : a::l₁ ~ a::lβ‚‚ ↔ l₁ ~ lβ‚‚ := ⟨perm_cons_inv, skip a⟩ theorem perm_app_left_iff {l₁ lβ‚‚ : list Ξ±} : βˆ€ l, l++l₁ ~ l++lβ‚‚ ↔ l₁ ~ lβ‚‚ | [] := iff.rfl | (a::l) := (perm_cons a).trans (perm_app_left_iff l) theorem perm_app_right_iff {l₁ lβ‚‚ : list Ξ±} (l) : l₁++l ~ lβ‚‚++l ↔ l₁ ~ lβ‚‚ := ⟨λ p, (perm_app_left_iff _).1 $ trans perm_app_comm $ trans p perm_app_comm, perm_app_left _⟩ theorem subperm_cons (a : Ξ±) {l₁ lβ‚‚ : list Ξ±} : a::l₁ <+~ a::lβ‚‚ ↔ l₁ <+~ lβ‚‚ := ⟨λ ⟨l, p, s⟩, begin cases s with _ _ _ s' u _ _ s', { exact (p.subperm_left.2 $ subperm_of_sublist $ sublist_cons _ _).trans (subperm_of_sublist s') }, { exact ⟨u, perm_cons_inv p, s'⟩ } end, Ξ» ⟨l, p, s⟩, ⟨a::l, skip a p, s.cons2 _ _ _⟩⟩ theorem cons_subperm_of_mem {a : Ξ±} {l₁ lβ‚‚ : list Ξ±} (d₁ : nodup l₁) (h₁ : a βˆ‰ l₁) (hβ‚‚ : a ∈ lβ‚‚) (s : l₁ <+~ lβ‚‚) : a :: l₁ <+~ lβ‚‚ := begin rcases s with ⟨l, p, s⟩, induction s generalizing l₁, case list.sublist.slnil { cases hβ‚‚ }, case list.sublist.cons : r₁ rβ‚‚ b s' ih { simp at hβ‚‚, cases hβ‚‚ with e m, { subst b, exact ⟨a::r₁, skip a p, s'.cons2 _ _ _⟩ }, { rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } }, case list.sublist.cons2 : r₁ rβ‚‚ b s' ih { have bm : b ∈ l₁ := (perm_subset p $ mem_cons_self _ _), have am : a ∈ rβ‚‚ := hβ‚‚.resolve_left (Ξ» e, h₁ $ e.symm β–Έ bm), rcases mem_split bm with ⟨t₁, tβ‚‚, rfl⟩, have st : t₁ ++ tβ‚‚ <+ t₁ ++ b :: tβ‚‚ := by simp, rcases ih am (nodup_of_sublist st d₁) (mt (Ξ» x, subset_of_sublist st x) h₁) (perm_cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩, exact ⟨b::t, (skip b p').trans $ (swap _ _ _).trans (skip a perm_middle.symm), s'.cons2 _ _ _⟩ } end theorem subperm_app_left {l₁ lβ‚‚ : list Ξ±} : βˆ€ l, l++l₁ <+~ l++lβ‚‚ ↔ l₁ <+~ lβ‚‚ | [] := iff.rfl | (a::l) := (subperm_cons a).trans (subperm_app_left l) theorem subperm_app_right {l₁ lβ‚‚ : list Ξ±} (l) : l₁++l <+~ lβ‚‚++l ↔ l₁ <+~ lβ‚‚ := (perm_app_comm.subperm_left.trans perm_app_comm.subperm_right).trans (subperm_app_left l) theorem subperm.exists_of_length_lt {l₁ lβ‚‚ : list Ξ±} : l₁ <+~ lβ‚‚ β†’ length l₁ < length lβ‚‚ β†’ βˆƒ a, a :: l₁ <+~ lβ‚‚ | ⟨l, p, s⟩ h := suffices length l < length lβ‚‚ β†’ βˆƒ (a : Ξ±), a :: l <+~ lβ‚‚, from (this $ perm_length p.symm β–Έ h).imp (Ξ» a, (skip a p).subperm_right.1), begin clear subperm.exists_of_length_lt p h l₁, rename lβ‚‚ u, induction s with l₁ lβ‚‚ a s IH _ _ b s IH; intro h, { cases h }, { cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≀ length lβ‚‚) with h h, { exact (IH h).imp (Ξ» a s, s.trans (subperm_of_sublist $ sublist_cons _ _)) }, { exact ⟨a, eq_of_sublist_of_length_eq s h β–Έ subperm.refl _⟩ } }, { exact (IH $ nat.lt_of_succ_lt_succ h).imp (Ξ» a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) } end theorem subperm_of_subset_nodup {l₁ lβ‚‚ : list Ξ±} (d : nodup l₁) (H : l₁ βŠ† lβ‚‚) : l₁ <+~ lβ‚‚ := begin induction d with a l₁' h d IH, { exact ⟨nil, perm.nil, nil_sublist _⟩ }, { cases forall_mem_cons.1 H with H₁ Hβ‚‚, simp at h, exact cons_subperm_of_mem d h H₁ (IH Hβ‚‚) } end theorem perm_ext {l₁ lβ‚‚ : list Ξ±} (d₁ : nodup l₁) (dβ‚‚ : nodup lβ‚‚) : l₁ ~ lβ‚‚ ↔ βˆ€a, a ∈ l₁ ↔ a ∈ lβ‚‚ := ⟨λ p a, mem_of_perm p, Ξ» H, subperm.antisymm (subperm_of_subset_nodup d₁ (Ξ» a, (H a).1)) (subperm_of_subset_nodup dβ‚‚ (Ξ» a, (H a).2))⟩ theorem perm_ext_sublist_nodup {l₁ lβ‚‚ l : list Ξ±} (d : nodup l) (s₁ : l₁ <+ l) (sβ‚‚ : lβ‚‚ <+ l) : l₁ ~ lβ‚‚ ↔ l₁ = lβ‚‚ := ⟨λ h, begin induction sβ‚‚ with lβ‚‚ l a sβ‚‚ IH lβ‚‚ l a sβ‚‚ IH generalizing l₁, { exact eq_nil_of_perm_nil h.symm }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { exact IH d.2 s₁ h }, { apply d.1.elim, exact subset_of_subperm ⟨_, h.symm, sβ‚‚βŸ© (mem_cons_self _ _) } }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { apply d.1.elim, exact subset_of_subperm ⟨_, h, sβ‚βŸ© (mem_cons_self _ _) }, { rw IH d.2 s₁ (perm_cons_inv h) } } end, Ξ» h, by rw h⟩ section variable [decidable_eq Ξ±] -- attribute [congr] theorem erase_perm_erase (a : Ξ±) {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : l₁.erase a ~ lβ‚‚.erase a := if h₁ : a ∈ l₁ then have hβ‚‚ : a ∈ lβ‚‚, from perm_subset p h₁, perm_cons_inv $ trans (perm_erase h₁).symm $ trans p (perm_erase hβ‚‚) else have hβ‚‚ : a βˆ‰ lβ‚‚, from mt (mem_of_perm p).2 h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem hβ‚‚]; exact p theorem perm_diff_left {l₁ lβ‚‚ : list Ξ±} (t : list Ξ±) (h : l₁ ~ lβ‚‚) : l₁.diff t ~ lβ‚‚.diff t := by induction t generalizing l₁ lβ‚‚ h; simp [*, erase_perm_erase] theorem perm_diff_right (l : list Ξ±) {t₁ tβ‚‚ : list Ξ±} (h : t₁ ~ tβ‚‚) : l.diff t₁ = l.diff tβ‚‚ := by induction h generalizing l; simp [*, erase_perm_erase, erase_comm] <|> exact (ih_1 _).trans (ih_2 _) theorem perm_bag_inter_left {l₁ lβ‚‚ : list Ξ±} (t : list Ξ±) (h : l₁ ~ lβ‚‚) : l₁.bag_inter t ~ lβ‚‚.bag_inter t := begin induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp}, { by_cases x ∈ t; simp [*, skip] }, { by_cases x = y, {simp [h]}, by_cases xt : x ∈ t; by_cases yt : y ∈ t, { simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] }, { simp [xt, yt, mt mem_of_mem_erase, skip] }, { simp [xt, yt, mt mem_of_mem_erase, skip] }, { simp [xt, yt] } }, { exact (ih_1 _).trans (ih_2 _) } end theorem perm_bag_inter_right (l : list Ξ±) {t₁ tβ‚‚ : list Ξ±} (p : t₁ ~ tβ‚‚) : l.bag_inter t₁ = l.bag_inter tβ‚‚ := begin induction l with a l IH generalizing t₁ tβ‚‚ p, {simp}, by_cases a ∈ t₁, { simp [h, (mem_of_perm p).1 h, IH (erase_perm_erase _ p)] }, { simp [h, mt (mem_of_perm p).2 h, IH p] } end theorem cons_perm_iff_perm_erase {a : Ξ±} {l₁ lβ‚‚ : list Ξ±} : a::l₁ ~ lβ‚‚ ↔ a ∈ lβ‚‚ ∧ l₁ ~ lβ‚‚.erase a := ⟨λ h, have a ∈ lβ‚‚, from perm_subset h (mem_cons_self a l₁), ⟨this, perm_cons_inv $ h.trans $ perm_erase this⟩, Ξ» ⟨m, h⟩, trans (skip a h) (perm_erase m).symm⟩ theorem perm_iff_count {l₁ lβ‚‚ : list Ξ±} : l₁ ~ lβ‚‚ ↔ βˆ€ a, count a l₁ = count a lβ‚‚ := ⟨perm_count, Ξ» H, begin induction l₁ with a l₁ IH generalizing lβ‚‚, { cases lβ‚‚ with b lβ‚‚, {refl}, specialize H b, simp at H, contradiction }, { have : a ∈ lβ‚‚ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos), refine trans (skip a $ IH $ Ξ» b, _) (perm_erase this).symm, specialize H b, rw perm_count (perm_erase this) at H, by_cases b = a; simp [h] at H ⊒; assumption } end⟩ instance decidable_perm : βˆ€ (l₁ lβ‚‚ : list Ξ±), decidable (l₁ ~ lβ‚‚) | [] [] := is_true $ perm.refl _ | [] (b::lβ‚‚) := is_false $ Ξ» h, by have := eq_nil_of_perm_nil h; contradiction | (a::l₁) lβ‚‚ := by haveI := decidable_perm l₁ (lβ‚‚.erase a); exact decidable_of_iff' _ cons_perm_iff_perm_erase -- @[congr] theorem perm_erase_dup_of_perm {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : erase_dup l₁ ~ erase_dup lβ‚‚ := perm_iff_count.2 $ Ξ» a, if h : a ∈ l₁ then by simp [nodup_erase_dup, h, perm_subset p h] else by simp [h, mt (mem_of_perm p).2 h] -- attribute [congr] theorem perm_insert (a : Ξ±) {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : insert a l₁ ~ insert a lβ‚‚ := if h : a ∈ l₁ then by simpa [h, perm_subset p h] using p else by simpa [h, mt (mem_of_perm p).2 h] using skip a p theorem perm_insert_swap (x y : Ξ±) (l : list Ξ±) : insert x (insert y l) ~ insert y (insert x l) := begin by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl], by_cases xy : x = y, { simp [xy] }, simp [not_mem_cons_of_ne_of_not_mem xy xl, not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl], constructor end theorem perm_union_left {l₁ lβ‚‚ : list Ξ±} (t₁ : list Ξ±) (h : l₁ ~ lβ‚‚) : l₁ βˆͺ t₁ ~ lβ‚‚ βˆͺ t₁ := begin induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp}, { exact perm_insert a ih }, { apply perm_insert_swap }, { exact ih_1.trans ih_2 } end theorem perm_union_right (l : list Ξ±) {t₁ tβ‚‚ : list Ξ±} (h : t₁ ~ tβ‚‚) : l βˆͺ t₁ ~ l βˆͺ tβ‚‚ := by induction l; simp [*, perm_insert] -- @[congr] theorem perm_union {l₁ lβ‚‚ t₁ tβ‚‚ : list Ξ±} (p₁ : l₁ ~ lβ‚‚) (pβ‚‚ : t₁ ~ tβ‚‚) : l₁ βˆͺ t₁ ~ lβ‚‚ βˆͺ tβ‚‚ := trans (perm_union_left t₁ p₁) (perm_union_right lβ‚‚ pβ‚‚) theorem perm_inter_left {l₁ lβ‚‚ : list Ξ±} (t₁ : list Ξ±) : l₁ ~ lβ‚‚ β†’ l₁ ∩ t₁ ~ lβ‚‚ ∩ t₁ := perm_filter _ theorem perm_inter_right (l : list Ξ±) {t₁ tβ‚‚ : list Ξ±} (p : t₁ ~ tβ‚‚) : l ∩ t₁ = l ∩ tβ‚‚ := by dsimp [(∩), list.inter]; congr; funext a; rw [mem_of_perm p] -- @[congr] theorem perm_inter {l₁ lβ‚‚ t₁ tβ‚‚ : list Ξ±} (p₁ : l₁ ~ lβ‚‚) (pβ‚‚ : t₁ ~ tβ‚‚) : l₁ ∩ t₁ ~ lβ‚‚ ∩ tβ‚‚ := perm_inter_right lβ‚‚ pβ‚‚ β–Έ perm_inter_left t₁ p₁ end theorem perm_pairwise {R : Ξ± β†’ Ξ± β†’ Prop} (S : symmetric R) : βˆ€ {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚), pairwise R l₁ ↔ pairwise R lβ‚‚ := suffices βˆ€ {l₁ lβ‚‚}, l₁ ~ lβ‚‚ β†’ pairwise R l₁ β†’ pairwise R lβ‚‚, from Ξ» l₁ lβ‚‚ p, ⟨this p, this p.symm⟩, Ξ» l₁ lβ‚‚ p d, begin induction d with a l₁ h d IH generalizing lβ‚‚, { rw eq_nil_of_perm_nil p, constructor }, { have : a ∈ lβ‚‚ := perm_subset p (mem_cons_self _ _), rcases mem_split this with ⟨sβ‚‚, tβ‚‚, rfl⟩, have p' := perm_cons_inv (p.trans perm_middle), refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩), exact h _ (perm_subset p'.symm m) } end theorem perm_nodup {l₁ lβ‚‚ : list Ξ±} : l₁ ~ lβ‚‚ β†’ (nodup l₁ ↔ nodup lβ‚‚) := perm_pairwise $ @ne.symm Ξ± theorem perm_bind_left {l₁ lβ‚‚ : list Ξ±} (f : Ξ± β†’ list Ξ²) (p : l₁ ~ lβ‚‚) : l₁.bind f ~ lβ‚‚.bind f := begin induction p with a l₁ lβ‚‚ p IH a b l l₁ lβ‚‚ l₃ p₁ pβ‚‚ IH₁ IHβ‚‚, {simp}, { simp, exact perm_app_right _ IH }, { simp, rw [← append_assoc, ← append_assoc], exact perm_app_left _ perm_app_comm }, { exact trans IH₁ IHβ‚‚ } end theorem perm_bind_right (l : list Ξ±) {f g : Ξ± β†’ list Ξ²} (h : βˆ€ a, f a ~ g a) : l.bind f ~ l.bind g := by induction l with a l IH; simp; exact perm_app (h a) IH theorem perm_product_left {l₁ lβ‚‚ : list Ξ±} (t₁ : list Ξ²) (p : l₁ ~ lβ‚‚) : product l₁ t₁ ~ product lβ‚‚ t₁ := perm_bind_left _ p theorem perm_product_right (l : list Ξ±) {t₁ tβ‚‚ : list Ξ²} (p : t₁ ~ tβ‚‚) : product l t₁ ~ product l tβ‚‚ := perm_bind_right _ $ Ξ» a, perm_map _ p @[congr] theorem perm_product {l₁ lβ‚‚ : list Ξ±} {t₁ tβ‚‚ : list Ξ²} (p₁ : l₁ ~ lβ‚‚) (pβ‚‚ : t₁ ~ tβ‚‚) : product l₁ t₁ ~ product lβ‚‚ tβ‚‚ := trans (perm_product_left t₁ p₁) (perm_product_right lβ‚‚ pβ‚‚) theorem sublists_cons_perm_append (a : Ξ±) (l : list Ξ±) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := begin simp [sublists, sublists_aux_cons_cons], refine skip _ ((skip _ _).trans perm_middle.symm), induction sublists_aux l cons with b l IH; simp, exact skip b ((skip _ IH).trans perm_middle.symm) end theorem sublists_perm_sublists' : βˆ€ l : list Ξ±, sublists l ~ sublists' l | [] := perm.refl _ | (a::l) := let IH := sublists_perm_sublists' l in by rw sublists'_cons; exact (sublists_cons_perm_append _ _).trans (perm_app IH (perm_map _ IH)) /- enumerating permutations -/ section permutations theorem permutations_aux2_fst (t : Ξ±) (ts : list Ξ±) (r : list Ξ²) : βˆ€ (ys : list Ξ±) (f : list Ξ± β†’ Ξ²), (permutations_aux2 t ts r ys f).1 = ys ++ ts | [] f := rfl | (y::ys) f := match _, permutations_aux2_fst ys _ : βˆ€ o : list Ξ± Γ— list Ξ², o.1 = ys ++ ts β†’ (permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with | ⟨_, zs⟩, rfl := rfl end @[simp] theorem permutations_aux2_snd_nil (t : Ξ±) (ts : list Ξ±) (r : list Ξ²) (f : list Ξ± β†’ Ξ²) : (permutations_aux2 t ts r [] f).2 = r := rfl @[simp] theorem permutations_aux2_snd_cons (t : Ξ±) (ts : list Ξ±) (r : list Ξ²) (y : Ξ±) (ys : list Ξ±) (f : list Ξ± β†’ Ξ²) : (permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) :: (permutations_aux2 t ts r ys (Ξ»x : list Ξ±, f (y::x))).2 := match _, permutations_aux2_fst t ts r _ _ : βˆ€ o : list Ξ± Γ— list Ξ², o.1 = ys ++ ts β†’ (permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with | ⟨_, zs⟩, rfl := rfl end theorem permutations_aux2_append (t : Ξ±) (ts : list Ξ±) (r : list Ξ²) (ys : list Ξ±) (f : list Ξ± β†’ Ξ²) : (permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 := by induction ys generalizing f; simp * theorem mem_permutations_aux2 {t : Ξ±} {ts : list Ξ±} {ys : list Ξ±} {l l' : list Ξ±} : l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔ βˆƒ l₁ lβ‚‚, lβ‚‚ β‰  [] ∧ ys = l₁ ++ lβ‚‚ ∧ l' = l ++ l₁ ++ t :: lβ‚‚ ++ ts := begin induction ys with y ys ih generalizing l, { simp {contextual := tt} }, { rw [permutations_aux2_snd_cons, show (Ξ» (x : list Ξ±), l ++ y :: x) = append (l ++ [y]), by funext; simp, mem_cons_iff, ih], split; intro h, { rcases h with e | ⟨l₁, lβ‚‚, l0, ye, _⟩, { subst l', exact ⟨[], y::ys, by simp⟩ }, { substs l' ys, exact ⟨y::l₁, lβ‚‚, l0, by simp⟩ } }, { rcases h with ⟨_ | ⟨y', lβ‚βŸ©, lβ‚‚, l0, ye, rfl⟩, { simp [ye] }, { simp at ye, rcases ye with ⟨rfl, rfl⟩, exact or.inr ⟨l₁, lβ‚‚, l0, by simp⟩ } } } end theorem mem_permutations_aux2' {t : Ξ±} {ts : list Ξ±} {ys : list Ξ±} {l : list Ξ±} : l ∈ (permutations_aux2 t ts [] ys id).2 ↔ βˆƒ l₁ lβ‚‚, lβ‚‚ β‰  [] ∧ ys = l₁ ++ lβ‚‚ ∧ l = l₁ ++ t :: lβ‚‚ ++ ts := by rw [show @id (list Ξ±) = append nil, by funext; refl]; apply mem_permutations_aux2 theorem length_permutations_aux2 (t : Ξ±) (ts : list Ξ±) (ys : list Ξ±) (f : list Ξ± β†’ Ξ²) : length (permutations_aux2 t ts [] ys f).2 = length ys := by induction ys generalizing f; simp * theorem foldr_permutations_aux2 (t : Ξ±) (ts : list Ξ±) (r L : list (list Ξ±)) : foldr (Ξ»y r, (permutations_aux2 t ts r y id).2) r L = L.bind (Ξ» y, (permutations_aux2 t ts [] y id).2) ++ r := by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}] theorem mem_foldr_permutations_aux2 {t : Ξ±} {ts : list Ξ±} {r L : list (list Ξ±)} {l' : list Ξ±} : l' ∈ foldr (Ξ»y r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨ βˆƒ l₁ lβ‚‚, l₁ ++ lβ‚‚ ∈ L ∧ lβ‚‚ β‰  [] ∧ l' = l₁ ++ t :: lβ‚‚ ++ ts := have (βˆƒ (a : list Ξ±), a ∈ L ∧ βˆƒ (l₁ lβ‚‚ : list Ξ±), Β¬lβ‚‚ = nil ∧ a = l₁ ++ lβ‚‚ ∧ l' = l₁ ++ t :: (lβ‚‚ ++ ts)) ↔ βˆƒ (l₁ lβ‚‚ : list Ξ±), Β¬lβ‚‚ = nil ∧ l₁ ++ lβ‚‚ ∈ L ∧ l' = l₁ ++ t :: (lβ‚‚ ++ ts), from ⟨λ ⟨a, aL, l₁, lβ‚‚, l0, e, h⟩, ⟨l₁, lβ‚‚, l0, e β–Έ aL, h⟩, Ξ» ⟨l₁, lβ‚‚, l0, aL, h⟩, ⟨_, aL, l₁, lβ‚‚, l0, rfl, h⟩⟩, by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this, or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc] theorem length_foldr_permutations_aux2 (t : Ξ±) (ts : list Ξ±) (r L : list (list Ξ±)) : length (foldr (Ξ»y r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r := by simp [foldr_permutations_aux2, (∘), length_permutations_aux2] theorem length_foldr_permutations_aux2' (t : Ξ±) (ts : list Ξ±) (r L : list (list Ξ±)) (n) (H : βˆ€ l ∈ L, length l = n) : length (foldr (Ξ»y r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r := begin rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)], induction L with l L ih, {simp}, simp [ih (Ξ» l m, H l (mem_cons_of_mem _ m)), H l (mem_cons_self _ _), mul_add] end theorem perm_of_mem_permutations_aux : βˆ€ {ts is l : list Ξ±}, l ∈ permutations_aux ts is β†’ l ~ ts ++ is := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2 m, rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m, rcases m with m | ⟨l₁, lβ‚‚, m, _, e⟩, { exact (IH1 m).trans perm_middle }, { subst e, have p : l₁ ++ lβ‚‚ ~ is, { simp [permutations] at m, cases m with e m, {simp [e]}, exact is.append_nil β–Έ IH2 m }, exact (perm_app_left _ (perm_middle.trans (skip _ p))).trans (skip _ perm_app_comm) } end theorem perm_of_mem_permutations {l₁ lβ‚‚ : list Ξ±} (h : l₁ ∈ permutations lβ‚‚) : l₁ ~ lβ‚‚ := (eq_or_mem_of_mem_cons h).elim (Ξ» e, e β–Έ perm.refl _) (Ξ» m, append_nil lβ‚‚ β–Έ perm_of_mem_permutations_aux m) theorem length_permutations_aux : βˆ€ ts is : list Ξ±, length (permutations_aux ts is) + is.length.fact = (length ts + length is).fact := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2, have IH2 : length (permutations_aux is nil) + 1 = is.length.fact, { simpa using IH2 }, simp [-add_comm, nat.fact, nat.add_succ, mul_comm] at IH1, rw [permutations_aux_cons, length_foldr_permutations_aux2' _ _ _ _ _ (Ξ» l m, perm_length (perm_of_mem_permutations m)), permutations, length, length, IH2, nat.succ_add, nat.fact_succ, mul_comm (nat.succ _), ← IH1, add_comm (_*_), add_assoc, nat.mul_succ, mul_comm] end theorem length_permutations (l : list Ξ±) : length (permutations l) = (length l).fact := length_permutations_aux l [] theorem mem_permutations_of_perm_lemma {is l : list Ξ±} (H : l ~ [] ++ is β†’ (βˆƒ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is []) : l ~ is β†’ l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutations_aux_of_perm : βˆ€ {ts is l : list Ξ±}, l ~ is ++ ts β†’ (βˆƒ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2 l p, rw [permutations_aux_cons, mem_foldr_permutations_aux2], rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m, { clear p, subst e, rcases mem_split (perm_subset p'.symm (mem_cons_self _ _)) with ⟨l₁, lβ‚‚, e⟩, subst is', have p := perm_cons_inv (perm_middle.symm.trans p'), cases lβ‚‚ with a lβ‚‚', { exact or.inl ⟨l₁, by simpa using p⟩ }, { exact or.inr (or.inr ⟨l₁, a::lβ‚‚', mem_permutations_of_perm_lemma IH2 p, by simp⟩) } }, { exact or.inr (or.inl m) } end @[simp] theorem mem_permutations (s t : list Ξ±) : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩ end permutations end list
ebb67937cd7b7e97b72e92f0708ee78751a4eeb2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/test/globs/Test/Subtest/1.lean
9116a5ee3a7f8e5fb0b10cbbc3e9550df37ce6d2
[ "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
36
lean
#eval "visited Test/Subtest/1.lean"
7ae0869a3fc60b6e414836dc9c7df15a082a41dd
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/defs.lean
7e9234c6067050bd43b1fcdda4ad70a26c492b64
[ "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
1,929
lean
import data.real.basic import data.set.intervals import tactic export has_Sup (Sup) has_Inf (Inf) namespace real_number_game -- hide (need to choose this or P) class nonemptyT (S : set ℝ) : Type := (x : ℝ) (thm : x ∈ S) -- hide (need to choose this or T) class nonemptyP (S : set ℝ) : Prop := (thm' : βˆƒ x : ℝ, x ∈ S) def nonemptyP.thm (S : set ℝ) [nonemptyP S] : βˆƒ x : ℝ, x ∈ S := nonemptyP.thm' -- irrelevant example example : βˆƒ x: ℝ, x < 1 := ⟨0.5, by norm_num⟩ example : (0.5 : ℝ) < 1 := by norm_num -- irrelevant example noncomputable example : nonemptyT (set.Icc 0 1) := { x := 0.5, thm := by {simp,split;norm_num} } -- show def is_upper_bound (S : set ℝ) (b : ℝ) : Prop := βˆ€ s ∈ S, s ≀ b -- hide this def class bounded_aboveT (S : set ℝ) : Type := (b : ℝ) (thm : is_upper_bound S b) -- hide this def class bounded_aboveP (S : set ℝ) : Prop := (thm' : βˆƒ b : ℝ, is_upper_bound S b) def bounded_aboveP.thm (S : set ℝ) [bounded_aboveP S] : βˆƒ b : ℝ, is_upper_bound S b := bounded_aboveP.thm' -- example (for me only) instance : bounded_aboveT (set.Icc 0 1) := { b := 2, thm := Ξ» r ⟨h1, h2⟩, le_trans h2 (by norm_num) } -- hide noncomputable def Sup (S : set ℝ) [nonemptyP S] [bounded_aboveP S] := Sup S -- state as axiom; hide proof theorem le_Sup {S : set ℝ} [nonemptyP S] [bounded_aboveP S] : βˆ€ x ∈ S, x ≀ Sup S := begin apply real.le_Sup, cases bounded_aboveP.thm S with b hb, use b, exact hb, end -- state as axiom; hide proof theorem Sup_le {S : set ℝ} [nonemptyP S] [bounded_aboveP S] : βˆ€ b : ℝ, is_upper_bound S b β†’ Sup S ≀ b := begin intros b hb, show has_Sup.Sup S ≀ b, rw real.Sup_le, { exact hb}, { cases nonemptyP.thm S with c hc, use c, exact hc}, { use b, exact hb} end -- other axioms: β„€ unbounded, linearly ordered field. -- Might need to introduce later. end real_number_game
f48dbe91fb37286d505042a64f28dceefedb2bbd
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Data/Lsp/Extra.lean
9d496c5ba78b4196847ffa113cc740b874ef0ce9
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
5,718
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.JsonRpc import Lean.Data.Lsp.Basic /-! This file contains Lean-specific extensions to LSP. See the structures below for which additional requests and notifications are supported. -/ namespace Lean.Lsp open Json /-- `textDocument/waitForDiagnostics` client->server request. Yields a response when all the diagnostics for a version of the document greater or equal to the specified one have been emitted. If the request specifies a version above the most recently processed one, the server will delay the response until it does receive the specified version. Exists for synchronization purposes, e.g. during testing or when external tools might want to use our LSP server. -/ structure WaitForDiagnosticsParams where uri : DocumentUri version : Nat deriving FromJson, ToJson /-- `textDocument/waitForDiagnostics` client<-server reply. -/ structure WaitForDiagnostics instance : FromJson WaitForDiagnostics := ⟨fun j => WaitForDiagnostics.mk⟩ instance : ToJson WaitForDiagnostics := ⟨fun o => mkObj []⟩ inductive LeanFileProgressKind | processing | fatalError deriving Inhabited, BEq instance : FromJson LeanFileProgressKind := ⟨fun j => match j.getNat? with | Except.ok 1 => LeanFileProgressKind.processing | Except.ok 2 => LeanFileProgressKind.fatalError | _ => throw s!"unknown LeanFileProgressKind '{j}'"⟩ instance : ToJson LeanFileProgressKind := ⟨fun | LeanFileProgressKind.processing => 1 | LeanFileProgressKind.fatalError => 2⟩ structure LeanFileProgressProcessingInfo where range : Range kind : LeanFileProgressKind := LeanFileProgressKind.processing deriving FromJson, ToJson /-- `$/lean/fileProgress` client<-server notification. Contains the ranges of the document that are currently being processed by the server. -/ structure LeanFileProgressParams where textDocument : VersionedTextDocumentIdentifier processing : Array LeanFileProgressProcessingInfo deriving FromJson, ToJson /-- `$/lean/plainGoal` client->server request. If there is a tactic proof at the specified position, returns the current goals. Otherwise returns `null`. -/ structure PlainGoalParams extends TextDocumentPositionParams deriving FromJson, ToJson /-- `$/lean/plainGoal` client<-server reply. -/ structure PlainGoal where /-- The goals as pretty-printed Markdown, or something like "no goals" if accomplished. -/ rendered : String /-- The pretty-printed goals, empty if all accomplished. -/ goals : Array String deriving FromJson, ToJson /-- `$/lean/plainTermGoal` client->server request. Returns the expected type at the specified position, pretty-printed as a string. -/ structure PlainTermGoalParams extends TextDocumentPositionParams deriving FromJson, ToJson /-- `$/lean/plainTermGoal` client<-server reply. -/ structure PlainTermGoal where goal : String range : Range deriving FromJson, ToJson /-- An object which RPC clients can refer to without marshalling. -/ structure RpcRef where /- NOTE(WN): It is important for this to be a single-field structure in order to deserialize as an `Object` on the JS side. -/ p : USize deriving BEq, Hashable, FromJson, ToJson instance : ToString RpcRef where toString r := toString r.p /-- `$/lean/rpc/connect` client->server request. Starts an RPC session at the given file's worker, replying with the new session ID. Multiple sessions may be started and operating concurrently. A session may be destroyed by the server at any time (e.g. due to a crash), in which case further RPC requests for that session will reply with `RpcNeedsReconnect` errors. The client should discard references held from that session and `connect` again. -/ structure RpcConnectParams where uri : DocumentUri deriving FromJson, ToJson /-- `$/lean/rpc/connect` client<-server reply. Indicates that an RPC connection had been made and a session started for it. -/ structure RpcConnected where sessionId : UInt64 deriving FromJson, ToJson /-- `$/lean/rpc/call` client->server request. A request to execute a procedure bound for RPC. If an incorrect session ID is present, the server errors with `RpcNeedsReconnect`. Extending TDPP is weird. But in Lean, symbols exist in the context of a position within a source file. So we need this to refer to code in the environment at that position. -/ structure RpcCallParams extends TextDocumentPositionParams where sessionId : UInt64 /-- Procedure to invoke. Must be fully qualified. -/ method : Name params : Json deriving FromJson, ToJson /-- `$/lean/rpc/release` client->server notification. A notification to release remote references. Should be sent by the client when it no longer needs `RpcRef`s it has previously received from the server. Not doing so is safe but will leak memory. -/ structure RpcReleaseParams where uri : DocumentUri sessionId : UInt64 refs : Array RpcRef deriving FromJson, ToJson /-- `$/lean/rpc/keepAlive` client->server notification. The client must send an RPC notification every 10s in order to keep the RPC session alive. This is the simplest one. On not seeing any notifications for three 10s periods, the server will drop the RPC session and its associated references. -/ structure RpcKeepAliveParams where uri : DocumentUri sessionId : UInt64 deriving FromJson, ToJson /-- Range of lines in a document, including `start` but excluding `end`. -/ structure LineRange where start : Nat «end» : Nat deriving Inhabited, Repr, FromJson, ToJson end Lean.Lsp
f2482f18a98b46a857dbda8bbf7fc6aa3fc27b17
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Util/Closure.lean
0e51a8183f7d4032b0643da288f5d8a9244da99b
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,262
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.ShareCommon import Init.Lean.MetavarContext import Init.Lean.Environment import Init.Lean.Util.FoldConsts namespace Lean namespace Closure structure Context := (mctx : MetavarContext) (lctxInput : LocalContext) structure State := (lctxOutput : LocalContext := {}) (ngen : NameGenerator := { namePrefix := `_closure }) (visitedLevel : LevelMap Level := {}) (visitedExpr : ExprStructMap Expr := {}) (levelParams : Array Name := #[]) (nextLevelIdx : Nat := 1) (levelClosure : Array Level := #[]) (nextExprIdx : Nat := 1) (exprClosure : Array Expr := #[]) def Exception := String abbrev ClosureM := ReaderT Context (EStateM Exception State) @[inline] def visitLevel (f : Level β†’ ClosureM Level) (u : Level) : ClosureM Level := if !u.hasMVar && !u.hasParam then pure u else do s ← get; match s.visitedLevel.find? u with | some v => pure v | none => do v ← f u; modify $ fun s => { s with visitedLevel := s.visitedLevel.insert u v }; pure v def mkNewLevelParam (u : Level) : ClosureM Level := do s ← get; let p := (`u).appendIndexAfter s.nextLevelIdx; modify $ fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelClosure := s.levelClosure.push u }; pure $ mkLevelParam p partial def collectLevelAux : Level β†’ ClosureM Level | u@(Level.succ v _) => do v ← visitLevel collectLevelAux v; pure $ u.updateSucc! v | u@(Level.max v w _) => do v ← visitLevel collectLevelAux v; w ← visitLevel collectLevelAux w; pure $ u.updateMax! v w | u@(Level.imax v w _) => do v ← visitLevel collectLevelAux v; w ← visitLevel collectLevelAux w; pure $ u.updateIMax! v w | u@(Level.mvar _ _) => mkNewLevelParam u | u@(Level.param _ _) => mkNewLevelParam u | u@(Level.zero _) => pure u def collectLevel (u : Level) : ClosureM Level := visitLevel collectLevelAux u def mkFreshFVarId : ClosureM FVarId := do s ← get; let id := s.ngen.curr; modify $ fun s => { s with ngen := s.ngen.next }; pure id /-- Remark: This method does not guarantee unique user names. The correctness of the procedure does not rely on unique user names. Recall that the pretty printer takes care of unintended collisions. -/ def mkNextUserName : ClosureM Name := do s ← get; let n := (`_x).appendIndexAfter s.nextExprIdx; modify $ fun s => { s with nextExprIdx := s.nextExprIdx + 1 }; pure n def getUserName (userName? : Option Name) : ClosureM Name := match userName? with | some userName => pure userName | none => mkNextUserName def mkLocalDecl (userName? : Option Name) (type : Expr) : ClosureM Expr := do userName ← getUserName userName?; fvarId ← mkFreshFVarId; modify $ fun s => { s with lctxOutput := s.lctxOutput.mkLocalDecl fvarId userName type }; pure $ mkFVar fvarId def mkLetDecl (userName : Name) (type : Expr) (value : Expr) : ClosureM Expr := do fvarId ← mkFreshFVarId; modify $ fun s => { s with lctxOutput := s.lctxOutput.mkLetDecl fvarId userName type value }; pure $ mkFVar fvarId @[inline] def visitExpr (f : Expr β†’ ClosureM Expr) (e : Expr) : ClosureM Expr := if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then pure e else do s ← get; match s.visitedExpr.find? e with | some r => pure r | none => do r ← f e; modify $ fun s => { s with visitedExpr := s.visitedExpr.insert e r }; pure r partial def collectExprAux : Expr β†’ ClosureM Expr | e => let collect (e : Expr) := visitExpr collectExprAux e; match e with | Expr.proj _ _ s _ => do s ← collect s; pure (e.updateProj! s) | Expr.forallE _ d b _ => do d ← collect d; b ← collect b; pure (e.updateForallE! d b) | Expr.lam _ d b _ => do d ← collect d; b ← collect b; pure (e.updateLambdaE! d b) | Expr.letE _ t v b _ => do t ← collect t; v ← collect v; b ← collect b; pure (e.updateLet! t v b) | Expr.app f a _ => do f ← collect f; a ← collect a; pure (e.updateApp! f a) | Expr.mdata _ b _ => do b ← collect b; pure (e.updateMData! b) | Expr.sort u _ => do u ← collectLevel u; pure (e.updateSort! u) | Expr.const c us _ => do us ← us.mapM collectLevel; pure (e.updateConst! us) | Expr.mvar mvarId _ => do ctx ← read; match ctx.mctx.findDecl? mvarId with | none => throw "unknown metavariable" | some mvarDecl => do type ← collect mvarDecl.type; x ← mkLocalDecl none type; modify $ fun s => { s with exprClosure := s.exprClosure.push e }; pure x | Expr.fvar fvarId _ => do ctx ← read; match ctx.lctxInput.find? fvarId with | none => throw "unknown free variable" | some (LocalDecl.cdecl _ _ userName type _) => do type ← collect type; x ← mkLocalDecl userName type; modify $ fun s => { s with exprClosure := s.exprClosure.push e }; pure x | some (LocalDecl.ldecl _ _ userName type value) => do type ← collect type; value ← collect value; -- Note that let-declarations do not need to be provided to the closure being constructed. mkLetDecl userName type value | e => pure e def collectExpr (e : Expr) : ClosureM Expr := visitExpr collectExprAux e structure MkClosureResult := (levelParams : Array Name) (type : Expr) (value : Expr) (levelClosure : Array Level) (exprClosure : Array Expr) def mkClosure (mctx : MetavarContext) (lctx : LocalContext) (type : Expr) (value : Expr) : Except String MkClosureResult := let shareCommonTypeValue : ShareCommonM (Expr Γ— Expr) := do { type ← withShareCommon type; value ← withShareCommon value; pure (type, value) }; let (type, value) := shareCommonTypeValue.run; let mkTypeValue : ClosureM (Expr Γ— Expr) := do { type ← collectExpr type; value ← collectExpr value; pure (type, value) }; match (mkTypeValue { mctx := mctx, lctxInput := lctx }).run {} with | EStateM.Result.ok (type, value) s => let fvars := s.lctxOutput.getFVars; let type := s.lctxOutput.mkForall fvars type; let value := s.lctxOutput.mkLambda fvars value; Except.ok { levelParams := s.levelParams, type := type, value := value, levelClosure := s.levelClosure, exprClosure := s.exprClosure } | EStateM.Result.error ex s => Except.error ex end Closure def mkAuxDefinition (env : Environment) (opts : Options) (mctx : MetavarContext) (lctx : LocalContext) (name : Name) (type : Expr) (value : Expr) : Except KernelException (Expr Γ— Environment) := match Closure.mkClosure mctx lctx type value with | Except.error ex => throw $ KernelException.other ex | Except.ok result => do let decl := Declaration.defnDecl { name := name, lparams := result.levelParams.toList, type := result.type, value := result.value, hints := ReducibilityHints.regular (getMaxHeight env result.value + 1), isUnsafe := env.hasUnsafe result.type || env.hasUnsafe result.value }; env ← env.addAndCompile opts decl; let c := mkAppN (mkConst name result.levelClosure.toList) result.exprClosure; pure (c, env) end Lean
2f1ce6b03f145204d8ee807e6b92f40e4deeeb5b
d8870c0d7a56f998464cfef82fdac792d2fd9dac
/homework/hw04.lean
3b31634f06c97855e2d7c9c28cb3b6d88e72a0f9
[]
no_license
williamdemeo/math2001-spring2019
565b70405e7b92c5f93a295d2114729786350b78
1b3bf3e0bf53684b064b3f96210ce1022850ebf0
refs/heads/master
1,587,030,510,505
1,558,394,100,000
1,558,394,100,000
165,477,693
2
1
null
null
null
null
UTF-8
Lean
false
false
840
lean
-- Math 2001 Homework 04 Lean Exercises -- 5.3.6. -- Prove Β¬ (A ∧ B) β†’ Β¬ A ∨ Β¬ B by replacing the sorry's below by proofs. open classical variables {A B C : Prop} lemma step1 (h₁ : Β¬ (A ∧ B)) (hβ‚‚ : A) : Β¬ A ∨ Β¬ B := have Β¬ B, from sorry, show Β¬ A ∨ Β¬ B, from or.inr this lemma step2 (h₁ : Β¬ (A ∧ B)) (hβ‚‚ : Β¬ (Β¬ A ∨ Β¬ B)) : false := have Β¬ A, from assume : A, have Β¬ A ∨ Β¬ B, from step1 h₁ β€ΉAβ€Ί, show false, from hβ‚‚ this, show false, from sorry theorem step3 (h : Β¬ (A ∧ B)) : Β¬ A ∨ Β¬ B := by_contradiction (assume h' : Β¬ (Β¬ A ∨ Β¬ B), show false, from step2 h h') -- 5.3.7. This exercise is optional (not required). -- open classical -- variables {A B C : Prop} example (h : Β¬ B β†’ Β¬ A) : A β†’ B := sorry example (h : A β†’ B) : Β¬ A ∨ B := sorry
29eb5ab2adea42a7206c74217aebfd4b09683f52
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/monoidal/discrete.lean
f056580d65f24d7ffbc2487f3dd5d21c651a15ce
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,809
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.natural_transformation import category_theory.discrete_category import algebra.group.hom /-! # Monoids as discrete monoidal categories The discrete category on a monoid is a monoidal category. Multiplicative morphisms induced monoidal functors. -/ universes u open category_theory open category_theory.discrete variables (M : Type u) [monoid M] namespace category_theory instance monoid_discrete : monoid (discrete M) := by { dsimp [discrete], apply_instance } instance : monoidal_category (discrete M) := { tensor_unit := 1, tensor_obj := Ξ» X Y, X * Y, tensor_hom := Ξ» W X Y Z f g, eq_to_hom (by rw [eq_of_hom f, eq_of_hom g]), left_unitor := Ξ» X, eq_to_iso (one_mul X), right_unitor := Ξ» X, eq_to_iso (mul_one X), associator := Ξ» X Y Z, eq_to_iso (mul_assoc _ _ _), } variables {M} {N : Type u} [monoid N] /-- A multiplicative morphism between monoids gives a monoidal functor between the corresponding discrete monoidal categories. -/ @[simps] def discrete.monoidal_functor (F : M β†’* N) : monoidal_functor (discrete M) (discrete N) := { obj := F, map := Ξ» X Y f, eq_to_hom (F.congr_arg (eq_of_hom f)), Ξ΅ := eq_to_hom F.map_one.symm, ΞΌ := Ξ» X Y, eq_to_hom (F.map_mul X Y).symm, } variables {K : Type u} [monoid K] /-- The monoidal natural isomorphism corresponding to composing two multiplicative morphisms. -/ def discrete.monoidal_functor_comp (F : M β†’* N) (G : N β†’* K) : discrete.monoidal_functor F βŠ—β‹™ discrete.monoidal_functor G β‰… discrete.monoidal_functor (G.comp F) := { hom := { app := Ξ» X, πŸ™ _, }, inv := { app := Ξ» X, πŸ™ _, }, } end category_theory
fad9669f107f8efbca0093c19c41fe73037c7b4b
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/real/order.lean
c37c025e7fac74e173f8bd2e7ad6f6276e67c6f4
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,479
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). To do: o Rename things and possibly make theorems private -/ import data.real.basic data.rat data.nat open rat nat eq pnat algebra local postfix `⁻¹` := pnat.inv namespace rat_seq definition pos (s : seq) := βˆƒ n : β„•+, n⁻¹ < (s n) definition nonneg (s : seq) := βˆ€ n : β„•+, -(n⁻¹) ≀ s n theorem sub_sub_comm (a b c : β„š) : a - b - c = a - c - b := by rewrite [+sub_eq_add_neg, add.assoc, {-b+_}add.comm, -add.assoc] theorem bdd_away_of_pos {s : seq} (Hs : regular s) (H : pos s) : βˆƒ N : β„•+, βˆ€ n : β„•+, n β‰₯ N β†’ (s n) β‰₯ N⁻¹ := begin cases H with [n, Hn], cases sep_by_inv Hn with [N, HN], existsi N, intro m Hm, have Habs : abs (s m - s n) β‰₯ s n - s m, by rewrite abs_sub; apply le_abs_self, have Habs' : s m + abs (s m - s n) β‰₯ s n, from (iff.mpr (le_add_iff_sub_left_le _ _ _)) Habs, have HN' : N⁻¹ + N⁻¹ ≀ s n - n⁻¹, begin rewrite sub_eq_add_neg, apply iff.mpr (algebra.le_add_iff_sub_right_le _ _ _), rewrite [sub_neg_eq_add, add.comm, -add.assoc], apply le_of_lt HN end, rewrite add.comm at Habs', have Hin : s m β‰₯ N⁻¹, from calc s m β‰₯ s n - abs (s m - s n) : (iff.mp (le_add_iff_sub_left_le _ _ _)) Habs' ... β‰₯ s n - (m⁻¹ + n⁻¹) : algebra.sub_le_sub_left !Hs ... = s n - m⁻¹ - n⁻¹ : by rewrite sub_add_eq_sub_sub ... = s n - n⁻¹ - m⁻¹ : by rewrite sub_sub_comm ... β‰₯ s n - n⁻¹ - N⁻¹ : algebra.sub_le_sub_left (inv_ge_of_le Hm) ... β‰₯ N⁻¹ + N⁻¹ - N⁻¹ : algebra.sub_le_sub_right HN' ... = N⁻¹ : by rewrite algebra.add_sub_cancel, apply Hin end theorem pos_of_bdd_away {s : seq} (H : βˆƒ N : β„•+, βˆ€ n : β„•+, n β‰₯ N β†’ (s n) β‰₯ N⁻¹) : pos s := begin cases H with [N, HN], existsi (N + pone), apply lt_of_lt_of_le, apply inv_add_lt_left, apply HN, apply pnat.le_of_lt, apply lt_add_left end theorem bdd_within_of_nonneg {s : seq} (Hs : regular s) (H : nonneg s) : βˆ€ n : β„•+, βˆƒ N : β„•+, βˆ€ m : β„•+, m β‰₯ N β†’ s m β‰₯ -n⁻¹ := begin intros, existsi n, intro m Hm, apply le.trans, apply neg_le_neg, apply inv_ge_of_le, apply Hm, apply H end theorem nonneg_of_bdd_within {s : seq} (Hs : regular s) (H : βˆ€n : β„•+, βˆƒ N : β„•+, βˆ€ m : β„•+, m β‰₯ N β†’ s m β‰₯ -n⁻¹) : nonneg s := begin rewrite ↑nonneg, intro k, apply ge_of_forall_ge_sub, intro Ξ΅ HΞ΅, cases H (pceil ((2) / Ξ΅)) with [N, HN], apply le.trans, rotate 1, apply sub_le_of_abs_sub_le_left, apply Hs, apply (max (pceil ((2)/Ξ΅)) N), rewrite [+sub_eq_add_neg, neg_add, {_ + (-k⁻¹ + _)}add.comm, *add.assoc], apply rat.add_le_add_left, apply le.trans, rotate 1, apply add_le_add, rotate 1, apply HN (max (pceil ((2)/Ξ΅)) N) !pnat.max_right, rotate_right 1, apply neg_le_neg, apply inv_ge_of_le, apply pnat.max_left, rewrite -neg_add, apply neg_le_neg, apply le.trans, apply add_le_add, repeat (apply inv_pceil_div; apply add_pos; repeat apply zero_lt_one; exact HΞ΅), rewrite [algebra.add_halves], apply rat.le_refl end theorem pos_of_pos_equiv {s t : seq} (Hs : regular s) (Heq : s ≑ t) (Hp : pos s) : pos t := begin cases (bdd_away_of_pos Hs Hp) with [N, HN], existsi 2 * 2 * N, apply lt_of_lt_of_le, rotate 1, apply sub_le_of_abs_sub_le_right, apply Heq, have Hs4 : N⁻¹ ≀ s (2 * 2 * N), from HN _ (!pnat.mul_le_mul_left), apply lt_of_lt_of_le, rotate 1, rewrite sub_eq_add_neg, apply iff.mpr !add_le_add_right_iff, apply Hs4, rewrite [*pnat.mul_assoc, pnat.add_halves, -(add_halves N), -sub_eq_add_neg, algebra.add_sub_cancel], apply inv_two_mul_lt_inv end theorem nonneg_of_nonneg_equiv {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≑ t) (Hp : nonneg s) : nonneg t := begin apply nonneg_of_bdd_within, apply Ht, intros, cases bdd_within_of_nonneg Hs Hp (2 * 2 * n) with [Ns, HNs], existsi max Ns (2 * 2 * n), intro m Hm, apply le.trans, rotate 1, apply sub_le_of_abs_sub_le_right, apply Heq, apply le.trans, rotate 1, apply algebra.sub_le_sub_right, apply HNs, apply pnat.le_trans, rotate 1, apply Hm, rotate_right 1, apply pnat.max_left, have Hms : m⁻¹ ≀ (2 * 2 * n)⁻¹, begin apply inv_ge_of_le, apply pnat.le_trans, rotate 1, apply Hm; apply pnat.max_right end, have Hms' : m⁻¹ + m⁻¹ ≀ (2 * 2 * n)⁻¹ + (2 * 2 * n)⁻¹, from add_le_add Hms Hms, apply le.trans, rotate 1, apply algebra.sub_le_sub_left, apply Hms', rewrite [*pnat.mul_assoc, pnat.add_halves, -neg_sub, -add_halves n, sub_neg_eq_add], apply neg_le_neg, apply algebra.add_le_add_left, apply inv_two_mul_le_inv end definition s_le (a b : seq) := nonneg (sadd b (sneg a)) definition s_lt (a b : seq) := pos (sadd b (sneg a)) theorem zero_nonneg : nonneg zero := begin intros, apply neg_nonpos_of_nonneg, apply rat.le_of_lt, apply pnat.inv_pos end theorem s_zero_lt_one : s_lt zero one := begin rewrite [↑s_lt, ↑zero, ↑sadd, ↑sneg, ↑one, neg_zero, add_zero, ↑pos], existsi 2, apply inv_lt_one_of_gt, apply one_lt_two end protected theorem le_refl {s : seq} (Hs : regular s) : s_le s s := begin apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply neg_s_cancel s Hs, apply zero_nonneg, apply zero_is_reg, apply reg_add_reg Hs (reg_neg_reg Hs) end theorem s_nonneg_of_pos {s : seq} (Hs : regular s) (H : pos s) : nonneg s := begin apply nonneg_of_bdd_within, apply Hs, intros, cases bdd_away_of_pos Hs H with [N, HN], existsi N, intro m Hm, apply le.trans, rotate 1, apply HN, apply Hm, apply le.trans, rotate 1, apply rat.le_of_lt, apply pnat.inv_pos, rewrite -neg_zero, apply neg_le_neg, apply rat.le_of_lt, apply pnat.inv_pos end theorem s_le_of_s_lt {s t : seq} (Hs : regular s) (Ht : regular t) (H : s_lt s t) : s_le s t := begin rewrite [↑s_le, ↑s_lt at *], apply s_nonneg_of_pos, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end theorem s_neg_add_eq_s_add_neg (s t : seq) : sneg (sadd s t) ≑ sadd (sneg s) (sneg t) := begin rewrite [↑equiv, ↑sadd, ↑sneg], intros, rewrite [neg_add, algebra.sub_self, abs_zero], apply add_invs_nonneg end theorem equiv_cancel_middle {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) : sadd (sadd u t) (sneg (sadd u s)) ≑ sadd t (sneg s) := begin let Hz := zero_is_reg, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply s_add_comm, apply s_neg_add_eq_s_add_neg, apply equiv.trans, rotate 3, apply s_add_assoc, rotate 2, apply add_well_defined, rotate 4, apply equiv.refl, apply equiv.trans, rotate 4, apply equiv.refl, rotate_right 1, apply equiv.trans, rotate 3, apply equiv.symm, apply s_add_assoc, rotate 2, apply equiv.trans, rotate 4, apply s_zero_add, rotate_right 1, apply add_well_defined, rotate 4, apply neg_s_cancel, rotate 1, apply equiv.refl, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end protected theorem add_le_add_of_le_right {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_le s t) : βˆ€ u : seq, regular u β†’ s_le (sadd u s) (sadd u t) := begin intro u Hu, rewrite [↑s_le at *], apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply equiv_cancel_middle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end theorem s_add_lt_add_left {s t : seq} (Hs : regular s) (Ht : regular t) (Hst : s_lt s t) {u : seq} (Hu : regular u) : s_lt (sadd u s) (sadd u t) := begin rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 1, apply equiv.symm, apply equiv_cancel_middle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end protected theorem add_nonneg_of_nonneg {s t : seq} (Hs : nonneg s) (Ht : nonneg t) : nonneg (sadd s t) := begin intros, rewrite [-pnat.add_halves, neg_add], apply add_le_add, apply Hs, apply Ht end protected theorem le_trans {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Lst : s_le s t) (Ltu : s_le t u) : s_le s u := begin rewrite ↑s_le at *, let Rz := zero_is_reg, have Hsum : nonneg (sadd (sadd u (sneg t)) (sadd t (sneg s))), from rat_seq.add_nonneg_of_nonneg Ltu Lst, have H' : nonneg (sadd (sadd u (sadd (sneg t) t)) (sneg s)), begin apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply s_add_assoc, repeat (apply reg_add_reg | apply reg_neg_reg | assumption), apply equiv.refl, apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply s_add_assoc, rotate 2, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end, have H'' : sadd (sadd u (sadd (sneg t) t)) (sneg s) ≑ sadd u (sneg s), begin apply add_well_defined, rotate 4, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_cancel, rotate 1, apply s_add_zero, rotate 1, apply equiv.refl, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end, apply nonneg_of_nonneg_equiv, rotate 2, apply H'', apply H', repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end theorem equiv_of_le_of_ge {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_le s t) (Lts : s_le t s) : s ≑ t := begin apply equiv_of_diff_equiv_zero, rotate 2, rewrite [↑s_le at *, ↑nonneg at *, ↑equiv, ↑sadd at *, ↑sneg at *], intros, rewrite [↑zero, algebra.sub_zero], apply abs_le_of_le_of_neg_le, apply le_of_neg_le_neg, rewrite [2 neg_add, neg_neg], apply rat.le_trans, apply algebra.neg_add_neg_le_neg_of_pos, apply pnat.inv_pos, rewrite add.comm, apply Lst, apply le_of_neg_le_neg, rewrite [neg_add, neg_neg], apply rat.le_trans, apply algebra.neg_add_neg_le_neg_of_pos, apply pnat.inv_pos, apply Lts, repeat assumption end definition sep (s t : seq) := s_lt s t ∨ s_lt t s local infix `β‰’` : 50 := sep theorem le_and_sep_of_lt {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_lt s t) : s_le s t ∧ sep s t := begin apply and.intro, intros, cases Lst with [N, HN], let Rns := reg_neg_reg Hs, let Rtns := reg_add_reg Ht Rns, let Habs := sub_le_of_abs_sub_le_right (Rtns N n), rewrite [sub_add_eq_sub_sub at Habs], exact (calc sadd t (sneg s) n β‰₯ sadd t (sneg s) N - N⁻¹ - n⁻¹ : Habs ... β‰₯ 0 - n⁻¹: begin apply algebra.sub_le_sub_right, apply rat.le_of_lt, apply (iff.mpr (sub_pos_iff_lt _ _)), apply HN end ... = -n⁻¹ : by rewrite algebra.zero_sub), exact or.inl Lst end theorem lt_of_le_and_sep {s t : seq} (Hs : regular s) (Ht : regular t) (H : s_le s t ∧ sep s t) : s_lt s t := begin let Le := and.left H, cases and.right H with [P, Hlt], exact P, rewrite [↑s_le at Le, ↑nonneg at Le, ↑s_lt at Hlt, ↑pos at Hlt], apply exists.elim Hlt, intro N HN, let LeN := Le N, let HN' := (iff.mpr !neg_lt_neg_iff_lt) HN, rewrite [↑sadd at HN', ↑sneg at HN', neg_add at HN', neg_neg at HN', add.comm at HN'], let HN'' := not_le_of_gt HN', apply absurd LeN HN'' end theorem lt_iff_le_and_sep {s t : seq} (Hs : regular s) (Ht : regular t) : s_lt s t ↔ s_le s t ∧ sep s t := iff.intro (le_and_sep_of_lt Hs Ht) (lt_of_le_and_sep Hs Ht) theorem s_neg_zero : sneg zero ≑ zero := begin rewrite ↑[sneg, zero, equiv], intros, rewrite [algebra.sub_zero, abs_neg, abs_zero], apply add_invs_nonneg end theorem s_sub_zero {s : seq} (Hs : regular s) : sadd s (sneg zero) ≑ s := begin apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_zero, apply s_add_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end theorem s_pos_of_gt_zero {s : seq} (Hs : regular s) (Hgz : s_lt zero s) : pos s := begin rewrite [↑s_lt at *], apply pos_of_pos_equiv, rotate 1, apply s_sub_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg), apply zero_is_reg end theorem s_gt_zero_of_pos {s : seq} (Hs : regular s) (Hp : pos s) : s_lt zero s := begin rewrite ↑s_lt, apply pos_of_pos_equiv, rotate 1, apply equiv.symm, apply s_sub_zero, repeat assumption end theorem s_nonneg_of_ge_zero {s : seq} (Hs : regular s) (Hgz : s_le zero s) : nonneg s := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply s_sub_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end theorem s_ge_zero_of_nonneg {s : seq} (Hs : regular s) (Hn : nonneg s) : s_le zero s := begin rewrite ↑s_le, apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply s_sub_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end theorem s_mul_pos_of_pos {s t : seq} (Hs : regular s) (Ht : regular t) (Hps : pos s) (Hpt : pos t) : pos (smul s t) := begin rewrite [↑pos at *], cases bdd_away_of_pos Hs Hps with [Ns, HNs], cases bdd_away_of_pos Ht Hpt with [Nt, HNt], existsi 2 * max Ns Nt * max Ns Nt, rewrite ↑smul, apply lt_of_lt_of_le, rotate 1, apply algebra.mul_le_mul, apply HNs, apply pnat.le_trans, apply pnat.max_left Ns Nt, rewrite -pnat.mul_assoc, apply pnat.mul_le_mul_left, apply HNt, apply pnat.le_trans, apply pnat.max_right Ns Nt, rewrite -pnat.mul_assoc, apply pnat.mul_le_mul_left, apply rat.le_of_lt, apply pnat.inv_pos, apply rat.le_trans, rotate 1, apply HNs, apply pnat.le_trans, apply pnat.max_left Ns Nt, rewrite -pnat.mul_assoc, apply pnat.mul_le_mul_left, rewrite pnat.inv_mul_eq_mul_inv, apply algebra.mul_lt_mul, rewrite [pnat.inv_mul_eq_mul_inv, -one_mul Ns⁻¹], apply algebra.mul_lt_mul, apply inv_lt_one_of_gt, apply dec_trivial, apply inv_ge_of_le, apply pnat.max_left, apply pnat.inv_pos, apply rat.le_of_lt zero_lt_one, apply inv_ge_of_le, apply pnat.max_right, apply pnat.inv_pos, repeat (apply le_of_lt; apply pnat.inv_pos) end theorem s_mul_gt_zero_of_gt_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Hzs : s_lt zero s) (Hzt : s_lt zero t) : s_lt zero (smul s t) := s_gt_zero_of_pos (reg_mul_reg Hs Ht) (s_mul_pos_of_pos Hs Ht (s_pos_of_gt_zero Hs Hzs) (s_pos_of_gt_zero Ht Hzt)) theorem le_of_lt_or_equiv {s t : seq} (Hs : regular s) (Ht : regular t) (Hor : (s_lt s t) ∨ (s ≑ t)) : s_le s t := or.elim Hor (begin intro Hlt, apply s_le_of_s_lt Hs Ht Hlt end) (begin intro Heq, rewrite ↑s_le, apply nonneg_of_nonneg_equiv, rotate 3, apply zero_nonneg, apply zero_is_reg, apply reg_add_reg Ht (reg_neg_reg Hs), apply equiv.symm, apply diff_equiv_zero_of_equiv, rotate 2, apply equiv.symm, apply Heq, repeat assumption end) theorem s_zero_mul {s : seq} : smul s zero ≑ zero := begin rewrite [↑equiv, ↑smul, ↑zero], intros, rewrite [algebra.mul_zero, algebra.sub_zero, abs_zero], apply add_invs_nonneg end theorem s_mul_nonneg_of_pos_of_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Hps : pos s) (Hpt : zero ≑ t) : nonneg (smul s t) := begin apply nonneg_of_nonneg_equiv, rotate 2, apply mul_well_defined, rotate 4, apply equiv.refl, apply Hpt, apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply s_zero_mul, apply zero_nonneg, repeat (assumption | apply reg_mul_reg | apply zero_is_reg) end theorem s_mul_nonneg_of_nonneg {s t : seq} (Hs : regular s) (Ht : regular t) (Hps : nonneg s) (Hpt : nonneg t) : nonneg (smul s t) := begin intro n, rewrite ↑smul, apply rat.le_by_cases 0 (s (((Kβ‚‚ s t) * 2) * n)), intro Hsp, apply rat.le_by_cases 0 (t (((Kβ‚‚ s t) * 2) * n)), intro Htp, apply rat.le_trans, rotate 1, apply rat.mul_nonneg Hsp Htp, rotate_right 1, apply le_of_lt, apply neg_neg_of_pos, apply pnat.inv_pos, intro Htn, apply rat.le_trans, rotate 1, apply algebra.mul_le_mul_of_nonpos_right, apply rat.le_trans, apply le_abs_self, apply canon_2_bound_left s t Hs, apply Htn, rotate_right 1, apply rat.le_trans, rotate 1, apply mul_le_mul_of_nonneg_left, apply Hpt, apply le_of_lt, apply rat_of_pnat_is_pos, rotate 1, rewrite -neg_mul_eq_mul_neg, apply neg_le_neg, rewrite [*pnat.mul_assoc, pnat.inv_mul_eq_mul_inv, -mul.assoc, pnat.inv_cancel_left, one_mul], apply inv_ge_of_le, apply pnat.mul_le_mul_left, intro Hsn, apply rat.le_by_cases 0 (t (((Kβ‚‚ s t) * 2) * n)), intro Htp, apply rat.le_trans, rotate 1, apply mul_le_mul_of_nonpos_left, apply rat.le_trans, apply le_abs_self, apply canon_2_bound_right s t Ht, apply Hsn, rotate_right 1, apply rat.le_trans, rotate 1, apply mul_le_mul_of_nonneg_right, apply Hps, apply le_of_lt, apply rat_of_pnat_is_pos, rotate 1, rewrite -neg_mul_eq_neg_mul, apply neg_le_neg, rewrite [+pnat.mul_assoc, pnat.inv_mul_eq_mul_inv, mul.comm, -mul.assoc, pnat.inv_cancel_left, one_mul], apply inv_ge_of_le, apply pnat.mul_le_mul_left, intro Htn, apply le.trans, rotate 1, apply mul_nonneg_of_nonpos_of_nonpos, apply Hsn, apply Htn, apply le_of_lt, apply neg_neg_of_pos, apply pnat.inv_pos end theorem s_mul_ge_zero_of_ge_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Hzs : s_le zero s) (Hzt : s_le zero t) : s_le zero (smul s t) := begin let Hzs' := s_nonneg_of_ge_zero Hs Hzs, let Htz' := s_nonneg_of_ge_zero Ht Hzt, apply s_ge_zero_of_nonneg, rotate 1, apply s_mul_nonneg_of_nonneg, repeat assumption, apply reg_mul_reg Hs Ht end protected theorem not_lt_self (s : seq) : Β¬ s_lt s s := begin intro Hlt, rewrite [↑s_lt at Hlt, ↑pos at Hlt], apply exists.elim Hlt, intro n Hn, esimp at Hn, rewrite [↑sadd at Hn,↑sneg at Hn, -sub_eq_add_neg at Hn, algebra.sub_self at Hn], apply absurd Hn (algebra.not_lt_of_ge (rat.le_of_lt !pnat.inv_pos)) end theorem not_sep_self (s : seq) : Β¬ s β‰’ s := begin intro Hsep, rewrite ↑sep at Hsep, let Hsep' := (iff.mp !or_self) Hsep, apply absurd Hsep' (!rat_seq.not_lt_self) end theorem le_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Hsu : s ≑ u) (Htv : t ≑ v) : s_le s t ↔ s_le u v := iff.intro (begin intro Hle, rewrite [↑s_le at *], apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply Htv, apply neg_well_defined, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) (begin intro Hle, rewrite [↑s_le at *], apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply equiv.symm, apply Htv, apply neg_well_defined, apply equiv.symm, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) theorem lt_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Hsu : s ≑ u) (Htv : t ≑ v) : s_lt s t ↔ s_lt u v := iff.intro (begin intro Hle, rewrite [↑s_lt at *], apply pos_of_pos_equiv, rotate 1, apply add_well_defined, rotate 4, apply Htv, apply neg_well_defined, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) (begin intro Hle, rewrite [↑s_lt at *], apply pos_of_pos_equiv, rotate 1, apply add_well_defined, rotate 4, apply equiv.symm, apply Htv, apply neg_well_defined, apply equiv.symm, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) theorem sep_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Hsu : s ≑ u) (Htv : t ≑ v) : s β‰’ t ↔ u β‰’ v := begin rewrite ↑sep, apply iff.intro, intro Hor, apply or.elim Hor, intro Hlt, apply or.inl, apply iff.mp (lt_well_defined Hs Ht Hu Hv Hsu Htv), assumption, intro Hlt, apply or.inr, apply iff.mp (lt_well_defined Ht Hs Hv Hu Htv Hsu), assumption, intro Hor, apply or.elim Hor, intro Hlt, apply or.inl, apply iff.mpr (lt_well_defined Hs Ht Hu Hv Hsu Htv), assumption, intro Hlt, apply or.inr, apply iff.mpr (lt_well_defined Ht Hs Hv Hu Htv Hsu), assumption end theorem s_lt_of_lt_of_le {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hst : s_lt s t) (Htu : s_le t u) : s_lt s u := begin let Rtns := reg_add_reg Ht (reg_neg_reg Hs), let Runt := reg_add_reg Hu (reg_neg_reg Ht), have Hcan : βˆ€ m, sadd u (sneg s) m = (sadd t (sneg s)) m + (sadd u (sneg t)) m, begin intro m, rewrite [↑sadd, ↑sneg, -*algebra.sub_eq_add_neg, -sub_eq_sub_add_sub] end, rewrite [↑s_lt at *, ↑s_le at *], cases bdd_away_of_pos Rtns Hst with [Nt, HNt], cases bdd_within_of_nonneg Runt Htu (2 * Nt) with [Nu, HNu], apply pos_of_bdd_away, existsi max (2 * Nt) Nu, intro n Hn, rewrite Hcan, apply rat.le_trans, rotate 1, apply algebra.add_le_add, apply HNt, apply pnat.le_trans, apply pnat.mul_le_mul_left 2, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_left, apply HNu, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_right, rewrite [-add_halves Nt, -sub_eq_add_neg, algebra.add_sub_cancel], apply inv_ge_of_le, apply pnat.max_left end theorem s_lt_of_le_of_lt {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hst : s_le s t) (Htu : s_lt t u) : s_lt s u := begin let Rtns := reg_add_reg Ht (reg_neg_reg Hs), let Runt := reg_add_reg Hu (reg_neg_reg Ht), have Hcan : βˆ€ m, sadd u (sneg s) m = (sadd t (sneg s)) m + (sadd u (sneg t)) m, begin intro m, rewrite [↑sadd, ↑sneg, -*sub_eq_add_neg, -sub_eq_sub_add_sub] end, rewrite [↑s_lt at *, ↑s_le at *], cases bdd_away_of_pos Runt Htu with [Nu, HNu], cases bdd_within_of_nonneg Rtns Hst (2 * Nu) with [Nt, HNt], apply pos_of_bdd_away, existsi max (2 * Nu) Nt, intro n Hn, rewrite Hcan, apply rat.le_trans, rotate 1, apply algebra.add_le_add, apply HNt, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_right, apply HNu, apply pnat.le_trans, apply pnat.mul_le_mul_left 2, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_left, rewrite [-add_halves Nu, neg_add_cancel_left], apply inv_ge_of_le, apply pnat.max_left end theorem le_of_le_reprs {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : βˆ€ n : β„•+, s_le s (const (t n))) : s_le s t := by intro m; apply Hle (2 * m) m theorem le_of_reprs_le {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : βˆ€ n : β„•+, s_le (const (t n)) s) : s_le t s := by intro m; apply Hle (2 * m) m ----------------------------- -- of_rat theorems theorem const_le_const_of_le {a b : β„š} (H : a ≀ b) : s_le (const a) (const b) := begin rewrite [↑s_le, ↑nonneg], intro n, rewrite [↑sadd, ↑sneg, ↑const], apply algebra.le.trans, apply neg_nonpos_of_nonneg, apply rat.le_of_lt, apply pnat.inv_pos, apply iff.mpr !sub_nonneg_iff_le, apply H end theorem le_of_const_le_const {a b : β„š} (H : s_le (const a) (const b)) : a ≀ b := begin rewrite [↑s_le at H, ↑nonneg at H, ↑sadd at H, ↑sneg at H, ↑const at H], apply iff.mp !sub_nonneg_iff_le, apply nonneg_of_ge_neg_invs _ H end theorem nat_inv_lt_rat {a : β„š} (H : a > 0) : βˆƒ n : β„•+, n⁻¹ < a := begin existsi (pceil (1 / (a / (2)))), apply lt_of_le_of_lt, rotate 1, apply div_two_lt_of_pos H, rewrite -(one_div_one_div (a / (1 + 1))), apply pceil_helper, apply pnat.le_refl, apply one_div_pos_of_pos, apply div_pos_of_pos_of_pos H dec_trivial end theorem const_lt_const_of_lt {a b : β„š} (H : a < b) : s_lt (const a) (const b) := begin rewrite [↑s_lt, ↑pos, ↑sadd, ↑sneg, ↑const], apply nat_inv_lt_rat, apply (iff.mpr !sub_pos_iff_lt H) end theorem lt_of_const_lt_const {a b : β„š} (H : s_lt (const a) (const b)) : a < b := begin rewrite [↑s_lt at H, ↑pos at H, ↑const at H, ↑sadd at H, ↑sneg at H], cases H with [n, Hn], apply (iff.mp !sub_pos_iff_lt), apply algebra.lt.trans, rotate 1, exact Hn, apply pnat.inv_pos end theorem s_le_of_le_pointwise {s t : seq} (Hs : regular s) (Ht : regular t) (H : βˆ€ n : β„•+, s n ≀ t n) : s_le s t := begin rewrite [↑s_le, ↑nonneg, ↑sadd, ↑sneg], intros, apply algebra.le.trans, apply iff.mpr !neg_nonpos_iff_nonneg, apply le_of_lt, apply pnat.inv_pos, apply iff.mpr !sub_nonneg_iff_le, apply H end -------- lift to reg_seqs definition r_lt (s t : reg_seq) := s_lt (reg_seq.sq s) (reg_seq.sq t) definition r_le (s t : reg_seq) := s_le (reg_seq.sq s) (reg_seq.sq t) definition r_sep (s t : reg_seq) := sep (reg_seq.sq s) (reg_seq.sq t) theorem r_le_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v) : r_le s t = r_le u v := propext (le_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) Hsu Htv) theorem r_lt_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v) : r_lt s t = r_lt u v := propext (lt_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) Hsu Htv) theorem r_sep_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v) : r_sep s t = r_sep u v := propext (sep_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) Hsu Htv) theorem r_le.refl (s : reg_seq) : r_le s s := rat_seq.le_refl (reg_seq.is_reg s) theorem r_le.trans {s t u : reg_seq} (Hst : r_le s t) (Htu : r_le t u) : r_le s u := rat_seq.le_trans (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu theorem r_equiv_of_le_of_ge {s t : reg_seq} (Hs : r_le s t) (Hu : r_le t s) : requiv s t := equiv_of_le_of_ge (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Hu theorem r_lt_iff_le_and_sep (s t : reg_seq) : r_lt s t ↔ r_le s t ∧ r_sep s t := lt_iff_le_and_sep (reg_seq.is_reg s) (reg_seq.is_reg t) theorem r_add_le_add_of_le_right {s t : reg_seq} (H : r_le s t) (u : reg_seq) : r_le (u + s) (u + t) := rat_seq.add_le_add_of_le_right (reg_seq.is_reg s) (reg_seq.is_reg t) H (reg_seq.sq u) (reg_seq.is_reg u) theorem r_add_le_add_of_le_right_var (s t u : reg_seq) (H : r_le s t) : r_le (u + s) (u + t) := r_add_le_add_of_le_right H u theorem r_mul_pos_of_pos {s t : reg_seq} (Hs : r_lt r_zero s) (Ht : r_lt r_zero t) : r_lt r_zero (s * t) := s_mul_gt_zero_of_gt_zero (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Ht theorem r_mul_nonneg_of_nonneg {s t : reg_seq} (Hs : r_le r_zero s) (Ht : r_le r_zero t) : r_le r_zero (s * t) := s_mul_ge_zero_of_ge_zero (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Ht theorem r_not_lt_self (s : reg_seq) : Β¬ r_lt s s := rat_seq.not_lt_self (reg_seq.sq s) theorem r_not_sep_self (s : reg_seq) : Β¬ r_sep s s := not_sep_self (reg_seq.sq s) theorem r_le_of_lt {s t : reg_seq} (H : r_lt s t) : r_le s t := s_le_of_s_lt (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_lt_of_le_of_lt {s t u : reg_seq} (Hst : r_le s t) (Htu : r_lt t u) : r_lt s u := s_lt_of_le_of_lt (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu theorem r_lt_of_lt_of_le {s t u : reg_seq} (Hst : r_lt s t) (Htu : r_le t u) : r_lt s u := s_lt_of_lt_of_le (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu theorem r_add_lt_add_left (s t : reg_seq) (H : r_lt s t) (u : reg_seq) : r_lt (u + s) (u + t) := s_add_lt_add_left (reg_seq.is_reg s) (reg_seq.is_reg t) H (reg_seq.is_reg u) theorem r_add_lt_add_left_var (s t u : reg_seq) (H : r_lt s t) : r_lt (u + s) (u + t) := r_add_lt_add_left s t H u theorem r_zero_lt_one : r_lt r_zero r_one := s_zero_lt_one theorem r_le_of_lt_or_eq (s t : reg_seq) (H : r_lt s t ∨ requiv s t) : r_le s t := le_of_lt_or_equiv (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_const_le_const_of_le {a b : β„š} (H : a ≀ b) : r_le (r_const a) (r_const b) := const_le_const_of_le H theorem r_le_of_const_le_const {a b : β„š} (H : r_le (r_const a) (r_const b)) : a ≀ b := le_of_const_le_const H theorem r_const_lt_const_of_lt {a b : β„š} (H : a < b) : r_lt (r_const a) (r_const b) := const_lt_const_of_lt H theorem r_lt_of_const_lt_const {a b : β„š} (H : r_lt (r_const a) (r_const b)) : a < b := lt_of_const_lt_const H theorem r_le_of_le_reprs (s t : reg_seq) (Hle : βˆ€ n : β„•+, r_le s (r_const (reg_seq.sq t n))) : r_le s t := le_of_le_reprs (reg_seq.is_reg s) (reg_seq.is_reg t) Hle theorem r_le_of_reprs_le (s t : reg_seq) (Hle : βˆ€ n : β„•+, r_le (r_const (reg_seq.sq t n)) s) : r_le t s := le_of_reprs_le (reg_seq.is_reg s) (reg_seq.is_reg t) Hle end rat_seq open real open [classes] rat_seq namespace real protected definition lt (x y : ℝ) := quot.lift_onβ‚‚ x y (Ξ» a b, rat_seq.r_lt a b) rat_seq.r_lt_well_defined protected definition le (x y : ℝ) := quot.lift_onβ‚‚ x y (Ξ» a b, rat_seq.r_le a b) rat_seq.r_le_well_defined definition real_has_lt [reducible] [instance] [priority real.prio] : has_lt ℝ := has_lt.mk real.lt definition real_has_le [reducible] [instance] [priority real.prio] : has_le ℝ := has_le.mk real.le definition sep (x y : ℝ) := quot.lift_onβ‚‚ x y (Ξ» a b, rat_seq.r_sep a b) rat_seq.r_sep_well_defined infix `β‰’` : 50 := sep protected theorem le_refl (x : ℝ) : x ≀ x := quot.induction_on x (Ξ» t, rat_seq.r_le.refl t) protected theorem le_trans {x y z : ℝ} : x ≀ y β†’ y ≀ z β†’ x ≀ z := quot.induction_on₃ x y z (Ξ» s t u, rat_seq.r_le.trans) protected theorem eq_of_le_of_ge {x y : ℝ} : x ≀ y β†’ y ≀ x β†’ x = y := quot.induction_onβ‚‚ x y (Ξ» s t Hst Hts, quot.sound (rat_seq.r_equiv_of_le_of_ge Hst Hts)) theorem lt_iff_le_and_sep (x y : ℝ) : x < y ↔ x ≀ y ∧ x β‰’ y := quot.induction_onβ‚‚ x y (Ξ» s t, rat_seq.r_lt_iff_le_and_sep s t) protected theorem add_le_add_left' (x y z : ℝ) : x ≀ y β†’ z + x ≀ z + y := quot.induction_on₃ x y z (Ξ» s t u, rat_seq.r_add_le_add_of_le_right_var s t u) protected theorem add_le_add_left (x y : ℝ) : x ≀ y β†’ βˆ€ z : ℝ, z + x ≀ z + y := take H z, real.add_le_add_left' x y z H protected theorem mul_pos (x y : ℝ) : 0 < x β†’ 0 < y β†’ 0 < x * y := quot.induction_onβ‚‚ x y (Ξ» s t, rat_seq.r_mul_pos_of_pos) protected theorem mul_nonneg (x y : ℝ) : 0 ≀ x β†’ 0 ≀ y β†’ 0 ≀ x * y := quot.induction_onβ‚‚ x y (Ξ» s t, rat_seq.r_mul_nonneg_of_nonneg) theorem not_sep_self (x : ℝ) : Β¬ x β‰’ x := quot.induction_on x (Ξ» s, rat_seq.r_not_sep_self s) protected theorem lt_irrefl (x : ℝ) : Β¬ x < x := quot.induction_on x (Ξ» s, rat_seq.r_not_lt_self s) protected theorem le_of_lt {x y : ℝ} : x < y β†’ x ≀ y := quot.induction_onβ‚‚ x y (Ξ» s t H', rat_seq.r_le_of_lt H') protected theorem lt_of_le_of_lt {x y z : ℝ} : x ≀ y β†’ y < z β†’ x < z := quot.induction_on₃ x y z (Ξ» s t u H H', rat_seq.r_lt_of_le_of_lt H H') protected theorem lt_of_lt_of_le {x y z : ℝ} : x < y β†’ y ≀ z β†’ x < z := quot.induction_on₃ x y z (Ξ» s t u H H', rat_seq.r_lt_of_lt_of_le H H') protected theorem add_lt_add_left' (x y z : ℝ) : x < y β†’ z + x < z + y := quot.induction_on₃ x y z (Ξ» s t u, rat_seq.r_add_lt_add_left_var s t u) protected theorem add_lt_add_left (x y : ℝ) : x < y β†’ βˆ€ z : ℝ, z + x < z + y := take H z, real.add_lt_add_left' x y z H protected theorem zero_lt_one : (0 : ℝ) < (1 : ℝ) := rat_seq.r_zero_lt_one protected theorem le_of_lt_or_eq (x y : ℝ) : x < y ∨ x = y β†’ x ≀ y := (quot.induction_onβ‚‚ x y (Ξ» s t H, or.elim H (take H', begin apply rat_seq.r_le_of_lt_or_eq, apply or.inl H' end) (take H', begin apply rat_seq.r_le_of_lt_or_eq, apply (or.inr (quot.exact H')) end))) definition ordered_ring [reducible] [instance] : algebra.ordered_ring ℝ := ⦃ algebra.ordered_ring, real.comm_ring, le_refl := real.le_refl, le_trans := @real.le_trans, mul_pos := real.mul_pos, mul_nonneg := real.mul_nonneg, zero_ne_one := real.zero_ne_one, add_le_add_left := real.add_le_add_left, le_antisymm := @real.eq_of_le_of_ge, lt_irrefl := real.lt_irrefl, lt_of_le_of_lt := @real.lt_of_le_of_lt, lt_of_lt_of_le := @real.lt_of_lt_of_le, le_of_lt := @real.le_of_lt, add_lt_add_left := real.add_lt_add_left ⦄ open int theorem of_rat_sub (a b : β„š) : of_rat (a - b) = of_rat a - of_rat b := rfl theorem of_int_sub (a b : β„€) : of_int (a - b) = of_int a - of_int b := by rewrite [of_int_eq, rat.of_int_sub, of_rat_sub] theorem of_rat_le_of_rat_of_le {a b : β„š} : a ≀ b β†’ of_rat a ≀ of_rat b := rat_seq.r_const_le_const_of_le theorem le_of_of_rat_le_of_rat {a b : β„š} : of_rat a ≀ of_rat b β†’ a ≀ b := rat_seq.r_le_of_const_le_const theorem of_rat_le_of_rat_iff (a b : β„š) : of_rat a ≀ of_rat b ↔ a ≀ b := iff.intro le_of_of_rat_le_of_rat of_rat_le_of_rat_of_le theorem of_rat_lt_of_rat_of_lt {a b : β„š} : a < b β†’ of_rat a < of_rat b := rat_seq.r_const_lt_const_of_lt theorem lt_of_of_rat_lt_of_rat {a b : β„š} : of_rat a < of_rat b β†’ a < b := rat_seq.r_lt_of_const_lt_const theorem of_rat_lt_of_rat_iff (a b : β„š) : of_rat a < of_rat b ↔ a < b := iff.intro lt_of_of_rat_lt_of_rat of_rat_lt_of_rat_of_lt theorem of_int_le_of_int_iff (a b : β„€) : of_int a ≀ of_int b ↔ (a ≀ b) := begin rewrite [+of_int_eq, of_rat_le_of_rat_iff], apply rat.of_int_le_of_int_iff end theorem of_int_le_of_int_of_le {a b : β„€} : (a ≀ b) β†’ of_int a ≀ of_int b := iff.mpr !of_int_le_of_int_iff theorem le_of_of_int_le_of_int {a b : β„€} : of_int a ≀ of_int b β†’ (a ≀ b) := iff.mp !of_int_le_of_int_iff theorem of_int_lt_of_int_iff (a b : β„€) : of_int a < of_int b ↔ (a < b) := by rewrite [*of_int_eq, of_rat_lt_of_rat_iff]; apply rat.of_int_lt_of_int_iff theorem of_int_lt_of_int_of_lt {a b : β„€} : (a < b) β†’ of_int a < of_int b := iff.mpr !of_int_lt_of_int_iff theorem lt_of_of_int_lt_of_int {a b : β„€} : of_int a < of_int b β†’ (a < b) := iff.mp !of_int_lt_of_int_iff theorem of_nat_le_of_nat_iff (a b : β„•) : of_nat a ≀ of_nat b ↔ (a ≀ b) := by rewrite [*of_nat_eq, of_rat_le_of_rat_iff]; apply rat.of_nat_le_of_nat_iff theorem of_nat_le_of_nat_of_le {a b : β„•} : (a ≀ b) β†’ of_nat a ≀ of_nat b := iff.mpr !of_nat_le_of_nat_iff theorem le_of_of_nat_le_of_nat {a b : β„•} : of_nat a ≀ of_nat b β†’ (a ≀ b) := iff.mp !of_nat_le_of_nat_iff theorem of_nat_lt_of_nat_iff (a b : β„•) : of_nat a < of_nat b ↔ (a < b) := by rewrite [*of_nat_eq, of_rat_lt_of_rat_iff]; apply rat.of_nat_lt_of_nat_iff theorem of_nat_lt_of_nat_of_lt {a b : β„•} : (a < b) β†’ of_nat a < of_nat b := iff.mpr !of_nat_lt_of_nat_iff theorem lt_of_of_nat_lt_of_nat {a b : β„•} : of_nat a < of_nat b β†’ (a < b) := iff.mp !of_nat_lt_of_nat_iff theorem of_nat_nonneg (a : β„•) : of_nat a β‰₯ 0 := of_rat_le_of_rat_of_le !rat.of_nat_nonneg theorem of_rat_pow (a : β„š) (n : β„•) : of_rat (a^n) = (of_rat a)^n := begin induction n with n ih, apply eq.refl, rewrite [2 pow_succ, of_rat_mul, ih] end theorem of_int_pow (a : β„€) (n : β„•) : of_int (#int a^n) = (of_int a)^n := by rewrite [of_int_eq, rat.of_int_pow, of_rat_pow] theorem of_nat_pow (a : β„•) (n : β„•) : of_nat (#nat a^n) = (of_nat a)^n := by rewrite [of_nat_eq, rat.of_nat_pow, of_rat_pow] open rat_seq theorem le_of_le_reprs (x : ℝ) (t : seq) (Ht : regular t) : (βˆ€ n : β„•+, x ≀ t n) β†’ x ≀ quot.mk (reg_seq.mk t Ht) := quot.induction_on x (take s Hs, show r_le s (reg_seq.mk t Ht), from have H' : βˆ€ n : β„•+, r_le s (r_const (t n)), from Hs, by apply r_le_of_le_reprs; apply Hs) theorem le_of_reprs_le (x : ℝ) (t : seq) (Ht : regular t) : (βˆ€ n : β„•+, t n ≀ x) β†’ x β‰₯ ((quot.mk (reg_seq.mk t Ht)) : ℝ) := quot.induction_on x (take s Hs, show r_le (reg_seq.mk t Ht) s, from have H' : βˆ€ n : β„•+, r_le (r_const (t n)) s, from Hs, by apply r_le_of_reprs_le; apply Hs) end real
94e93eaea91312e568902b1f5cb92fde66ed936a
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/tests/lean/run/basic_monitor3.lean
b7f8e512d561c38c41b393d35bbd5ac0b2c585c8
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
1,574
lean
meta def get_file (fn : name) : vm format := do { d ← vm.get_decl fn, some n ← return (vm_decl.olean d) | failure, return (to_fmt n) } <|> return (to_fmt "<curr file>") meta def pos_info (fn : name) : vm format := do { d ← vm.get_decl fn, some (line, col) ← return (vm_decl.pos d) | failure, file ← get_file fn, return (file ++ ":" ++ line ++ ":" ++ col) } <|> return (to_fmt "<position not available>") meta def obj_fmt (o : vm_obj) : vm format := match o^.kind with | vm_obj_kind.tactic_state := return (to_fmt "state:" ++ format.nest 8 (format.line ++ o^.to_tactic_state^.to_format)) | _ := do s ← vm.obj_to_string o, return $ to_fmt s end meta def display_args_aux : nat β†’ vm unit | i := do sz ← vm.stack_size, if i = sz then return () else do o ← vm.stack_obj i, (n, t) ← vm.stack_obj_info i, fmt ← obj_fmt o, vm.trace (to_fmt " " ++ to_fmt n ++ " := " ++ fmt), display_args_aux (i+1) meta def display_args : vm unit := do bp ← vm.bp, display_args_aux bp meta def basic_monitor : vm_monitor nat := { init := 1000, step := Ξ» sz, do csz ← vm.call_stack_size, if sz = csz then return sz else do fn ← vm.curr_fn, pos ← pos_info fn, vm.trace (to_fmt "[" ++ csz ++ "]: " ++ to_fmt fn ++ " @ " ++ pos), display_args, return csz } run_command vm_monitor.register `basic_monitor set_option debugger true open tactic example (a b : Prop) : a β†’ b β†’ a ∧ b := by (intros >> constructor >> repeat assumption)
f40a5f0ace9f80c07c4e38f098a116b9f4f06554
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/polynomial/ring_division.lean
2dfa0d08125592223c47ddbe28f3e05d8199ede0
[ "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
36,742
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, Johan Commelin -/ import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div import ring_theory.localization.fraction_ring import algebra.polynomial.big_operators /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ ## Main definitions * `polynomial.roots p`: The multiset containing all the roots of `p`, including their multiplicities. * `polynomial.root_set p E`: The set of distinct roots of `p` in an algebra `E`. ## Main statements * `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a` ranges through its roots. -/ noncomputable theory open_locale classical polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {a b : R} {n : β„•} section comm_ring variables [comm_ring R] {p q : R[X]} section variables [semiring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p β‰  0) {z : S} (hz : aeval z p = 0) (inj : βˆ€ (x : R), algebra_map R S x = 0 β†’ x = 0) : 0 < p.nat_degree := nat_degree_pos_of_evalβ‚‚_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p β‰  0) {z : S} (hz : aeval z p = 0) (inj : βˆ€ (x : R), algebra_map R S x = 0 β†’ x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma mod_by_monic_eq_of_dvd_sub (hq : q.monic) {p₁ pβ‚‚ : R[X]} (h : q ∣ (p₁ - pβ‚‚)) : p₁ %β‚˜ q = pβ‚‚ %β‚˜ q := begin nontriviality R, obtain ⟨f, sub_eq⟩ := h, refine (div_mod_by_monic_unique (pβ‚‚ /β‚˜ q + f) _ hq ⟨_, degree_mod_by_monic_lt _ hq⟩).2, rw [sub_eq_iff_eq_add.mp sub_eq, mul_add, ← add_assoc, mod_by_monic_add_div _ hq, add_comm] end lemma add_mod_by_monic (p₁ pβ‚‚ : R[X]) : (p₁ + pβ‚‚) %β‚˜ q = p₁ %β‚˜ q + pβ‚‚ %β‚˜ q := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (p₁ /β‚˜ q + pβ‚‚ /β‚˜ q) _ hq ⟨by rw [mul_add, add_left_comm, add_assoc, mod_by_monic_add_div _ hq, ← add_assoc, add_comm (q * _), mod_by_monic_add_div _ hq], (degree_add_le _ _).trans_lt (max_lt (degree_mod_by_monic_lt _ hq) (degree_mod_by_monic_lt _ hq))⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end lemma smul_mod_by_monic (c : R) (p : R[X]) : (c β€’ p) %β‚˜ q = c β€’ (p %β‚˜ q) := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (c β€’ (p /β‚˜ q)) (c β€’ (p %β‚˜ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, mod_by_monic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_mod_by_monic_lt _ hq)⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end /-- `_ %β‚˜ q` as an `R`-linear map. -/ @[simps] def mod_by_monic_hom (q : R[X]) : R[X] β†’β‚—[R] R[X] := { to_fun := Ξ» p, p %β‚˜ q, map_add' := add_mod_by_monic, map_smul' := smul_mod_by_monic } end section variables [ring S] lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : R[X]} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %β‚˜ q) = aeval x p := -- `evalβ‚‚_mod_by_monic_eq_self_of_root` doesn't work here as it needs commutativity by rw [mod_by_monic_eq_sub_mul_div p hq, _root_.map_sub, _root_.map_mul, hx, zero_mul, sub_zero] end end comm_ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} instance : no_zero_divisors R[X] := { eq_zero_or_eq_zero_of_mul_eq_zero := Ξ» a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } lemma nat_degree_mul (hp : p β‰  0) (hq : q β‰  0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] lemma trailing_degree_mul : (p * q).trailing_degree = p.trailing_degree + q.trailing_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, trailing_degree_zero, top_add] }, by_cases hq : q = 0, { rw [hq, mul_zero, trailing_degree_zero, add_top] }, rw [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, trailing_degree_eq_nat_trailing_degree (mul_ne_zero hp hq), nat_trailing_degree_mul hp hq, with_top.coe_add], end @[simp] lemma nat_degree_pow (p : R[X]) (n : β„•) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma degree_le_mul_left (p : R[X]) (hq : q β‰  0) : degree p ≀ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q β‰  0) : p.nat_degree ≀ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end lemma degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q β‰  0) : degree p ≀ degree q := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, exact degree_le_mul_left p h2.2, end /-- This lemma is useful for working with the `int_degree` of a rational function. -/ lemma nat_degree_sub_eq_of_prod_eq {p₁ pβ‚‚ q₁ qβ‚‚ : polynomial R} (hp₁ : p₁ β‰  0) (hq₁ : q₁ β‰  0) (hpβ‚‚ : pβ‚‚ β‰  0) (hqβ‚‚ : qβ‚‚ β‰  0) (h_eq : p₁ * qβ‚‚ = pβ‚‚ * q₁) : (p₁.nat_degree : β„€) - q₁.nat_degree = (pβ‚‚.nat_degree : β„€) - qβ‚‚.nat_degree := begin rw sub_eq_sub_iff_add_eq_add, norm_cast, rw [← nat_degree_mul hp₁ hqβ‚‚, ← nat_degree_mul hpβ‚‚ hq₁, h_eq] end variables [char_zero R] @[simp] lemma degree_bit0_eq (p : R[X]) : degree (bit0 p) = degree p := by rw [bit0_eq_two_mul, degree_mul, (by simp : (2 : polynomial R) = C 2), @polynomial.degree_C R _ _ two_ne_zero', zero_add] @[simp] lemma nat_degree_bit0_eq (p : R[X]) : nat_degree (bit0 p) = nat_degree p := nat_degree_eq_of_degree_eq $ degree_bit0_eq p @[simp] lemma nat_degree_bit1_eq (p : R[X]) : nat_degree (bit1 p) = nat_degree p := begin rw bit1, apply le_antisymm, convert nat_degree_add_le _ _, { simp, }, by_cases h : p.nat_degree = 0, { simp [h], }, apply le_nat_degree_of_ne_zero, intro hh, apply h, simp [*, coeff_one, if_neg (ne.symm h)] at *, end lemma degree_bit1_eq {p : R[X]} (hp : 0 < degree p) : degree (bit1 p) = degree p := begin rw [bit1, degree_add_eq_left_of_degree_lt, degree_bit0_eq], rwa [degree_one, degree_bit0_eq] end end no_zero_divisors section no_zero_divisors variables [comm_semiring R] [no_zero_divisors R] {p q : R[X]} lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h end no_zero_divisors section ring variables [ring R] [is_domain R] {p q : R[X]} instance : is_domain R[X] := { ..polynomial.no_zero_divisors, ..polynomial.nontrivial, } end ring section comm_ring variables [comm_ring R] [is_domain R] {p q : R[X]} section roots open multiset lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p β‰  0, from Ξ» hp0, by simpa [hp0] using hq, have hq0 : q β‰  0, from Ξ» hp0, by simpa [hp0] using hq, have nat_degree (1 : R[X]) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : R[X]Λ£) : degree (u : R[X]) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C r, Ξ» _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : R[X]) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm β–Έ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : R[X]) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu, apply_instance, end lemma root_multiplicity_mul {p q : R[X]} {x : R} (hpq : p * q β‰  0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p β‰  0 := left_ne_zero_of_mul hpq, have hq : q β‰  0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : β„•) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := pow_ne_zero n.succ (X_sub_C_ne_zero a), rw pow_succ (X - C a) n at hzero ⊒, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ lemma root_multiplicity_of_dvd {p : R[X]} {a : R} {n : β„•} (hzero : p β‰  0) (h : (X - C a) ^ n ∣ p) : n ≀ root_multiplicity a p := begin obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h, rw hq at hzero, simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow, ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right], end /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : R[X]} (a : R) (hzero : p + q β‰  0) : min (root_multiplicity a p) (root_multiplicity a q) ≀ root_multiplicity a (p + q) := begin refine root_multiplicity_of_dvd hzero _, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end lemma exists_multiset_roots : βˆ€ {p : R[X]} (hp : p β‰  0), βˆƒ s : multiset R, (s.card : with_bot β„•) ≀ degree p ∧ βˆ€ a, s.count a = root_multiplicity a p | p := Ξ» hp, by haveI := classical.prop_decidable (βˆƒ x, is_root p x); exact if h : βˆƒ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /β‚˜ (X - C x) β‰  0 := Ξ» h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /β‚˜ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm β–Έ dec_trivial), let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /β‚˜ (X - C x)) hd0 in have hdeg : degree (X - C x) ≀ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /β‚˜ (X - C x) β‰  0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)).1 $ not_lt.2 hdeg, ⟨x ::β‚˜ t, calc (card (x ::β‚˜ t) : with_bot β„•) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≀ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot β„•)) htd, begin assume a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm β–Έ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : R[X]) : multiset R := if h : p = 0 then βˆ… else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : R[X]).roots = 0 := dif_pos rfl lemma card_roots (hp0 : p β‰  0) : ((roots p).card : with_bot β„•) ≀ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_multiset_roots hp0)).1 end lemma card_roots' (p : R[X]) : p.roots.card ≀ nat_degree p := begin by_cases hp0 : p = 0, { simp [hp0], }, exact with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) end lemma card_roots_sub_C {p : R[X]} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot β„•) ≀ degree p := calc ((p - C a).roots.card : with_bot β„•) ≀ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ Ξ» h, not_le_of_gt hp0 $ h.symm β–Έ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : R[X]} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≀ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (Ξ» h, by simp [*, lt_irrefl] at *))) @[simp] lemma count_roots (p : R[X]) : p.roots.count a = root_multiplicity a p := begin by_cases hp : p = 0, { simp [hp], }, rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a end @[simp] lemma mem_roots (hp : p β‰  0) : a ∈ p.roots ↔ is_root p a := by rw [← count_pos, count_roots p, root_multiplicity_pos hp] lemma ne_zero_of_mem_roots (h : a ∈ p.roots) : p β‰  0 := Ξ» hp, by rwa [hp, roots_zero] at h lemma is_root_of_mem_roots (h : a ∈ p.roots) : is_root p a := (mem_roots $ ne_zero_of_mem_roots h).mp h theorem card_le_degree_of_subset_roots {p : R[X]} {Z : finset R} (h : Z.val βŠ† p.roots) : Z.card ≀ p.nat_degree := (multiset.card_le_of_le (finset.val_le_iff_val_subset.2 h)).trans (polynomial.card_roots' p) lemma finite_set_of_is_root {p : R[X]} (hp : p β‰  0) : set.finite {x | is_root p x} := by simpa only [← finset.set_of_mem, mem_to_finset, mem_roots hp] using p.roots.to_finset.finite_to_set lemma eq_zero_of_infinite_is_root (p : R[X]) (h : set.infinite {x | is_root p x}) : p = 0 := not_imp_comm.mp finite_set_of_is_root h lemma exists_max_root [linear_order R] (p : R[X]) (hp : p β‰  0) : βˆƒ xβ‚€, βˆ€ x, p.is_root x β†’ x ≀ xβ‚€ := set.exists_upper_bound_image _ _ $ finite_set_of_is_root hp lemma exists_min_root [linear_order R] (p : R[X]) (hp : p β‰  0) : βˆƒ xβ‚€, βˆ€ x, p.is_root x β†’ xβ‚€ ≀ x := set.exists_lower_bound_image _ _ $ finite_set_of_is_root hp lemma eq_of_infinite_eval_eq (p q : R[X]) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : R[X]} (hpq : p * q β‰  0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ Ξ» r, by rw [count_add, count_roots, count_roots, count_roots, root_multiplicity_mul hpq] lemma roots.le_of_dvd (h : q β‰  0) : p ∣ q β†’ roots p ≀ roots q := begin rintro ⟨k, rfl⟩, exact multiset.le_iff_exists_add.mpr ⟨k.roots, roots_mul h⟩ end @[simp] lemma mem_roots_sub_C {p : R[X]} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a β‰  0, from mt sub_eq_zero.1 $ Ξ» h, not_le_of_gt hp0 $ h.symm β–Έ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin ext s, rw [count_roots, root_multiplicity_X_sub_C], split_ifs with h, { rw [h, count_singleton_self] }, { rw [←cons_zero, count_cons_of_ne h, count_zero] } end @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ Ξ» r, by rw [count_roots, count_zero, root_multiplicity_eq_zero (not_is_root_C _ _ H)] @[simp] lemma roots_one : (1 : R[X]).roots = βˆ… := roots_C 1 lemma roots_smul_nonzero (p : R[X]) {r : R} (hr : r β‰  0) : (r β€’ p).roots = p.roots := begin by_cases hp : p = 0; simp [smul_eq_C_mul, roots_mul, hr, hp] end lemma roots_list_prod (L : list R[X]) : ((0 : R[X]) βˆ‰ L) β†’ L.prod.roots = (L : multiset R[X]).bind roots := list.rec_on L (Ξ» _, roots_one) $ Ξ» hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset R[X]) : (0 : R[X]) βˆ‰ m β†’ m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [multiset.coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ΞΉ : Type*} (f : ΞΉ β†’ R[X]) (s : finset ΞΉ) : s.prod f β‰  0 β†’ (s.prod f).roots = s.val.bind (Ξ» i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end lemma roots_prod_X_sub_C (s : finset R) : (s.prod (Ξ» a, X - C a)).roots = s.val := (roots_prod (Ξ» a, X - C a) s (prod_ne_zero_iff.mpr (Ξ» a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) @[simp] lemma roots_multiset_prod_X_sub_C (s : multiset R) : (s.map (Ξ» a, X - C a)).prod.roots = s := begin rw [roots_multiset_prod, multiset.bind_map], { simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id'] }, { rw [multiset.mem_map], rintro ⟨a, -, h⟩, exact X_sub_C_ne_zero a h }, end @[simp] lemma nat_degree_multiset_prod_X_sub_C_eq_card (s : multiset R): (s.map (Ξ» a, X - C a)).prod.nat_degree = s.card := begin rw [nat_degree_multiset_prod_of_monic, multiset.map_map], { convert multiset.sum_repeat 1 _, { convert multiset.map_const _ 1, ext, apply nat_degree_X_sub_C }, { simp } }, { intros f hf, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.1 hf, exact monic_X_sub_C a }, end lemma card_roots_X_pow_sub_C {n : β„•} (hn : 0 < n) (a : R) : (roots ((X : R[X]) ^ n - C a)).card ≀ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : R[X]) ^ n - C a)).card : with_bot β„•) ≀ degree ((X : R[X]) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section variables {A B : Type*} [comm_ring A] [comm_ring B] lemma le_root_multiplicity_map {p : A[X]} {f : A β†’+* B} (hmap : map f p β‰  0) (a : A) : root_multiplicity a p ≀ root_multiplicity (f a) (map f p) := begin have hp0 : p β‰  0 := Ξ» h, hmap (h.symm β–Έ polynomial.map_zero f), rw [root_multiplicity, root_multiplicity, dif_neg hp0, dif_neg hmap], simp only [not_not, nat.lt_find_iff, nat.le_find_iff], intros m hm, have := (map_ring_hom f).map_dvd (hm m le_rfl), simpa only [coe_map_ring_hom, map_pow, map_sub, map_X, map_C], end lemma eq_root_multiplicity_map {p : A[X]} {f : A β†’+* B} (hf : function.injective f) (a : A) : root_multiplicity a p = root_multiplicity (f a) (map f p) := begin by_cases hp0 : p = 0, { simp only [hp0, root_multiplicity_zero, polynomial.map_zero], }, have hmap : map f p β‰  0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, apply le_antisymm (le_root_multiplicity_map hmap a), rw [root_multiplicity, root_multiplicity, dif_neg hp0, dif_neg hmap], simp only [not_not, nat.lt_find_iff, nat.le_find_iff], intros m hm, rw ← map_dvd_map f hf ((monic_X_sub_C a).pow _), convert hm m le_rfl, simp only [polynomial.map_pow, polynomial.map_sub, map_pow, map_sub, map_X, map_C], end lemma count_map_roots [is_domain A] (p : A[X]) {f : A β†’+* B} (hf : function.injective f) (a : B) : count a (p.roots.map f) ≀ root_multiplicity a (map f p) := begin by_cases h : βˆƒ t, f t = a, { rcases h with ⟨h_w, rfl⟩, rw [multiset.count_map_eq_count' f _ hf, count_roots], exact (eq_root_multiplicity_map hf h_w).le }, { suffices : (multiset.map f p.roots).count a = 0, { rw this, exact zero_le _, }, rw [multiset.count_map, multiset.card_eq_zero, multiset.filter_eq_nil], rintro k hk rfl, exact h ⟨k, rfl⟩, }, end lemma roots_map_of_injective_card_eq_total_degree [is_domain A] [is_domain B] {p : A[X]} {f : A β†’+* B} (hf : function.injective f) (hroots : p.roots.card = p.nat_degree) : p.roots.map f = (map f p).roots := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, polynomial.map_zero], }, have hmap : map f p β‰  0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, apply multiset.eq_of_le_of_card_le, { simpa only [multiset.le_iff_count, count_roots] using count_map_roots p hf }, { simpa only [multiset.card_map, hroots] using (card_roots' _).trans (nat_degree_map_le f p) }, end end section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : β„•) (a : R) : multiset R := roots ((X : R[X]) ^ n - C a) @[simp] lemma mem_nth_roots {n : β„•} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : β„•) (a : R) : (nth_roots n a).card ≀ n := if hn : n = 0 then if h : (X : R[X]) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], exact degree_C_le })) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : β„•) (R : Type*) [comm_ring R] [is_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : β„•} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : β„•) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] @[simp] lemma nth_roots_finset_zero : nth_roots_finset 0 R = βˆ… := by simp [nth_roots_finset] end nth_roots lemma monic.comp (hp : p.monic) (hq : q.monic) (h : q.nat_degree β‰  0) : (p.comp q).monic := by rw [monic.def, leading_coeff_comp h, monic.def.1 hp, monic.def.1 hq, one_pow, one_mul] lemma monic.comp_X_add_C (hp : p.monic) (r : R) : (p.comp (X + C r)).monic := begin refine hp.comp (monic_X_add_C _) (Ξ» ha, _), rw [nat_degree_X_add_C] at ha, exact one_ne_zero ha end lemma monic.comp_X_sub_C (hp : p.monic) (r : R) : (p.comp (X - C r)).monic := by simpa using hp.comp_X_add_C (-r) lemma units_coeff_zero_smul (c : R[X]Λ£) (p : R[X]) : (c : R[X]).coeff 0 β€’ p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : R[X]Λ£) : nat_degree (u : R[X]) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact Ξ» h, or.rec (Ξ» h, by rw [h, zero_comp]) (Ξ» h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : R[X]) (h : βˆ€ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, Ξ» x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : R[X]} (ext : βˆ€ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end variables [comm_ring T] /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : set S := (p.map (algebra_map T S)).roots.to_finset lemma root_set_def (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : p.root_set S = (p.map (algebra_map T S)).roots.to_finset := rfl @[simp] lemma root_set_zero (S) [comm_ring S] [is_domain S] [algebra T S] : (0 : T[X]).root_set S = βˆ… := by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty] @[simp] lemma root_set_C [comm_ring S] [is_domain S] [algebra T S] (a : T) : (C a).root_set S = βˆ… := by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] instance root_set_fintype (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : (p.root_set S).finite := set.to_finite _ theorem mem_root_set_iff' {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] (hp : p.map (algebra_map T S) β‰  0) (a : S) : a ∈ p.root_set S ↔ (p.map (algebra_map T S)).eval a = 0 := by { change a ∈ multiset.to_finset _ ↔ _, rw [mem_to_finset, mem_roots hp], refl } theorem mem_root_set_iff {p : T[X]} (hp : p β‰  0) {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] (a : S) : a ∈ p.root_set S ↔ aeval a p = 0 := begin rw [mem_root_set_iff', ←evalβ‚‚_eq_eval_map], { refl }, intro h, rw ←polynomial.map_zero (algebra_map T S) at h, exact hp (map_injective _ (no_zero_smul_divisors.algebra_map_injective T S) h) end lemma root_set_maps_to {p : T[X]} {S S'} [comm_ring S] [is_domain S] [algebra T S] [comm_ring S'] [is_domain S'] [algebra T S'] (hp : p.map (algebra_map T S') β‰  0) (f : S →ₐ[T] S') : (p.root_set S).maps_to f (p.root_set S') := Ξ» x hx, begin rw [mem_root_set_iff' hp, ← f.comp_algebra_map, ← map_map, eval_map], erw [evalβ‚‚_hom, (mem_root_set_iff' (mt (Ξ» h, _) hp) x).1 hx, _root_.map_zero], rw [← f.comp_algebra_map, ← map_map, h, polynomial.map_zero], end lemma ne_zero_of_mem_root_set {p : T[X]} [comm_ring S] [is_domain S] [algebra T S] {a : S} (h : a ∈ p.root_set S) : p β‰  0 := Ξ» hf, by rwa [hf, root_set_zero] at h lemma aeval_eq_zero_of_mem_root_set {p : T[X]} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] {a : S} (hx : a ∈ p.root_set S) : aeval a p = 0 := (mem_root_set_iff (ne_zero_of_mem_root_set hx) a).mp hx end roots theorem is_unit_iff {f : R[X]} : is_unit f ↔ βˆƒ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) β–Έ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, Ξ» ⟨r, hr, hrf⟩, hrf β–Έ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : R[X]Λ£) : coeff (u : R[X]) 0 β‰  0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg, this.elim (Ξ» h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have hβ‚‚ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at hβ‚‚; exact absurd hβ‚‚ dec_trivial) (Ξ» hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [comm_ring R] {p q : R[X]} (hmonic : q.monic) (hdegree : q.degree ≀ p.degree) : (p /β‚˜ q).leading_coeff = p.leading_coeff := begin nontriviality, have h : q.leading_coeff * (p /β‚˜ q).leading_coeff β‰  0, { simpa [div_by_monic_eq_zero_iff hmonic, hmonic.leading_coeff, nat.with_bot.one_le_iff_zero_lt] using hdegree }, nth_rewrite_rhs 0 ←mod_by_monic_add_div p hmonic, rw [leading_coeff_add_of_degree_lt, leading_coeff_monic_mul hmonic], rw [degree_mul' h, degree_add_div_by_monic hmonic hdegree], exact (degree_mod_by_monic_lt p hmonic).trans_le hdegree end lemma leading_coeff_div_by_monic_X_sub_C (p : R[X]) (hp : degree p β‰  0) (a : R) : leading_coeff (p /β‚˜ (X - C a)) = leading_coeff p := begin nontriviality, cases hp.lt_or_lt with hd hd, { rw [degree_eq_bot.mp $ (nat.with_bot.lt_zero_iff _).mp hd, zero_div_by_monic] }, refine leading_coeff_div_by_monic_of_monic (monic_X_sub_C a) _, rwa [degree_X_sub_C, nat.with_bot.one_le_iff_zero_lt] end lemma eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≀ p.nat_degree) : q = C q.leading_coeff * p := begin obtain ⟨r, hr⟩ := hdiv, obtain (rfl|hq) := eq_or_ne q 0, {simp}, have rzero : r β‰  0 := Ξ» h, by simpa [h, hq] using hr, rw [hr, nat_degree_mul'] at hdeg, swap, { rw [hp.leading_coeff, one_mul, leading_coeff_ne_zero], exact rzero }, rw [mul_comm, @eq_C_of_nat_degree_eq_zero _ _ r] at hr, { convert hr, convert leading_coeff_C _ using 1, rw [hr, leading_coeff_mul_monic hp] }, { exact (add_right_inj _).1 (le_antisymm hdeg $ nat.le.intro rfl) }, end lemma eq_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≀ p.nat_degree) : q = p := begin convert eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le hp hdiv hdeg, rw [hq.leading_coeff, C_1, one_mul], end lemma is_coprime_X_sub_C_of_is_unit_sub {R} [comm_ring R] {a b : R} (h : is_unit (a - b)) : is_coprime (X - C a) (X - C b) := ⟨-C h.unit⁻¹.val, C h.unit⁻¹.val, by { rw [neg_mul_comm, ← left_distrib, neg_add_eq_sub, sub_sub_sub_cancel_left, ← C_sub, ← C_mul], convert C_1, exact h.coe_inv_mul }⟩ theorem pairwise_coprime_X_sub_C {K} [field K] {I : Type v} {s : I β†’ K} (H : function.injective s) : pairwise (is_coprime on (Ξ» i : I, X - C (s i))) := Ξ» i j hij, is_coprime_X_sub_C_of_is_unit_sub (sub_ne_zero_of_ne $ H.ne hij).is_unit lemma monic_prod_multiset_X_sub_C : monic (p.roots.map (Ξ» a, X - C a)).prod := monic_multiset_prod_of_monic _ _ (Ξ» a _, monic_X_sub_C a) lemma prod_multiset_root_eq_finset_root : (p.roots.map (Ξ» a, X - C a)).prod = p.roots.to_finset.prod (Ξ» a, (X - C a) ^ root_multiplicity a p) := by simp only [count_roots, 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 : R[X]) : (p.roots.map (Ξ» a, X - C a)).prod ∣ p := begin rw ← map_dvd_map _ (is_fraction_ring.injective R $ fraction_ring R) monic_prod_multiset_X_sub_C, rw [prod_multiset_root_eq_finset_root, polynomial.map_prod], refine finset.prod_dvd_of_coprime (Ξ» a _ b _ h, _) (Ξ» a _, _), { simp_rw [polynomial.map_pow, polynomial.map_sub, map_C, map_X], exact (pairwise_coprime_X_sub_C (is_fraction_ring.injective R $ fraction_ring R) _ _ h).pow }, { exact polynomial.map_dvd _ (pow_root_multiplicity_dvd p a) }, end lemma exists_prod_multiset_X_sub_C_mul (p : R[X]) : βˆƒ q, (p.roots.map (Ξ» a, X - C a)).prod * q = p ∧ p.roots.card + q.nat_degree = p.nat_degree ∧ q.roots = 0 := begin obtain ⟨q, he⟩ := prod_multiset_X_sub_C_dvd p, use [q, he.symm], obtain (rfl|hq) := eq_or_ne q 0, { rw mul_zero at he, subst he, simp }, split, { conv_rhs { rw he }, rw [monic_prod_multiset_X_sub_C.nat_degree_mul' hq, nat_degree_multiset_prod_X_sub_C_eq_card] }, { replace he := congr_arg roots he.symm, rw [roots_mul, roots_multiset_prod_X_sub_C] at he, exacts [add_right_eq_self.1 he, mul_ne_zero monic_prod_multiset_X_sub_C.ne_zero hq] }, end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C (hroots : p.roots.card = p.nat_degree) : C p.leading_coeff * (p.roots.map (Ξ» a, X - C a)).prod = p := (eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le monic_prod_multiset_X_sub_C (prod_multiset_X_sub_C_dvd p) $ ((nat_degree_multiset_prod_X_sub_C_eq_card _).trans hroots).ge).symm /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq (hp : p.monic) (hroots : p.roots.card = p.nat_degree) : (p.roots.map (Ξ» a, X - C a)).prod = p := by { convert C_leading_coeff_mul_prod_multiset_X_sub_C hroots, rw [hp.leading_coeff, C_1, one_mul] } end comm_ring section variables [semiring R] [comm_ring S] [is_domain S] (Ο† : R β†’+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map {f : R[X]} (hf : is_unit f.leading_coeff) (H : is_unit (map Ο† f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map C _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (Ο† f.leading_coeff) := is_unit.map Ο† hf, rw h at u, simpa using u, } end end section variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] (Ο† : R β†’+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `β„€` is irreducible if it is monic and irreducible over `β„€/pβ„€` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : R[X]) (h_mon : monic f) (h_irr : irreducible (map Ο† f)) : irreducible f := begin refine ⟨h_irr.not_unit ∘ is_unit.map (map_ring_hom Ο†), Ξ» a b h, _⟩, dsimp [monic] at h_mon, have q := (leading_coeff_mul a b).symm, rw [←h, h_mon] at q, refine (h_irr.is_unit_or_is_unit $ (congr_arg (map Ο†) h).trans (polynomial.map_mul Ο†)).imp _ _; apply is_unit_of_is_unit_leading_coeff_of_is_unit_map; apply is_unit_of_mul_eq_one, { exact q }, { rw mul_comm, exact q }, end end end polynomial
581b1a11298fc14357e2d65320a313e5cc0e0c13
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/dynamics/fixed_points/topology.lean
e55f0e24a83f94bfa5431b713083ed5a21a56968
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,331
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes HΓΆlzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.dynamics.fixed_points.basic import Mathlib.topology.separation import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Topological properties of fixed points Currently this file contains two lemmas: - `is_fixed_pt_of_tendsto_iterate`: if `f^n(x) β†’ y` and `f` is continuous at `y`, then `f y = y`; - `is_closed_fixed_points`: the set of fixed points of a continuous map is a closed set. ## TODO fixed points, iterates -/ /-- If the iterates `f^[n] x` converge to `y` and `f` is continuous at `y`, then `y` is a fixed point for `f`. -/ theorem is_fixed_pt_of_tendsto_iterate {Ξ± : Type u_1} [topological_space Ξ±] [t2_space Ξ±] {f : Ξ± β†’ Ξ±} {x : Ξ±} {y : Ξ±} (hy : filter.tendsto (fun (n : β„•) => nat.iterate f n x) filter.at_top (nhds y)) (hf : continuous_at f y) : function.is_fixed_pt f y := sorry /-- The set of fixed points of a continuous map is a closed set. -/ theorem is_closed_fixed_points {Ξ± : Type u_1} [topological_space Ξ±] [t2_space Ξ±] {f : Ξ± β†’ Ξ±} (hf : continuous f) : is_closed (function.fixed_points f) := is_closed_eq hf continuous_id
5939e42987bbe01cfa2acfcf1ccbcb89738cebfb
1546f9083f4babf70df0329497d1ee05adc8c665
/src/monoidal_categories_reboot/dagger_category.lean
6121f04b0e17c54592d1ce00e3375aa17634b28b
[ "Apache-2.0" ]
permissive
khoek/monoidal-categories-reboot
0899b0d4552ff039388042059c91f7207c6c34e5
ed3df8ecce5d4e3d95cb858911bad12bb632cf8a
refs/heads/master
1,588,877,903,131
1,554,987,273,000
1,554,987,273,000
180,791,863
0
0
null
1,554,987,295,000
1,554,987,295,000
null
UTF-8
Lean
false
false
2,290
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import category_theory.category import category_theory.functor import category_theory.products import category_theory.natural_isomorphism import category_theory.tactics.obviously -- Give ourselves access to `rewrite_search` import .slice_tactic import .braided_monoidal_category import .rigid_monoidal_category universes u v namespace category_theory.dagger open category_theory open category_theory.monoidal class dagger_structure (C : Sort u) [π’ž : category.{v} C] := (dagger_hom : Ξ  {X Y : C} (f : X ⟢ Y), Y ⟢ X) (dagger_comp' : βˆ€ {X Y Z} (f : X ⟢ Y) (g : Y ⟢ Z), dagger_hom (f ≫ g) = (dagger_hom g) ≫ (dagger_hom f) . obviously) (dagger_id' : βˆ€ X, dagger_hom (πŸ™ X) = πŸ™ X . obviously) (dagger_involution' : βˆ€ {X Y : C} (f : X ⟢ Y), dagger_hom (dagger_hom f) = f . obviously) restate_axiom dagger_structure.dagger_comp' attribute [simp,search] dagger_structure.dagger_comp' restate_axiom dagger_structure.dagger_id' attribute [simp,search] dagger_structure.dagger_id' restate_axiom dagger_structure.dagger_involution' attribute [simp,search] dagger_structure.dagger_involution' postfix ` † `:10000 := dagger_structure.dagger_hom def dagger_structure.dagger {C : Sort u} [π’ž : category.{v} C] [dagger_structure C] : Cα΅’α΅– β₯€ C := { map := Ξ» {X Y} (f), (has_hom.hom.unop f)†, obj := Ξ» X, unop X } def is_unitary {C : Sort u} [category.{v} C] [dagger_structure C] {X Y : C} (f : X β‰… Y) : Prop := f.inv = f.hom† open category_theory.monoidal.monoidal_category open category_theory.monoidal.braided_monoidal_category class monoidal_dagger_structure (C : Sort u) [symmetric_monoidal_category.{v u} C] extends dagger_structure.{u v} C := (dagger_tensor' : βˆ€ {X Y X' Y' : C} (f : X ⟢ Y) (g : X' ⟢ Y'), (f βŠ— g)† = f† βŠ— g† . obviously) (associator_unitary' : βˆ€ X Y Z : C, is_unitary (associator X Y Z) . obviously) (left_unitor_unitary' : βˆ€ X : C, is_unitary (left_unitor X) . obviously) (right_unitor_unitary' : βˆ€ X : C, is_unitary (right_unitor X) . obviously) (braiding_unitary' : βˆ€ X Y : C, is_unitary (braiding X Y) . obviously) end category_theory.dagger
cd59152d91edf6f0baf3df88bf000eda53568f1d
b7fc5b86b12212bea5542eb2c9d9f0988fd78697
/src/hints/category_theory/exercise10/hint.lean
29261decae7c26f4a685d7175599147213c2bcbc
[]
no_license
stjordanis/lftcm2020
3b16591aec853c8546d9c8b69c0bf3f5f3956fee
1f3485e4dafdc587b451ec5144a1d8d3ec9b411e
refs/heads/master
1,675,958,865,413
1,609,901,722,000
1,609,901,722,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,619
lean
import category_theory.limits.shapes.zero import category_theory.full_subcategory import algebra.homology.chain_complex import data.int.basic /-! Here's a partial solution. It provides most of the data, but doesn't check required properties. It starts becoming rough going at about this point, when you start proving properties of `long_map`. -/ open category_theory open category_theory.limits namespace exercise variables (C : Type) [category.{0} C] [has_zero_morphisms C] @[derive category] def complex : Type := { F : β„€ β₯€ C // βˆ€ i : β„€, F.map (hom_of_le (by tidy) : i ⟢ i+2) = 0 } def functor : complex C β₯€ cochain_complex C := { obj := Ξ» P, { X := P.1.obj, d := Ξ» i, P.1.map (hom_of_le (by tidy) : i ⟢ i+1), d_squared' := sorry, }, map := Ξ» P Q Ξ±, { f := Ξ» i, Ξ±.app i, comm' := sorry, } } def long_map (P : cochain_complex C) (i j : β„€) : P.X i ⟢ P.X j := if hβ‚€ : j = i then eq_to_hom (by rw hβ‚€) else if h₁ : j = i+1 then P.d i ≫ eq_to_hom (by {simp [h₁]}) else 0 def inverse : cochain_complex C β₯€ complex C := { obj := Ξ» P, { val := { obj := Ξ» i, P.X i, map := Ξ» i j p, long_map C P i j, map_id' := sorry, map_comp' := sorry }, property := sorry, }, map := Ξ» P Q f, { app := Ξ» i, f.f i, naturality' := sorry, }, map_id' := sorry, map_comp' := sorry, } def exercise : complex C β‰Œ cochain_complex C := { functor := functor C, inverse := inverse C, unit_iso := sorry, -- There's still more data to provide here. counit_iso := sorry, -- and here. functor_unit_iso_comp' := sorry, } end exercise
4ac6bf601b95c81c967e539a19f298067707f6c3
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/group_theory/quotient_group.lean
d1411a170a725b0e2045d1b0a28f7776030d81e8
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
6,544
lean
/- Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot. This file is to a certain extent based on `quotient_module.lean` by Johannes HΓΆlzl. -/ import group_theory.coset universes u v variables {G : Type u} [group G] (N : set G) [normal_subgroup N] {H : Type v} [group H] namespace quotient_group instance : group (quotient N) := { one := (1 : G), mul := Ξ» a b, quotient.lift_onβ‚‚' a b (Ξ» a b, ((a * b : G) : quotient N)) (Ξ» a₁ aβ‚‚ b₁ bβ‚‚ hab₁ habβ‚‚, quot.sound ((is_subgroup.mul_mem_cancel_left N (is_subgroup.inv_mem habβ‚‚)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ bβ‚‚, ← mul_assoc bβ‚‚, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact normal_subgroup.normal _ hab₁ _))), mul_assoc := Ξ» a b c, quotient.induction_on₃' a b c (Ξ» a b c, congr_arg mk (mul_assoc a b c)), one_mul := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (one_mul a)), mul_one := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (mul_one a)), inv := Ξ» a, quotient.lift_on' a (Ξ» a, ((a⁻¹ : G) : quotient N)) (Ξ» a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab) end), mul_left_inv := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (mul_left_inv a)) } attribute [to_additive quotient_add_group.add_group._proof_6] quotient_group.group._proof_6 attribute [to_additive quotient_add_group.add_group._proof_5] quotient_group.group._proof_5 attribute [to_additive quotient_add_group.add_group._proof_4] quotient_group.group._proof_4 attribute [to_additive quotient_add_group.add_group._proof_3] quotient_group.group._proof_3 attribute [to_additive quotient_add_group.add_group._proof_2] quotient_group.group._proof_2 attribute [to_additive quotient_add_group.add_group._proof_1] quotient_group.group._proof_1 attribute [to_additive quotient_add_group.add_group] quotient_group.group attribute [to_additive quotient_add_group.add_group.equations._eqn_1] quotient_group.group.equations._eqn_1 instance : is_group_hom (mk : G β†’ quotient N) := ⟨λ _ _, rfl⟩ attribute [to_additive quotient_add_group.is_add_group_hom] quotient_group.is_group_hom attribute [to_additive quotient_add_group.is_add_group_hom.equations._eqn_1] quotient_group.is_group_hom.equations._eqn_1 instance {G : Type*} [comm_group G] (s : set G) [is_subgroup s] : comm_group (quotient s) := { mul_comm := Ξ» a b, quotient.induction_onβ‚‚' a b (Ξ» a b, congr_arg mk (mul_comm a b)), ..@quotient_group.group _ _ s (normal_subgroup_of_comm_group s) } attribute [to_additive quotient_add_group.add_comm_group._proof_6] quotient_group.comm_group._proof_6 attribute [to_additive quotient_add_group.add_comm_group._proof_5] quotient_group.comm_group._proof_5 attribute [to_additive quotient_add_group.add_comm_group._proof_4] quotient_group.comm_group._proof_4 attribute [to_additive quotient_add_group.add_comm_group._proof_3] quotient_group.comm_group._proof_3 attribute [to_additive quotient_add_group.add_comm_group._proof_2] quotient_group.comm_group._proof_2 attribute [to_additive quotient_add_group.add_comm_group._proof_1] quotient_group.comm_group._proof_1 attribute [to_additive quotient_add_group.add_comm_group] quotient_group.comm_group attribute [to_additive quotient_add_group.add_comm_group.equations._eqn_1] quotient_group.comm_group.equations._eqn_1 @[simp] lemma coe_one : ((1 : G) : quotient N) = 1 := rfl @[simp] lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl @[simp] lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : β„•) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.pow _ _ _ _ mk _ a n attribute [to_additive quotient_add_group.coe_zero] coe_one attribute [to_additive quotient_add_group.coe_add] coe_mul attribute [to_additive quotient_add_group.coe_neg] coe_inv @[simp] lemma coe_gpow (a : G) (n : β„€) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.gpow _ _ _ _ mk _ a n local notation ` Q ` := quotient N instance is_group_hom_quotient_group_mk : is_group_hom (mk : G β†’ Q) := by refine {..}; intros; refl attribute [to_additive quotient_add_group.is_add_group_hom_quotient_add_group_mk] quotient_group.is_group_hom_quotient_group_mk attribute [to_additive quotient_add_group.is_add_group_hom_quotient_add_group_mk.equations._eqn_1] quotient_group.is_group_hom_quotient_group_mk.equations._eqn_1 def lift (Ο† : G β†’ H) [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) (q : Q) : H := q.lift_on' Ο† $ assume a b (hab : a⁻¹ * b ∈ N), (calc Ο† a = Ο† a * 1 : by simp ... = Ο† a * Ο† (a⁻¹ * b) : by rw HN (a⁻¹ * b) hab ... = Ο† (a * (a⁻¹ * b)) : by rw is_group_hom.mul Ο† a (a⁻¹ * b) ... = Ο† b : by simp) attribute [to_additive quotient_add_group.lift._proof_1] lift._proof_1 attribute [to_additive quotient_add_group.lift] lift attribute [to_additive quotient_add_group.lift.equations._eqn_1] lift.equations._eqn_1 @[simp] lemma lift_mk {Ο† : G β†’ H} [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) (g : G) : lift N Ο† HN (g : Q) = Ο† g := rfl attribute [to_additive quotient_add_group.lift_mk] lift_mk @[simp] lemma lift_mk' {Ο† : G β†’ H} [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) (g : G) : lift N Ο† HN (mk g : Q) = Ο† g := rfl attribute [to_additive quotient_add_group.lift_mk'] lift_mk' variables (Ο† : G β†’ H) [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) instance is_group_hom_quotient_lift : is_group_hom (lift N Ο† HN) := ⟨λ q r, quotient.induction_onβ‚‚' q r $ Ξ» a b, show Ο† (a * b) = Ο† a * Ο† b, from is_group_hom.mul Ο† a b⟩ attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift] quotient_group.is_group_hom_quotient_lift attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift.equations._eqn_1] quotient_group.is_group_hom_quotient_lift.equations._eqn_1 open function is_group_hom @[to_additive quotient_add_group.injective_ker_lift] lemma injective_ker_lift : injective (lift (ker Ο†) Ο† $ Ξ» x h, (mem_ker Ο†).1 h) := assume a b, quotient.induction_onβ‚‚' a b $ assume a b (h : Ο† a = Ο† b), quotient.sound' $ show a⁻¹ * b ∈ ker Ο†, by rw [mem_ker Ο†, is_group_hom.mul Ο†, ← h, is_group_hom.inv Ο†, inv_mul_self] end quotient_group
28ef97388096d2d22151a8e3ad863a0efc0bd9bb
3863d2564418bccb1859e057bf5a4ef240e75fd7
/hott/eq2.hlean
5563983616ebc25f29af2d129d43a4614d604d84
[ "Apache-2.0" ]
permissive
JacobGross/lean
118bbb067ff4d4af48a266face2c7eb9868fa91c
eb26087df940c54337cb807b4bc6d345d1fc1085
refs/heads/master
1,582,735,011,532
1,462,557,826,000
1,462,557,826,000
46,451,196
0
0
null
1,462,557,826,000
1,447,885,161,000
C++
UTF-8
Lean
false
false
4,644
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about 2-dimensional paths -/ import .cubical.square open function namespace eq variables {A B C : Type} {f : A β†’ B} {a a' a₁ aβ‚‚ a₃ aβ‚„ : A} {b b' : B} theorem ap_is_constant_eq (p : Ξ x, f x = b) (q : a = a') : ap_is_constant p q = eq_con_inv_of_con_eq ((eq_of_square (square_of_pathover (apd p q)))⁻¹ ⬝ whisker_left (p a) (ap_constant q b)) := begin induction q, esimp, generalize (p a), intro p, cases p, apply idpath idp end definition ap_inv2 {p q : a = a'} (r : p = q) : square (ap (ap f) (inverse2 r)) (inverse2 (ap (ap f) r)) (ap_inv f p) (ap_inv f q) := by induction r;exact hrfl definition ap_con2 {p₁ q₁ : a₁ = aβ‚‚} {pβ‚‚ qβ‚‚ : aβ‚‚ = a₃} (r₁ : p₁ = q₁) (rβ‚‚ : pβ‚‚ = qβ‚‚) : square (ap (ap f) (r₁ β—Ύ rβ‚‚)) (ap (ap f) r₁ β—Ύ ap (ap f) rβ‚‚) (ap_con f p₁ pβ‚‚) (ap_con f q₁ qβ‚‚) := by induction rβ‚‚;induction r₁;exact hrfl theorem ap_con_right_inv_sq {A B : Type} {a1 a2 : A} (f : A β†’ B) (p : a1 = a2) : square (ap (ap f) (con.right_inv p)) (con.right_inv (ap f p)) (ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p)) idp := by cases p;apply hrefl theorem ap_con_left_inv_sq {A B : Type} {a1 a2 : A} (f : A β†’ B) (p : a1 = a2) : square (ap (ap f) (con.left_inv p)) (con.left_inv (ap f p)) (ap_con f p⁻¹ p ⬝ whisker_right (ap_inv f p) _) idp := by cases p;apply vrefl theorem ap_ap_is_constant {A B C : Type} (g : B β†’ C) {f : A β†’ B} {b : B} (p : Ξ x, f x = b) {x y : A} (q : x = y) : square (ap (ap g) (ap_is_constant p q)) (ap_is_constant (Ξ»a, ap g (p a)) q) (ap_compose g f q)⁻¹ (!ap_con ⬝ whisker_left _ !ap_inv) := begin induction q, esimp, generalize (p x), intro p, cases p, apply ids -- induction q, rewrite [↑ap_compose,ap_inv], apply hinverse, apply ap_con_right_inv_sq, end theorem ap_ap_compose {A B C D : Type} (h : C β†’ D) (g : B β†’ C) (f : A β†’ B) {x y : A} (p : x = y) : square (ap_compose (h ∘ g) f p) (ap (ap h) (ap_compose g f p)) (ap_compose h (g ∘ f) p) (ap_compose h g (ap f p)) := by induction p;exact ids theorem ap_compose_inv {A B C : Type} (g : B β†’ C) (f : A β†’ B) {x y : A} (p : x = y) : square (ap_compose g f p⁻¹) (inverse2 (ap_compose g f p) ⬝ (ap_inv g (ap f p))⁻¹) (ap_inv (g ∘ f) p) (ap (ap g) (ap_inv f p)) := by induction p;exact ids theorem ap_compose_con (g : B β†’ C) (f : A β†’ B) (p : a₁ = aβ‚‚) (q : aβ‚‚ = a₃) : square (ap_compose g f (p ⬝ q)) (ap_compose g f p β—Ύ ap_compose g f q ⬝ (ap_con g (ap f p) (ap f q))⁻¹) (ap_con (g ∘ f) p q) (ap (ap g) (ap_con f p q)) := by induction q;induction p;exact ids theorem ap_compose_natural {A B C : Type} (g : B β†’ C) (f : A β†’ B) {x y : A} {p q : x = y} (r : p = q) : square (ap (ap (g ∘ f)) r) (ap (ap g ∘ ap f) r) (ap_compose g f p) (ap_compose g f q) := natural_square (ap_compose g f) r theorem whisker_right_eq_of_con_inv_eq_idp {p q : a₁ = aβ‚‚} (r : p ⬝ q⁻¹ = idp) : whisker_right (eq_of_con_inv_eq_idp r) q⁻¹ ⬝ con.right_inv q = r := by induction q; esimp at r; cases r; reflexivity theorem ap_eq_of_con_inv_eq_idp (f : A β†’ B) {p q : a₁ = aβ‚‚} (r : p ⬝ q⁻¹ = idp) : ap02 f (eq_of_con_inv_eq_idp r) = eq_of_con_inv_eq_idp (whisker_left _ !ap_inv⁻¹ ⬝ !ap_con⁻¹ ⬝ ap02 f r) := by induction q;esimp at *;cases r;reflexivity theorem eq_of_con_inv_eq_idp_con2 {p p' q q' : a₁ = aβ‚‚} (r : p = p') (s : q = q') (t : p' ⬝ q'⁻¹ = idp) : eq_of_con_inv_eq_idp (r β—Ύ inverse2 s ⬝ t) = r ⬝ eq_of_con_inv_eq_idp t ⬝ s⁻¹ := by induction s;induction r;induction q;reflexivity definition naturality_apd_eq {A : Type} {B : A β†’ Type} {a aβ‚‚ : A} {f g : Ξ a, B a} (H : f ~ g) (p : a = aβ‚‚) : apd f p = concato_eq (eq_concato (H a) (apd g p)) (H aβ‚‚)⁻¹ := begin induction p, esimp, generalizes [H a, g a], intro ga Ha, induction Ha, reflexivity end theorem con_tr_idp {P : A β†’ Type} {x y : A} (q : x = y) (u : P x) : con_tr idp q u = ap (Ξ»p, p β–Έ u) (idp_con q) := by induction q;reflexivity end eq
d162c3e289173069859b49a9e48702843e15ee10
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/meta/smt/interactive.lean
65177d0d8454f860089a45281a18d11d9e3bbc26
[ "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
10,191
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.smt_tactic init.meta.interactive import init.meta.smt.rsimp namespace smt_tactic meta def save_info (p : pos) : smt_tactic unit := do (ss, ts) ← smt_tactic.read, tactic.save_info_thunk p (Ξ» _, smt_state.to_format ss ts) meta def skip : smt_tactic unit := return () meta def solve_goals : smt_tactic unit := repeat close meta def step {Ξ± : Type} (tac : smt_tactic Ξ±) : smt_tactic unit := tac >> solve_goals meta def istep {Ξ± : Type} (line : nat) (col : nat) (tac : smt_tactic Ξ±) : smt_tactic unit := Ξ» ss ts, @scope_trace _ line col ((tac >> solve_goals) ss ts) meta def rstep {Ξ± : Type} (line : nat) (col : nat) (tac : smt_tactic Ξ±) : smt_tactic unit := Ξ» ss ts, result.cases_on (istep line col tac ss ts) (Ξ» ⟨a, new_ss⟩ new_ts, result.success ((), new_ss) new_ts) (Ξ» msg_thunk e, tactic.report_exception line col msg_thunk) meta def execute (tac : smt_tactic unit) : tactic unit := using_smt tac meta def execute_with (cfg : smt_config) (tac : smt_tactic unit) : tactic unit := using_smt tac cfg namespace interactive open lean.parser open interactive open interactive.types local postfix ?:9001 := optional local postfix *:9001 := many meta def itactic : Type := smt_tactic unit meta def irtactic : Type := smt_tactic unit meta def intros : parse ident* β†’ smt_tactic unit | [] := smt_tactic.intros | hs := smt_tactic.intro_lst hs /-- Try to close main goal by using equalities implied by the congruence closure module. -/ meta def close : smt_tactic unit := smt_tactic.close /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from lemmas in the main goal with terms in the main goal. The set of lemmas is populated with theorems tagged with the attribute specified at smt_config.em_attr, and lemmas added using tactics such as `smt_tactic.add_lemmas`. The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`. -/ meta def ematch : smt_tactic unit := smt_tactic.ematch meta def apply (q : parse texpr) : smt_tactic unit := tactic.interactive.apply q meta def fapply (q : parse texpr) : smt_tactic unit := tactic.interactive.fapply q meta def apply_instance : smt_tactic unit := tactic.apply_instance meta def change (q : parse texpr) : smt_tactic unit := tactic.interactive.change q meta def exact (q : parse texpr) : smt_tactic unit := tactic.interactive.exact q meta def assert (h : parse ident) (q : parse $ tk ":" *> texpr) : smt_tactic unit := do e ← tactic.to_expr_strict q, smt_tactic.assert h e meta def define (h : parse ident) (q : parse $ tk ":" *> texpr) : smt_tactic unit := do e ← tactic.to_expr_strict q, smt_tactic.define h e meta def assertv (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (qβ‚‚ : parse $ tk ":=" *> texpr) : smt_tactic unit := do t ← tactic.to_expr_strict q₁, v ← tactic.to_expr_strict ``(%%qβ‚‚ : %%t), smt_tactic.assertv h t v meta def definev (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (qβ‚‚ : parse $ tk ":=" *> texpr) : smt_tactic unit := do t ← tactic.to_expr_strict q₁, v ← tactic.to_expr_strict ``(%%qβ‚‚ : %%t), smt_tactic.definev h t v meta def note (h : parse ident) (q : parse $ tk ":=" *> texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.note h p meta def pose (h : parse ident) (q : parse $ tk ":=" *> texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.pose h p meta def add_fact (q : parse texpr) : smt_tactic unit := do h ← tactic.get_unused_name `h none, p ← tactic.to_expr_strict q, smt_tactic.note h p meta def trace_state : smt_tactic unit := smt_tactic.trace_state meta def trace {Ξ± : Type} [has_to_tactic_format Ξ±] (a : Ξ±) : smt_tactic unit := tactic.trace a meta def destruct (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.destruct p meta def by_cases (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.by_cases p meta def by_contradiction : smt_tactic unit := smt_tactic.by_contradiction meta def by_contra : smt_tactic unit := smt_tactic.by_contradiction open tactic (resolve_name transparency to_expr) private meta def report_invalid_em_lemma {Ξ± : Type} (n : name) : tactic Ξ± := fail ("invalid ematch lemma '" ++ to_string n ++ "'") private meta def add_lemma_name (md : transparency) (lhs_lemma : bool) (n : name) (ref : expr) : smt_tactic unit := do e ← resolve_name n, match e with | expr.const n _ := (add_ematch_lemma_from_decl_core md lhs_lemma n >> tactic.save_const_type_info n ref) <|> report_invalid_em_lemma n | _ := (add_ematch_lemma_core md lhs_lemma e >> try (tactic.save_type_info e ref)) <|> report_invalid_em_lemma n end private meta def add_lemma_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) : smt_tactic unit := let e := pexpr.to_raw_expr p in match e with | (expr.const c []) := add_lemma_name md lhs_lemma c e | (expr.local_const c _ _ _) := add_lemma_name md lhs_lemma c e | _ := do new_e ← to_expr p, add_ematch_lemma_core md lhs_lemma new_e end private meta def add_lemma_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr β†’ smt_tactic unit | [] := return () | (p::ps) := add_lemma_pexpr md lhs_lemma p >> add_lemma_pexprs ps meta def add_lemma (l : parse qexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible ff l meta def add_lhs_lemma (l : parse qexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible tt l private meta def add_eqn_lemmas_for_core (md : transparency) : list name β†’ smt_tactic unit | [] := return () | (c::cs) := do e ← resolve_name c, match e with | expr.const n _ := add_ematch_eqn_lemmas_for_core md n >> add_eqn_lemmas_for_core cs | _ := fail $ "'" ++ to_string c ++ "' is not a constant" end meta def add_eqn_lemmas_for (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for_core reducible ids meta def add_eqn_lemmas (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for ids private meta def add_hinst_lemma_from_name (md : transparency) (lhs_lemma : bool) (n : name) (hs : hinst_lemmas) (ref : expr) : smt_tactic hinst_lemmas := do e ← resolve_name n, match e with | expr.const n _ := (do h ← hinst_lemma.mk_from_decl_core md n lhs_lemma, tactic.save_const_type_info n ref, return $ hs^.add h) <|> (do hs₁ ← mk_ematch_eqn_lemmas_for_core md n, tactic.save_const_type_info n ref, return $ hs^.merge hs₁) <|> report_invalid_em_lemma n | _ := (do h ← hinst_lemma.mk_core md e lhs_lemma, try (tactic.save_type_info e ref), return $ hs^.add h) <|> report_invalid_em_lemma n end private meta def add_hinst_lemma_from_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) (hs : hinst_lemmas) : smt_tactic hinst_lemmas := let e := pexpr.to_raw_expr p in match e with | (expr.const c []) := add_hinst_lemma_from_name md lhs_lemma c hs e | (expr.local_const c _ _ _) := add_hinst_lemma_from_name md lhs_lemma c hs e | _ := do new_e ← to_expr p, h ← hinst_lemma.mk_core md new_e lhs_lemma, return $ hs^.add h end private meta def add_hinst_lemmas_from_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr β†’ hinst_lemmas β†’ smt_tactic hinst_lemmas | [] hs := return hs | (p::ps) hs := do hs₁ ← add_hinst_lemma_from_pexpr md lhs_lemma p hs, add_hinst_lemmas_from_pexprs ps hs₁ meta def ematch_using (l : parse qexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.ematch_using hs /-- Try the given tactic, and do nothing if it fails. -/ meta def try (t : itactic) : smt_tactic unit := smt_tactic.try t /-- Keep applying the given tactic until it fails. -/ meta def repeat (t : itactic) : smt_tactic unit := smt_tactic.repeat t /-- Apply the given tactic to all remaining goals. -/ meta def all_goals (t : itactic) : smt_tactic unit := smt_tactic.all_goals t meta def induction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) : smt_tactic unit := slift (tactic.interactive.induction p rec_name ids) open tactic /-- Simplify the target type of the main goal. -/ meta def simp (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := tactic.interactive.simp hs attr_names ids [] cfg /-- Simplify the target type of the main goal using simplification lemmas and the current set of hypotheses. -/ meta def simp_using_hs (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := tactic.interactive.simp_using_hs hs attr_names ids cfg meta def simph (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := simp_using_hs hs attr_names ids cfg meta def dsimp (es : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) : smt_tactic unit := tactic.interactive.dsimp es attr_names ids [] meta def rsimp : smt_tactic unit := do ccs ← to_cc_state, rsimp.rsimplify_goal ccs meta def add_simp_lemmas : smt_tactic unit := get_hinst_lemmas_for_attr `rsimp_attr >>= add_lemmas /-- Keep applying heuristic instantiation until the current goal is solved, or it fails. -/ meta def eblast : smt_tactic unit := smt_tactic.eblast /-- Keep applying heuristic instantiation using the given lemmas until the current goal is solved, or it fails. -/ meta def eblast_using (l : parse qexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.repeat (smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close) end interactive end smt_tactic
a47eaa0829f1111e2ae9d3b2bf447529b6c12b77
1437b3495ef9020d5413178aa33c0a625f15f15f
/tactic/interactive.lean
6165b4b4b3dc0b9054f7888b6e4664bfdfd28767
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,541
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import data.dlist data.dlist.basic data.prod category.basic tactic.basic tactic.rcases tactic.generalize_proofs tactic.split_ifs logic.basic tactic.ext tactic.tauto tactic.replacer tactic.simpa tactic.squeeze open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- The `rcases` tactic is the same as `cases`, but with more flexibility in the `with` pattern syntax to allow for recursive case splitting. The pattern syntax uses the following recursive grammar: ``` patt ::= (patt_list "|")* patt_list patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩" ``` A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `βˆƒ x, βˆƒ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. `rcases` also has special support for quotient types: quotient induction into Prop works like matching on the constructor `quot.mk`. `rcases? e` will perform case splits on `e` in the same way as `rcases e`, but rather than accepting a pattern, it does a maximal cases and prints the pattern that would produce this case splitting. The default maximum depth is 5, but this can be modified with `rcases? e : n`. -/ meta def rcases : parse rcases_parse β†’ tactic unit | (p, sum.inl ids) := tactic.rcases p ids | (p, sum.inr depth) := do patt ← tactic.rcases_hint p depth, pe ← pp p, trace $ ↑"snippet: rcases " ++ pe ++ " with " ++ to_fmt patt /-- The `rintro` tactic is a combination of the `intros` tactic with `rcases` to allow for destructuring patterns while introducing variables. See `rcases` for a description of supported patterns. For example, `rintros (a | ⟨b, c⟩) ⟨d, e⟩` will introduce two variables, and then do case splits on both of them producing two subgoals, one with variables `a d e` and the other with `b c d e`. `rintro?` will introduce and case split on variables in the same way as `rintro`, but will also print the `rintro` invocation that would have the same result. Like `rcases?`, `rintro? : n` allows for modifying the depth of splitting; the default is 5. -/ meta def rintro : parse rintro_parse β†’ tactic unit | (sum.inl []) := intros [] | (sum.inl l) := tactic.rintro l | (sum.inr depth) := do ps ← tactic.rintro_hint depth, trace $ ↑"snippet: rintro" ++ format.join (ps.map $ Ξ» p, format.space ++ format.group (p.format tt)) /-- Alias for `rintro`. -/ meta def rintros := rintro /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, Ξ» s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (Ξ» h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (Β¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := Ξ» s, result.cases_on (tac s) (Ξ» a, result.success ()) (Ξ» e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end /-- Generalize proofs in the goal, naming them with the provided list. -/ meta def generalize_proofs : parse ident_* β†’ tactic unit := tactic.generalize_proofs /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ Ξ» h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (Β¬ cl), tactic.clear h /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊒ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊒ x = y` and `⊒ y = x`, while `congr' 2` produces the intended `⊒ x + y = y + x`. -/ meta def congr' : parse (with_desc "n" small_nat)? β†’ tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core >> all_goals (reflexivity <|> `[apply proof_irrel_heq] <|> `[apply proof_irrel] <|> try (congr' (nat.pred <$> o))))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊒ goal` and `f : p β†’ q`, then after `replace h := f h` the goal will be `h : q ⊒ goal`, where `have h := f h` would result in the state `h : p, h : q ⊒ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (qβ‚‚ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), Β«haveΒ» h q₁ qβ‚‚, match old, qβ‚‚ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- `apply_assumption` looks for an assumption of the form `... β†’ βˆ€ _, ... β†’ head` where `head` matches the current goal. alternatively, when encountering an assumption of the form `sgβ‚€ β†’ Β¬ sg₁`, after the main approach failed, the goal is dismissed and `sgβ‚€` and `sg₁` are made into the new goal. optional arguments: - asms: list of rules to consider instead of the local constants - tac: a tactic to run on each subgoals after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (asms : tactic (list expr) := local_context) (tac : tactic unit := return ()) : tactic unit := tactic.apply_assumption asms tac open nat meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name): tactic (list expr) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, hs ← hs.mmap i_to_expr_for_apply, l ← attr.mmap $ Ξ» a, attribute.get_instances a, let l := l.join, m ← list.mmap mk_const l, let hs := (hs ++ m).filter $ Ξ» h, expr.const_name h βˆ‰ gex, hs ← if no_dflt then return hs else do { congr_fun ← mk_const `congr_fun, congr_arg ← mk_const `congr_arg, return (congr_fun :: congr_arg :: hs) }, if Β¬ no_dflt ∨ all_hyps then do ctx ← local_context, return $ hs.append (ctx.filter (Ξ» h, h.local_uniq_name βˆ‰ hex)) -- remove local exceptions else return hs /-- `solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches and then repeatedly calls `apply_assumption` on the generated subgoals until no subgoals remain, performing at most `max_rep` recursive steps. `solve_by_elim` discharges the current goal or fails `solve_by_elim` performs back-tracking if `apply_assumption` chooses an unproductive assumption By default, the assumptions passed to apply_assumption are the local context, `congr_fun` and `congr_arg`. `solve_by_elim [h₁, hβ‚‚, ..., hα΅£]` also applies the named lemmas. `solve_by_elim with attr₁ ... attrα΅£ also applied all lemmas tagged with the specified attributes. `solve_by_elim only [h₁, hβ‚‚, ..., hα΅£]` does not include the local context, `congr_fun`, or `congr_arg` unless they are explicitly included. `solve_by_elim [-id]` removes a specified assumption. optional arguments: - discharger: a subsidiary tactic to try at each step (e.g. `cc` may be helpful) - max_rep: number of attempts at discharging generated sub-goals -/ meta def solve_by_elim (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : by_elim_opt := { }) : tactic unit := do asms ← mk_assumption_set no_dflt hs attr_names, tactic.solve_by_elim { assumptions := return asms ..opt } /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `βˆƒ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `βˆƒ _, _` until it can be discharged using `reflexivity` or `solve_by_elim` -/ meta def tautology (c : parse $ (tk "!")?) := tactic.tautology c.is_some /-- Shorter name for the tactic `tautology`. -/ meta def tauto (c : parse $ (tk "!")?) := tautology c /-- Make every propositions in the context decidable -/ meta def classical := tactic.classical private meta def generalize_arg_p_aux : pexpr β†’ parser (pexpr Γ— name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr Γ— name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux lemma {u} generalize_a_aux {Ξ± : Sort u} (h : βˆ€ x : Sort u, (Ξ± β†’ x) β†’ x) : Ξ± := h Ξ± id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if Β¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end /-- Similar to `refine` but generates equality proof obligations for every discrepancy between the goal and the type of the rule. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], congr' n, gs' ← get_goals, set_goals $ gs' ++ gs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (Ξ» e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name Γ— pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (Ξ» x, x.2 ∈ missing), exp_fields.mmap $ Ξ» ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr β†’ state_t (list $ exprΓ—structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr Γ— list (exprΓ—structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (exprΓ—structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (Ξ» f, (f.2 : name) βˆ‰ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (Ξ» f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (Ξ» x, x.2 βˆ‰ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (Ξ» (n : name Γ— name) v, do set_goals [v], try (interactive.unfold (provided.map $ Ξ» ⟨s,f⟩, f.update_prefix s) (loc.ns [none])), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr Γ— structure_instance_info β†’ tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ``` refine_struct ( { .. } : semigroup Ξ± ), -- case semigroup, mul -- Ξ± : Type u, -- ⊒ Ξ± β†’ Ξ± β†’ Ξ± -- case semigroup, mul_assoc -- Ξ± : Type u, -- ⊒ βˆ€ (a b c : Ξ±), a * b * c = a * (b * c) ``` -/ meta def refine_struct : parse texpr β†’ tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p meta def guard_hyp_nums (n : β„•) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (Ξ» x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ``` refine_struct ({ .. } : semigroup Ξ±), { have_field, ... }, { have_field, ... }, ``` behaves like ``` refine_struct ({ .. } : semigroup Ξ±), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. example, with or without user attribute: ``` @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≀ b) (h2 : c ≀ d) (h3 : 0 ≀ e) : a + c * e + a + c + 0 ≀ b + d * e + b + d + e := by apply_rules mono_rules -- any of the following lines would also work: -- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 -- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] -- by apply_rules [mono_rules] ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit := tactic.apply_rules hs n meta def return_cast (f : option expr) (t : option (expr Γ— expr)) (es : list (expr Γ— expr Γ— expr)) (e x x' eq_h : expr) : tactic (option (expr Γ— expr) Γ— list (expr Γ— expr Γ— expr)) := (do guard (Β¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> to_expr ``(@id %%(expr.sort u : expr)), t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr Γ— expr)) (es : list (expr Γ— expr Γ— expr)) : expr β†’ tactic (option (expr Γ— expr) Γ— list (expr Γ— expr Γ— expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%Ξ± %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%Ξ± %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%Ξ± %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%Ξ± %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr Γ— expr Γ— expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (Ξ» e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr β†’ parser (pexpr Γ— name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr Γ— name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. `h_generalize Hx : e == x with h` adds hypothesis `Ξ± = Ξ²` with `e : Ξ±, x : Ξ²`. `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `Ξ± = Ξ²`. `h_generalize! Hx : e == x` reverts `Hx`. when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (Ξ» ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (Ξ» ⟨h,e⟩, do h ← if h β‰  `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (Ξ» h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) /-- `choose a b h using hyp` takes an hypothesis `hyp` of the form `βˆ€ (x : X) (y : Y), βˆƒ (a : A) (b : B), P x y a b` for some `P : X β†’ Y β†’ A β†’ B β†’ Prop` and outputs into context a function `a : X β†’ Y β†’ A`, `b : X β†’ Y β†’ B` and a proposition `h` stating `βˆ€ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions. Example: ```lean example (h : βˆ€n m : β„•, βˆƒi j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := β„• β†’ β„• β†’ β„•, guard_hyp j := β„• β†’ β„• β†’ β„•, guard_hyp h := βˆ€ (n m : β„•), m = n + i n m ∨ m + j n m = n, trivial end ``` -/ meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do tgt ← match tgt with | none := get_local `this | some e := tactic.i_to_expr_strict e end, tactic.choose tgt (first :: names), try (tactic.clear tgt) meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" /-- Similar to `existsi`. `use x` will instantiate the first term of an `βˆƒ` or `Ξ£` goal with `x`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: example (Ξ± : Type) : βˆƒ S : set Ξ±, S = S := by use βˆ… example : βˆƒ x : β„€, x = x := by use 42 example : βˆƒ a b c : β„€, a + b + c = 6 := by use [1, 2, 3] example : βˆƒ p : β„€ Γ— β„€, p.1 = 1 := by use ⟨1, 42⟩ example : Ξ£ x y : β„€, (β„€ Γ— β„€) Γ— β„€ := by use [1, 2, 3, 4, 5] inductive foo | mk : β„• β†’ bool Γ— β„• β†’ β„• β†’ foo example : foo := by use [100, tt, 4, 3] -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := tactic.use l >> try triv end interactive end tactic
aebbaa008316b5707dbb88e43e24846236187d5f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/calculus/parametric_integral.lean
3d20e2e6674f22893c1e58cd58ff870fa3274b5c
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,494
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import measure_theory.integral.set_integral import analysis.calculus.mean_value /-! # Derivatives of integrals depending on parameters A parametric integral is a function with shape `f = Ξ» x : H, ∫ a : Ξ±, F x a βˆ‚ΞΌ` for some `F : H β†’ Ξ± β†’ E`, where `H` and `E` are normed spaces and `Ξ±` is a measured space with measure `ΞΌ`. We already know from `continuous_of_dominated` in `measure_theory.integral.bochner` how to guarantee that `f` is continuous using the dominated convergence theorem. In this file, we want to express the derivative of `f` as the integral of the derivative of `F` with respect to `x`. ## Main results As explained above, all results express the derivative of a parametric integral as the integral of a derivative. The variations come from the assumptions and from the different ways of expressing derivative, especially FrΓ©chet derivatives vs elementary derivative of function of one real variable. * `has_fderiv_at_of_dominated_loc_of_lip`: this version assumes `F x` is ae-measurable for x near `xβ‚€`, `F xβ‚€` is integrable, `Ξ» x, F x a` has derivative `F' a : H β†’L[ℝ] E` at `xβ‚€` which is ae-measurable, `Ξ» x, F x a` is locally Lipschitz near `xβ‚€` for almost every `a`, with a Lipschitz bound which is integrable with respect to `a`. A subtle point is that the "near xβ‚€" in the last condition has to be uniform in `a`. This is controlled by a positive number `Ξ΅`. * `has_fderiv_at_of_dominated_of_fderiv_le`: this version assume `Ξ» x, F x a` has derivative `F' x a` for `x` near `xβ‚€` and `F' x` is bounded by an integrable function independent from `x` near `xβ‚€`. `has_deriv_at_of_dominated_loc_of_lip` and `has_deriv_at_of_dominated_loc_of_deriv_le ` are versions of the above two results that assume `H = ℝ` and use the high-school derivative `deriv` instead of FrΓ©chet derivative `fderiv`. -/ noncomputable theory open topological_space measure_theory filter metric open_locale topological_space filter variables {Ξ± : Type*} [measurable_space Ξ±] {ΞΌ : measure Ξ±} {E : Type*} [normed_group E] [normed_space ℝ E] [complete_space E] [second_countable_topology E] [measurable_space E] [borel_space E] {H : Type*} [normed_group H] [normed_space ℝ H] [second_countable_topology $ H β†’L[ℝ] E] /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `xβ‚€`, assuming `F xβ‚€` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `xβ‚€` for ae `a` with integrable Lipschitz bound (with a ball radius independent of `a`), and `F x` is ae-measurable for `x` in the same ball. See `has_fderiv_at_of_dominated_loc_of_lip` for a slightly more general version. -/ lemma has_fderiv_at_of_dominated_loc_of_lip' {F : H β†’ Ξ± β†’ E} {F' : Ξ± β†’ (H β†’L[ℝ] E)} {xβ‚€ : H} {bound : Ξ± β†’ ℝ} {Ξ΅ : ℝ} (Ξ΅_pos : 0 < Ξ΅) (hF_meas : βˆ€ x ∈ ball xβ‚€ Ξ΅, ae_measurable (F x) ΞΌ) (hF_int : integrable (F xβ‚€) ΞΌ) (hF'_meas : ae_measurable F' ΞΌ) (h_lipsch : βˆ€α΅ a βˆ‚ΞΌ, lipschitz_on_with (real.nnabs $ bound a) (Ξ» x, F x a) (ball xβ‚€ Ξ΅)) (bound_integrable : integrable (bound : Ξ± β†’ ℝ) ΞΌ) (h_diff : βˆ€α΅ a βˆ‚ΞΌ, has_fderiv_at (Ξ» x, F x a) (F' a) xβ‚€) : integrable F' ΞΌ ∧ has_fderiv_at (Ξ» x, ∫ a, F x a βˆ‚ΞΌ) (∫ a, F' a βˆ‚ΞΌ) xβ‚€ := begin have xβ‚€_in : xβ‚€ ∈ ball xβ‚€ Ξ΅ := mem_ball_self Ξ΅_pos, have nneg : βˆ€ x, 0 ≀ βˆ₯x - xβ‚€βˆ₯⁻¹ := Ξ» x, inv_nonneg.mpr (norm_nonneg _) , set b : Ξ± β†’ ℝ := Ξ» a, |bound a|, have b_int : integrable b ΞΌ := bound_integrable.norm, have b_nonneg : βˆ€ a, 0 ≀ b a := Ξ» a, abs_nonneg _, have hF_int' : βˆ€ x ∈ ball xβ‚€ Ξ΅, integrable (F x) ΞΌ, { intros x x_in, have : βˆ€α΅ a βˆ‚ΞΌ, βˆ₯F xβ‚€ a - F x aβˆ₯ ≀ Ξ΅ * βˆ₯(bound a : ℝ)βˆ₯, { apply h_lipsch.mono, intros a ha, rw lipschitz_on_with_iff_norm_sub_le at ha, apply (ha xβ‚€ xβ‚€_in x x_in).trans, rw [mul_comm, real.coe_nnabs, real.norm_eq_abs], rw [mem_ball, dist_eq_norm, norm_sub_rev] at x_in, exact mul_le_mul_of_nonneg_right (le_of_lt x_in) (abs_nonneg _) }, exact integrable_of_norm_sub_le (hF_meas x x_in) hF_int (integrable.const_mul bound_integrable.norm Ξ΅) this }, have hF'_int : integrable F' ΞΌ, { have : βˆ€α΅ a βˆ‚ΞΌ, βˆ₯F' aβˆ₯ ≀ b a, { apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_diff, ha_lip⟩, exact ha_diff.le_of_lip (ball_mem_nhds _ Ξ΅_pos) ha_lip }, exact b_int.mono' hF'_meas this }, refine ⟨hF'_int, _⟩, have h_ball: ball xβ‚€ Ξ΅ ∈ 𝓝 xβ‚€ := ball_mem_nhds xβ‚€ Ξ΅_pos, have : βˆ€αΆ  x in 𝓝 xβ‚€, βˆ₯x - xβ‚€βˆ₯⁻¹ * βˆ₯∫ a, F x a βˆ‚ΞΌ - ∫ a, F xβ‚€ a βˆ‚ΞΌ - (∫ a, F' a βˆ‚ΞΌ) (x - xβ‚€)βˆ₯ = βˆ₯∫ a, βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ (F x a - F xβ‚€ a - F' a (x - xβ‚€)) βˆ‚ΞΌβˆ₯, { apply mem_of_superset (ball_mem_nhds _ Ξ΅_pos), intros x x_in, rw [set.mem_set_of_eq, ← norm_smul_of_nonneg (nneg _), integral_smul, integral_sub, integral_sub, ← continuous_linear_map.integral_apply hF'_int], exacts [hF_int' x x_in, hF_int, (hF_int' x x_in).sub hF_int, hF'_int.apply_continuous_linear_map _] }, rw [has_fderiv_at_iff_tendsto, tendsto_congr' this, ← tendsto_zero_iff_norm_tendsto_zero, ← show ∫ (a : Ξ±), βˆ₯xβ‚€ - xβ‚€βˆ₯⁻¹ β€’ (F xβ‚€ a - F xβ‚€ a - (F' a) (xβ‚€ - xβ‚€)) βˆ‚ΞΌ = 0, by simp], apply tendsto_integral_filter_of_dominated_convergence, { filter_upwards [h_ball], intros x x_in, apply ae_measurable.const_smul, exact ((hF_meas _ x_in).sub (hF_meas _ xβ‚€_in)).sub (hF'_meas.apply_continuous_linear_map _) }, { apply mem_of_superset h_ball, intros x hx, apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_deriv, ha_bound⟩, show βˆ₯βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ (F x a - F xβ‚€ a - F' a (x - xβ‚€))βˆ₯ ≀ b a + βˆ₯F' aβˆ₯, replace ha_bound : βˆ₯F x a - F xβ‚€ aβˆ₯ ≀ b a * βˆ₯x - xβ‚€βˆ₯, { rw lipschitz_on_with_iff_norm_sub_le at ha_bound, exact ha_bound _ hx _ xβ‚€_in }, calc βˆ₯βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ (F x a - F xβ‚€ a - F' a (x - xβ‚€))βˆ₯ = βˆ₯βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ (F x a - F xβ‚€ a) - βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ F' a (x - xβ‚€)βˆ₯ : by rw smul_sub ... ≀ βˆ₯βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ (F x a - F xβ‚€ a)βˆ₯ + βˆ₯βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ F' a (x - xβ‚€)βˆ₯ : norm_sub_le _ _ ... = βˆ₯x - xβ‚€βˆ₯⁻¹ * βˆ₯F x a - F xβ‚€ aβˆ₯ + βˆ₯x - xβ‚€βˆ₯⁻¹ * βˆ₯F' a (x - xβ‚€)βˆ₯ : by { rw [norm_smul_of_nonneg, norm_smul_of_nonneg] ; exact nneg _} ... ≀ βˆ₯x - xβ‚€βˆ₯⁻¹ * (b a * βˆ₯x - xβ‚€βˆ₯) + βˆ₯x - xβ‚€βˆ₯⁻¹ * (βˆ₯F' aβˆ₯ * βˆ₯x - xβ‚€βˆ₯) : add_le_add _ _ ... ≀ b a + βˆ₯F' aβˆ₯ : _, exact mul_le_mul_of_nonneg_left ha_bound (nneg _), apply mul_le_mul_of_nonneg_left ((F' a).le_op_norm _) (nneg _), by_cases h : βˆ₯x - xβ‚€βˆ₯ = 0, { simpa [h] using add_nonneg (b_nonneg a) (norm_nonneg (F' a)) }, { field_simp [h] } }, { exact b_int.add hF'_int.norm }, { apply h_diff.mono, intros a ha, suffices : tendsto (Ξ» x, βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ (F x a - F xβ‚€ a - F' a (x - xβ‚€))) (𝓝 xβ‚€) (𝓝 0), by simpa, rw tendsto_zero_iff_norm_tendsto_zero, have : (Ξ» x, βˆ₯x - xβ‚€βˆ₯⁻¹ * βˆ₯F x a - F xβ‚€ a - F' a (x - xβ‚€)βˆ₯) = Ξ» x, βˆ₯βˆ₯x - xβ‚€βˆ₯⁻¹ β€’ (F x a - F xβ‚€ a - F' a (x - xβ‚€))βˆ₯, { ext x, rw norm_smul_of_nonneg (nneg _) }, rwa [has_fderiv_at_iff_tendsto, this] at ha }, end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `xβ‚€`, assuming `F xβ‚€` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `xβ‚€` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `xβ‚€`. -/ lemma has_fderiv_at_of_dominated_loc_of_lip {F : H β†’ Ξ± β†’ E} {F' : Ξ± β†’ (H β†’L[ℝ] E)} {xβ‚€ : H} {bound : Ξ± β†’ ℝ} {Ξ΅ : ℝ} (Ξ΅_pos : 0 < Ξ΅) (hF_meas : βˆ€αΆ  x in 𝓝 xβ‚€, ae_measurable (F x) ΞΌ) (hF_int : integrable (F xβ‚€) ΞΌ) (hF'_meas : ae_measurable F' ΞΌ) (h_lip : βˆ€α΅ a βˆ‚ΞΌ, lipschitz_on_with (real.nnabs $ bound a) (Ξ» x, F x a) (ball xβ‚€ Ξ΅)) (bound_integrable : integrable (bound : Ξ± β†’ ℝ) ΞΌ) (h_diff : βˆ€α΅ a βˆ‚ΞΌ, has_fderiv_at (Ξ» x, F x a) (F' a) xβ‚€) : integrable F' ΞΌ ∧ has_fderiv_at (Ξ» x, ∫ a, F x a βˆ‚ΞΌ) (∫ a, F' a βˆ‚ΞΌ) xβ‚€ := begin obtain ⟨Ρ', Ξ΅'_pos, h'⟩ : βˆƒ Ξ΅' > 0, βˆ€ x ∈ ball xβ‚€ Ξ΅', ae_measurable (F x) ΞΌ, by simpa using nhds_basis_ball.eventually_iff.mp hF_meas, set Ξ΄ := min Ξ΅ Ξ΅', have Ξ΄_pos : 0 < Ξ΄ := lt_min Ξ΅_pos Ξ΅'_pos, replace h' : βˆ€ x, x ∈ ball xβ‚€ Ξ΄ β†’ ae_measurable (F x) ΞΌ, { intros x x_in, exact h' _ (ball_subset_ball (min_le_right Ξ΅ Ξ΅') x_in) }, replace h_lip : βˆ€α΅ (a : Ξ±) βˆ‚ΞΌ, lipschitz_on_with (real.nnabs $ bound a) (Ξ» x, F x a) (ball xβ‚€ Ξ΄), { apply h_lip.mono, intros a lip, exact lip.mono (ball_subset_ball $ min_le_left Ξ΅ Ξ΅') }, apply has_fderiv_at_of_dominated_loc_of_lip' Ξ΄_pos ; assumption end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `xβ‚€`, assuming `F xβ‚€` is integrable, `x ↦ F x a` is differentiable on a ball around `xβ‚€` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `xβ‚€`. -/ lemma has_fderiv_at_of_dominated_of_fderiv_le {F : H β†’ Ξ± β†’ E} {F' : H β†’ Ξ± β†’ (H β†’L[ℝ] E)} {xβ‚€ : H} {bound : Ξ± β†’ ℝ} {Ξ΅ : ℝ} (Ξ΅_pos : 0 < Ξ΅) (hF_meas : βˆ€αΆ  x in 𝓝 xβ‚€, ae_measurable (F x) ΞΌ) (hF_int : integrable (F xβ‚€) ΞΌ) (hF'_meas : ae_measurable (F' xβ‚€) ΞΌ) (h_bound : βˆ€α΅ a βˆ‚ΞΌ, βˆ€ x ∈ ball xβ‚€ Ξ΅, βˆ₯F' x aβˆ₯ ≀ bound a) (bound_integrable : integrable (bound : Ξ± β†’ ℝ) ΞΌ) (h_diff : βˆ€α΅ a βˆ‚ΞΌ, βˆ€ x ∈ ball xβ‚€ Ξ΅, has_fderiv_at (Ξ» x, F x a) (F' x a) x) : has_fderiv_at (Ξ» x, ∫ a, F x a βˆ‚ΞΌ) (∫ a, F' xβ‚€ a βˆ‚ΞΌ) xβ‚€ := begin have xβ‚€_in : xβ‚€ ∈ ball xβ‚€ Ξ΅ := mem_ball_self Ξ΅_pos, have diff_xβ‚€ : βˆ€α΅ a βˆ‚ΞΌ, has_fderiv_at (Ξ» x, F x a) (F' xβ‚€ a) xβ‚€ := h_diff.mono (Ξ» a ha, ha xβ‚€ xβ‚€_in), have : βˆ€α΅ a βˆ‚ΞΌ, lipschitz_on_with (real.nnabs (bound a)) (Ξ» x, F x a) (ball xβ‚€ Ξ΅), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (Ξ» x x_in, (ha_deriv x x_in).has_fderiv_within_at) (Ξ» x x_in, _), rw [← nnreal.coe_le_coe, coe_nnnorm, real.coe_nnabs], exact (ha_bound x x_in).trans (le_abs_self _) }, exact (has_fderiv_at_of_dominated_loc_of_lip Ξ΅_pos hF_meas hF_int hF'_meas this bound_integrable diff_xβ‚€).2 end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `xβ‚€ : ℝ`, assuming `F xβ‚€` is integrable, `x ↦ F x a` is locally Lipschitz on an interval around `xβ‚€` for ae `a` (with interval radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `xβ‚€`. -/ lemma has_deriv_at_of_dominated_loc_of_lip {F : ℝ β†’ Ξ± β†’ E} {F' : Ξ± β†’ E} {xβ‚€ : ℝ} {Ξ΅ : ℝ} (Ξ΅_pos : 0 < Ξ΅) (hF_meas : βˆ€αΆ  x in 𝓝 xβ‚€, ae_measurable (F x) ΞΌ) (hF_int : integrable (F xβ‚€) ΞΌ) (hF'_meas : ae_measurable F' ΞΌ) {bound : Ξ± β†’ ℝ} (h_lipsch : βˆ€α΅ a βˆ‚ΞΌ, lipschitz_on_with (real.nnabs $ bound a) (Ξ» x, F x a) (ball xβ‚€ Ξ΅)) (bound_integrable : integrable (bound : Ξ± β†’ ℝ) ΞΌ) (h_diff : βˆ€α΅ a βˆ‚ΞΌ, has_deriv_at (Ξ» x, F x a) (F' a) xβ‚€) : (integrable F' ΞΌ) ∧ has_deriv_at (Ξ» x, ∫ a, F x a βˆ‚ΞΌ) (∫ a, F' a βˆ‚ΞΌ) xβ‚€ := begin have hm := (continuous_linear_map.smul_rightL ℝ ℝ E 1).continuous.measurable.comp_ae_measurable hF'_meas, cases has_fderiv_at_of_dominated_loc_of_lip Ξ΅_pos hF_meas hF_int hm h_lipsch bound_integrable h_diff with hF'_int key, replace hF'_int : integrable F' ΞΌ, { rw [← integrable_norm_iff hm] at hF'_int, simpa only [integrable_norm_iff, hF'_meas, one_mul, norm_one, continuous_linear_map.norm_smul_rightL_apply] using hF'_int}, refine ⟨hF'_int, _⟩, simp_rw has_deriv_at_iff_has_fderiv_at at h_diff ⊒, rwa continuous_linear_map.integral_comp_comm _ hF'_int at key, all_goals { apply_instance, }, end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `xβ‚€ : ℝ`, assuming `F xβ‚€` is integrable, `x ↦ F x a` is differentiable on an interval around `xβ‚€` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `xβ‚€`. -/ lemma has_deriv_at_of_dominated_loc_of_deriv_le {F : ℝ β†’ Ξ± β†’ E} {F' : ℝ β†’ Ξ± β†’ E} {xβ‚€ : ℝ} {Ξ΅ : ℝ} (Ξ΅_pos : 0 < Ξ΅) (hF_meas : βˆ€αΆ  x in 𝓝 xβ‚€, ae_measurable (F x) ΞΌ) (hF_int : integrable (F xβ‚€) ΞΌ) (hF'_meas : ae_measurable (F' xβ‚€) ΞΌ) {bound : Ξ± β†’ ℝ} (h_bound : βˆ€α΅ a βˆ‚ΞΌ, βˆ€ x ∈ ball xβ‚€ Ξ΅, βˆ₯F' x aβˆ₯ ≀ bound a) (bound_integrable : integrable bound ΞΌ) (h_diff : βˆ€α΅ a βˆ‚ΞΌ, βˆ€ x ∈ ball xβ‚€ Ξ΅, has_deriv_at (Ξ» x, F x a) (F' x a) x) : (integrable (F' xβ‚€) ΞΌ) ∧ has_deriv_at (Ξ»n, ∫ a, F n a βˆ‚ΞΌ) (∫ a, F' xβ‚€ a βˆ‚ΞΌ) xβ‚€ := begin have xβ‚€_in : xβ‚€ ∈ ball xβ‚€ Ξ΅ := mem_ball_self Ξ΅_pos, have diff_xβ‚€ : βˆ€α΅ a βˆ‚ΞΌ, has_deriv_at (Ξ» x, F x a) (F' xβ‚€ a) xβ‚€ := h_diff.mono (Ξ» a ha, ha xβ‚€ xβ‚€_in), have : βˆ€α΅ a βˆ‚ΞΌ, lipschitz_on_with (real.nnabs (bound a)) (Ξ» (x : ℝ), F x a) (ball xβ‚€ Ξ΅), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_deriv_within_le (Ξ» x x_in, (ha_deriv x x_in).has_deriv_within_at) (Ξ» x x_in, _), rw [← nnreal.coe_le_coe, coe_nnnorm, real.coe_nnabs], exact (ha_bound x x_in).trans (le_abs_self _) }, exact has_deriv_at_of_dominated_loc_of_lip Ξ΅_pos hF_meas hF_int hF'_meas this bound_integrable diff_xβ‚€ end
56812c3341bb901deb2c62c126d8339f25b65267
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/withLocationImplementationDetails.lean
96d04eb46942b137e65a19eb6eb679864380880f
[ "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
119
lean
axiom A : Nat axiom B : Nat axiom equality : A = B example : A = 3 -> B = 3 := by intro h rewrite [equality] at *
3e06ca38713316c04064c1369a0fe9d8fb11da37
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/match_pattern2.lean
a5a53bed3bc19c685bee73900c9c86dcaf921198
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
1,418
lean
open tactic list expr private meta definition pattern_telescope : expr β†’ list expr β†’ tactic (list expr Γ— expr Γ— expr) | e ps := if expr.is_pi e = tt then do n ← mk_fresh_name, p ← return $ local_const n (binding_name e) (binding_info e) (binding_domain e), new_e ← return $ instantiate_var (binding_body e) p, pattern_telescope new_e (p :: ps) else do (lhs, rhs) ← match_eq e, return (reverse ps, lhs, rhs) meta definition mk_pattern_for_constant : name β†’ tactic pattern | n := do env ← get_env, d : declaration ← returnex $ environment.get env n, ls : list level ← return $ map level.param (declaration.univ_params d), (some type) ← return $ declaration.instantiate_type_univ_params d ls | failed, (es, lhs, rhs) ← pattern_telescope type [], p : pattern ← mk_pattern ls es lhs [] [rhs, app_of_list (expr.const n ls) es], return p open nat constant add.comm (a b : nat) : a + b = b + a example (a b : nat) (H : a + b + a + b = 0) : true := by do a ← get_local `a, b ← get_local `b, H ← get_local `H >>= infer_type, (lhs, rhs) ← match_eq H, p ← mk_pattern_for_constant $ `add.comm, [rhs_inst, prf] ← match_pattern p lhs | failed, trace "match rhs", trace rhs_inst, trace "proof lhs = rhs", trace prf, prf_type ← infer_type prf, trace "proof type:", trace prf_type, constructor
bc9f20760eba2619a0d59c37c4b121dd8bd44f51
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/data/vector.lean
d09a98260aa5a7f43bbf7837a95570a7b862a7bd
[ "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
3,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 Ξ± (succ n) β†’ vector Ξ± n | ⟨ [], h ⟩ := by contradiction | ⟨ a :: v, h ⟩ := ⟨ v, congr_arg pred h ⟩ theorem tail_cons (a : Ξ±) : Ξ  (v : vector Ξ± n), tail (a :: v) = v | ⟨ l, h ⟩ := rfl def to_list : vector Ξ± n β†’ list Ξ± | ⟨ l, h ⟩ := l def append {n m : nat} : vector Ξ± n β†’ vector Ξ± m β†’ vector Ξ± (n + m) | ⟨ l₁, h₁ ⟩ ⟨ lβ‚‚, hβ‚‚ ⟩ := ⟨ l₁ ++ lβ‚‚, by simp_using_hs ⟩ /- 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 ⟩ 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⟩ ⟨.x, h2⟩ rfl := rfl @[simp] lemma to_list_nil : to_list [] = @list.nil Ξ± := rfl @[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
262c4184fded3570406ba745229c70c6e9becf2d
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/functor_category.lean
cbafd2c3d1fcc0488270c4695f756c0b9ecc13a6
[ "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
10,661
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.preserves.limits open category_theory category_theory.category namespace category_theory.limits universes v vβ‚‚ u -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u} [category.{v} C] variables {J K : Type v} [small_category J] [category.{vβ‚‚} K] @[simp, reassoc] lemma limit.lift_Ο€_app (H : J β₯€ K β₯€ C) [has_limit H] (c : cone H) (j : J) (k : K) : (limit.lift H c).app k ≫ (limit.Ο€ H j).app k = (c.Ο€.app j).app k := congr_app (limit.lift_Ο€ c j) k @[simp, reassoc] lemma colimit.ΞΉ_desc_app (H : J β₯€ K β₯€ C) [has_colimit H] (c : cocone H) (j : J) (k : K) : (colimit.ΞΉ H j).app k ≫ (colimit.desc H c).app k = (c.ΞΉ.app j).app k := congr_app (colimit.ΞΉ_desc c j) k /-- The evaluation functors jointly reflect limits: that is, to show a cone is a limit of `F` it suffices to show that each evaluation cone is a limit. In other words, to prove a cone is limiting you can show it's pointwise limiting. -/ def evaluation_jointly_reflects_limits {F : J β₯€ K β₯€ C} (c : cone F) (t : Ξ  (k : K), is_limit (((evaluation K C).obj k).map_cone c)) : is_limit c := { lift := Ξ» s, { app := Ξ» k, (t k).lift ⟨s.X.obj k, whisker_right s.Ο€ ((evaluation K C).obj k)⟩, naturality' := Ξ» X Y f, (t Y).hom_ext $ Ξ» j, begin rw [assoc, (t Y).fac _ j], simpa using ((t X).fac_assoc ⟨s.X.obj X, whisker_right s.Ο€ ((evaluation K C).obj X)⟩ j _).symm, end }, fac' := Ξ» s j, nat_trans.ext _ _ $ funext $ Ξ» k, (t k).fac _ j, uniq' := Ξ» s m w, nat_trans.ext _ _ $ funext $ Ξ» x, (t x).hom_ext $ Ξ» j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.Ο€ ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of limit cones for each diagram `X ↦ F X k`, we can stitch them together to give a cone for the diagram `F`. `combined_is_limit` shows that the new cone is limiting, and `eval_combined` shows it is (essentially) made up of the original cones. -/ @[simps] def combine_cones (F : J β₯€ K β₯€ C) (c : Ξ  (k : K), limit_cone (F.flip.obj k)) : cone F := { X := { obj := Ξ» k, (c k).cone.X, map := Ξ» k₁ kβ‚‚ f, (c kβ‚‚).is_limit.lift ⟨_, (c k₁).cone.Ο€ ≫ F.flip.map f⟩, map_id' := Ξ» k, (c k).is_limit.hom_ext (Ξ» j, by { dsimp, simp }), map_comp' := Ξ» k₁ kβ‚‚ k₃ f₁ fβ‚‚, (c k₃).is_limit.hom_ext (Ξ» j, by simp) }, Ο€ := { app := Ξ» j, { app := Ξ» k, (c k).cone.Ο€.app j }, naturality' := Ξ» j₁ jβ‚‚ g, nat_trans.ext _ _ $ funext $ Ξ» k, (c k).cone.Ο€.naturality g } } /-- The stitched together cones each project down to the original given cones (up to iso). -/ def evaluate_combined_cones (F : J β₯€ K β₯€ C) (c : Ξ  (k : K), limit_cone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cone (combine_cones F c) β‰… (c k).cone := cones.ext (iso.refl _) (by tidy) /-- Stitching together limiting cones gives a limiting cone. -/ def combined_is_limit (F : J β₯€ K β₯€ C) (c : Ξ  (k : K), limit_cone (F.flip.obj k)) : is_limit (combine_cones F c) := evaluation_jointly_reflects_limits _ (Ξ» k, (c k).is_limit.of_iso_limit (evaluate_combined_cones F c k).symm) /-- The evaluation functors jointly reflect colimits: that is, to show a cocone is a colimit of `F` it suffices to show that each evaluation cocone is a colimit. In other words, to prove a cocone is colimiting you can show it's pointwise colimiting. -/ def evaluation_jointly_reflects_colimits {F : J β₯€ K β₯€ C} (c : cocone F) (t : Ξ  (k : K), is_colimit (((evaluation K C).obj k).map_cocone c)) : is_colimit c := { desc := Ξ» s, { app := Ξ» k, (t k).desc ⟨s.X.obj k, whisker_right s.ΞΉ ((evaluation K C).obj k)⟩, naturality' := Ξ» X Y f, (t X).hom_ext $ Ξ» j, begin rw [(t X).fac_assoc _ j], erw ← (c.ΞΉ.app j).naturality_assoc f, erw (t Y).fac ⟨s.X.obj _, whisker_right s.ΞΉ _⟩ j, dsimp, simp, end }, fac' := Ξ» s j, nat_trans.ext _ _ $ funext $ Ξ» k, (t k).fac _ j, uniq' := Ξ» s m w, nat_trans.ext _ _ $ funext $ Ξ» x, (t x).hom_ext $ Ξ» j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.ΞΉ ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of colimit cocones for each diagram `X ↦ F X k`, we can stitch them together to give a cocone for the diagram `F`. `combined_is_colimit` shows that the new cocone is colimiting, and `eval_combined` shows it is (essentially) made up of the original cocones. -/ @[simps] def combine_cocones (F : J β₯€ K β₯€ C) (c : Ξ  (k : K), colimit_cocone (F.flip.obj k)) : cocone F := { X := { obj := Ξ» k, (c k).cocone.X, map := Ξ» k₁ kβ‚‚ f, (c k₁).is_colimit.desc ⟨_, F.flip.map f ≫ (c kβ‚‚).cocone.ι⟩, map_id' := Ξ» k, (c k).is_colimit.hom_ext (Ξ» j, by { dsimp, simp }), map_comp' := Ξ» k₁ kβ‚‚ k₃ f₁ fβ‚‚, (c k₁).is_colimit.hom_ext (Ξ» j, by simp) }, ΞΉ := { app := Ξ» j, { app := Ξ» k, (c k).cocone.ΞΉ.app j }, naturality' := Ξ» j₁ jβ‚‚ g, nat_trans.ext _ _ $ funext $ Ξ» k, (c k).cocone.ΞΉ.naturality g } } /-- The stitched together cocones each project down to the original given cocones (up to iso). -/ def evaluate_combined_cocones (F : J β₯€ K β₯€ C) (c : Ξ  (k : K), colimit_cocone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cocone (combine_cocones F c) β‰… (c k).cocone := cocones.ext (iso.refl _) (by tidy) /-- Stitching together colimiting cocones gives a colimiting cocone. -/ def combined_is_colimit (F : J β₯€ K β₯€ C) (c : Ξ  (k : K), colimit_cocone (F.flip.obj k)) : is_colimit (combine_cocones F c) := evaluation_jointly_reflects_colimits _ (Ξ» k, (c k).is_colimit.of_iso_colimit (evaluate_combined_cocones F c k).symm) noncomputable theory instance functor_category_has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (K β₯€ C) := { has_limit := Ξ» F, has_limit.mk { cone := combine_cones F (Ξ» k, get_limit_cone _), is_limit := combined_is_limit _ _ } } instance functor_category_has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (K β₯€ C) := { has_colimit := Ξ» F, has_colimit.mk { cocone := combine_cocones _ (Ξ» k, get_colimit_cocone _), is_colimit := combined_is_colimit _ _ } } instance functor_category_has_limits [has_limits C] : has_limits (K β₯€ C) := { has_limits_of_shape := Ξ» J π’₯, by resetI; apply_instance } instance functor_category_has_colimits [has_colimits C] : has_colimits (K β₯€ C) := { has_colimits_of_shape := Ξ» J π’₯, by resetI; apply_instance } instance evaluation_preserves_limits_of_shape [has_limits_of_shape J C] (k : K) : preserves_limits_of_shape J ((evaluation K C).obj k) := { preserves_limit := Ξ» F, preserves_limit_of_preserves_limit_cone (combined_is_limit _ _) $ is_limit.of_iso_limit (limit.is_limit _) (evaluate_combined_cones F _ k).symm } /-- If `F : J β₯€ K β₯€ C` is a functor into a functor category which has a limit, then the evaluation of that limit at `k` is the limit of the evaluations of `F.obj j` at `k`. -/ def limit_obj_iso_limit_comp_evaluation [has_limits_of_shape J C] (F : J β₯€ K β₯€ C) (k : K) : (limit F).obj k β‰… limit (F β‹™ ((evaluation K C).obj k)) := preserves_limit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_hom_Ο€ [has_limits_of_shape J C] (F : J β₯€ (K β₯€ C)) (j : J) (k : K) : (limit_obj_iso_limit_comp_evaluation F k).hom ≫ limit.Ο€ (F β‹™ ((evaluation K C).obj k)) j = (limit.Ο€ F j).app k := begin dsimp [limit_obj_iso_limit_comp_evaluation], simp, end @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_inv_Ο€_app [has_limits_of_shape J C] (F : J β₯€ (K β₯€ C)) (j : J) (k : K): (limit_obj_iso_limit_comp_evaluation F k).inv ≫ (limit.Ο€ F j).app k = limit.Ο€ (F β‹™ ((evaluation K C).obj k)) j := begin dsimp [limit_obj_iso_limit_comp_evaluation], rw iso.inv_comp_eq, simp, end @[ext] lemma limit_obj_ext {H : J β₯€ K β₯€ C} [has_limits_of_shape J C] {k : K} {W : C} {f g : W ⟢ (limit H).obj k} (w : βˆ€ j, f ≫ (limits.limit.Ο€ H j).app k = g ≫ (limits.limit.Ο€ H j).app k) : f = g := begin apply (cancel_mono (limit_obj_iso_limit_comp_evaluation H k).hom).1, ext, simpa using w j, end instance evaluation_preserves_colimits_of_shape [has_colimits_of_shape J C] (k : K) : preserves_colimits_of_shape J ((evaluation K C).obj k) := { preserves_colimit := Ξ» F, preserves_colimit_of_preserves_colimit_cocone (combined_is_colimit _ _) $ is_colimit.of_iso_colimit (colimit.is_colimit _) (evaluate_combined_cocones F _ k).symm } /-- If `F : J β₯€ K β₯€ C` is a functor into a functor category which has a colimit, then the evaluation of that colimit at `k` is the colimit of the evaluations of `F.obj j` at `k`. -/ def colimit_obj_iso_colimit_comp_evaluation [has_colimits_of_shape J C] (F : J β₯€ K β₯€ C) (k : K) : (colimit F).obj k β‰… colimit (F β‹™ ((evaluation K C).obj k)) := preserves_colimit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ΞΉ_inv [has_colimits_of_shape J C] (F : J β₯€ (K β₯€ C)) (j : J) (k : K) : colimit.ΞΉ (F β‹™ ((evaluation K C).obj k)) j ≫ (colimit_obj_iso_colimit_comp_evaluation F k).inv = (colimit.ΞΉ F j).app k := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], simp, end @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ΞΉ_app_hom [has_colimits_of_shape J C] (F : J β₯€ (K β₯€ C)) (j : J) (k : K) : (colimit.ΞΉ F j).app k ≫ (colimit_obj_iso_colimit_comp_evaluation F k).hom = colimit.ΞΉ (F β‹™ ((evaluation K C).obj k)) j := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], rw ←iso.eq_comp_inv, simp, end @[ext] lemma colimit_obj_ext {H : J β₯€ K β₯€ C} [has_colimits_of_shape J C] {k : K} {W : C} {f g : (colimit H).obj k ⟢ W} (w : βˆ€ j, (colimit.ΞΉ H j).app k ≫ f = (colimit.ΞΉ H j).app k ≫ g) : f = g := begin apply (cancel_epi (colimit_obj_iso_colimit_comp_evaluation H k).inv).1, ext, simpa using w j, end instance evaluation_preserves_limits [has_limits C] (k : K) : preserves_limits ((evaluation K C).obj k) := { preserves_limits_of_shape := Ξ» J π’₯, by resetI; apply_instance } instance evaluation_preserves_colimits [has_colimits C] (k : K) : preserves_colimits ((evaluation K C).obj k) := { preserves_colimits_of_shape := Ξ» J π’₯, by resetI; apply_instance } end category_theory.limits
cc0d8df4ad37f1a85461390631c4fc8817f0c6b1
0ddf2dd8409bcb923d11603846800bd9699616ea
/category.lean
64bc6d4ed784092b8ceb2ef84a334dc94ac1bf7e
[]
no_license
tounaishouta/Lean
0cbaaa9340e7f8f884504ea170243e07a54f0566
1d75311f5506ca2bfd8b7ccec0b7d70c3319d555
refs/heads/master
1,610,229,383,935
1,459,950,226,000
1,459,950,226,000
50,836,185
0
0
null
null
null
null
UTF-8
Lean
false
false
7,945
lean
import standard namespace category structure Category : Type := (Ob : Type) (Hom : Ob β†’ Ob β†’ Type) (comp : Ξ  {x y z : Ob}, Hom y z β†’ Hom x y β†’ Hom x z) (id : Ξ  x : Ob, Hom x x) (comp_assoc : βˆ€ {x y z w : Ob} {f : Hom x y} {g : Hom y z} {h : Hom z w}, comp (comp h g) f = comp h (comp g f)) (comp_id : βˆ€ {x y : Ob} {f : Hom x y}, comp f (id x) = f) (id_comp : βˆ€ {x y : Ob} {f : Hom x y}, comp (id y) f = f) attribute Category.Ob [coercion] -- attribute Category.Hom [coercion] -- δΈŠζ‰‹γγ„γ‹γͺい open Category (Hom) infixr ` ∘ ` := Category.comp _ notation 1 := Category.id _ _ definition op [reducible] (C : Category) : Category := ⦃ Category, Ob := C, Hom := take x y, Hom C y x, comp := take x y z g f, Category.comp C f g, id := take x, Category.id C x, comp_assoc := take x y z w f g h, eq.symm (Category.comp_assoc C), comp_id := take x y f, Category.id_comp C, id_comp := take x y f, Category.comp_id C ⦄ prefix `-` := op open prod (pr1 pr2) definition prod [reducible] (C D : Category) : Category := ⦃ Category, Ob := C Γ— D, Hom := take x y, Hom C (pr1 x) (pr1 y) Γ— Hom D (pr2 x) (pr2 y), comp := take x y z g f, (pr1 g ∘ pr1 f, pr2 g ∘ pr2 f), id := take x, (1, 1), comp_assoc := take x y z w h g f, prod.eq (Category.comp_assoc C) (Category.comp_assoc D), comp_id := take x y f, prod.eq (Category.comp_id C) (Category.comp_id D), id_comp := take x y f, prod.eq (Category.id_comp C) (Category.id_comp D) ⦄ infix ` Γ— ` := prod definition Type_ [reducible] : Category := ⦃ Category, Ob := Type, Hom := take x y, x β†’ y, comp := take x y z g f a, g (f a), id := take x a, a, comp_assoc := take x y z w f g h, rfl, comp_id := take x y f, rfl, id_comp := take x y f, rfl ⦄ structure Functor (C D : Category) : Type := (ob : C β†’ D) (hom : Ξ  {x y : C}, Hom C x y β†’ Hom D (ob x) (ob y)) (resp_comp : βˆ€ {x y z : C} {f : Hom C x y} {g : Hom C y z}, hom (g ∘ f) = hom g ∘ hom f) (resp_id : βˆ€ {x : C}, hom (1 : Hom C x x) = (1 : Hom D (ob x) (ob x))) attribute Functor.ob [coercion] attribute Functor.hom [coercion] definition HomFunc [reducible] (C : Category) : Functor (-C Γ— C) Type_ := ⦃ Functor (-C Γ— C) Type_, ob := take x, Hom C (pr1 x) (pr2 x), hom := take x y f a, pr2 f ∘ a ∘ pr1 f, resp_comp := take x y z f g, funext (take a, by unfold [op, prod, Type_]; rewrite +Category.comp_assoc), resp_id := take x, funext (take a, by unfold [op, prod, Type_]; rewrite [Category.comp_id, Category.id_comp]) ⦄ definition Cat [reducible] : Category := ⦃ Category, Ob := Category, Hom := Functor, comp := take C D E G F, proof ⦃ Functor C E, ob := take x, G (F x), hom := take x y f, G (F f), resp_comp := take x y z g f, by rewrite 2 Functor.resp_comp, resp_id := take x, by rewrite 2 Functor.resp_id ⦄ qed, id := take C, proof ⦃ Functor C C, ob := take x, x, hom := take x y f, f, resp_comp := take x y z g f, rfl, resp_id := take x, rfl ⦄ qed, comp_assoc := take A B C D F G H, rfl, comp_id := take C D F, by cases F; reflexivity, id_comp := take C D F, by cases F; reflexivity ⦄ structure NatTrans {C D : Category} (F G : Functor C D) : Type := (trans : Ξ  x : C, Hom D (F x) (G x)) (comm : βˆ€ (x y : C) (f : Hom C x y), G f ∘ trans x = trans y ∘ F f) attribute NatTrans.trans [coercion] theorem NatTrans.eq {C D : Category} {F G : Functor C D} {ΞΎ Ξ· : NatTrans F G} : (βˆ€ x : C, ΞΎ x = Ξ· x) β†’ ΞΎ = Ξ· := begin cases ΞΎ, cases Ξ·, intro H, congruence, apply funext, exact H end definition Func (C D : Category) : Category := ⦃ Category, Ob := Functor C D, Hom := NatTrans, comp := take F G H Ξ· ΞΎ, proof ⦃ NatTrans F H, trans := take x, Ξ· x ∘ ΞΎ x, comm := take x y f, by rewrite [ -Category.comp_assoc, NatTrans.comm, Category.comp_assoc, NatTrans.comm, -Category.comp_assoc ] ⦄ qed, id := take F, proof ⦃ NatTrans F F, trans := take x, 1, comm := take x y f, by rewrite [Category.comp_id, Category.id_comp] ⦄ qed, comp_assoc := take F G H K ΞΎ Ξ· ΞΆ, NatTrans.eq (take x, by rewrite [β–Έ*, Category.comp_assoc]), comp_id := take F G ΞΎ, NatTrans.eq (take x, by rewrite [β–Έ*, Category.comp_id]), id_comp := take F G ΞΎ, NatTrans.eq (take x, by rewrite [β–Έ*, Category.id_comp]) ⦄ definition adj_ob [reducible] {C D E : Category} (F : Functor (C Γ— D) E) (x' : D) : Functor C E := ⦃ Functor C E, ob := take x, F (x, x'), hom := take x y f, F (f, 1), resp_comp := take x y z f g, by rewrite [-Functor.resp_comp, ↑prod, Category.comp_id], resp_id := take x, by rewrite -Functor.resp_id ⦄ definition adj_hom [reducible] {C D E : Category} (F : Functor (C Γ— D) E) {x' y' : D} (f' : Hom D x' y') : NatTrans (adj_ob F x') (adj_ob F y') := ⦃ NatTrans (adj_ob F x') (adj_ob F y'), trans := take x, F (1, f'), comm := take x y f, begin unfold adj_ob, rewrite -2 Functor.resp_comp, unfold prod, rewrite [2 Category.comp_id, 2 Category.id_comp] end ⦄ definition adj [reducible] {C D E : Category} (F : Functor (C Γ— D) E) : Functor D (Func C E) := ⦃ Functor D (Func C E), ob := adj_ob F, hom := @(adj_hom F), resp_comp := take x' y' z' f' g', NatTrans.eq (take x, begin unfold [adj_hom, Func], rewrite -Functor.resp_comp, unfold prod, rewrite Category.comp_id end), resp_id := take x', NatTrans.eq (take x, begin unfold [adj_hom, Func], rewrite -Functor.resp_id end) ⦄ definition Yoneda [reducible] (C : Category) : Functor C (Func (-C) Type_) := adj (HomFunc C) definition Y_ob [reducible] (C : Category) (x : C) : Functor (-C) Type_ := Yoneda C x definition Y_hom [reducible] (C : Category) {x y : C} (f : Hom C x y) : NatTrans (Y_ob C x) (Y_ob C y) := Yoneda C f theorem Y_ob_ob {C : Category} {a x : C} : Y_ob C x a = Hom C a x := rfl theorem Y_ob_hom {C : Category} {a b x : C} {f : Hom C a b} {g : Hom C b x} : Y_ob C x f g = g ∘ f := begin unfold [Y_ob, Yoneda, adj, adj_ob, HomFunc], rewrite Category.id_comp end theorem Y_hom_ob {C : Category} {a x y : C} {f : Hom C a x} {g : Hom C x y} : Y_hom C g a f = g ∘ f := begin unfold [Y_hom, Yoneda, adj, adj_hom, HomFunc, op], rewrite Category.comp_id end definition bijective {X Y : Type} (f : X β†’ Y) : Prop := βˆƒ g : Y β†’ X, (βˆ€ x : X, g (f x) = x) ∧ (βˆ€ y : Y, f (g y) = y) definition fully_faithful {C D : Category} (F : Functor C D) : Prop := βˆ€ {x y : C}, bijective (take f : Hom C x y, F f) theorem Yoneda_lemma {C : Category} : fully_faithful (Yoneda C) := begin unfold [fully_faithful, bijective], intro x y, existsi take ΞΎ : NatTrans (Yoneda C x) (Yoneda C y), ΞΎ x 1, split, { intro f, unfold [Yoneda, adj, adj_hom, HomFunc, op], rewrite 2 Category.comp_id }, { show βˆ€ ΞΎ : NatTrans (Y_ob C x) (Y_ob C y), Y_hom C (ΞΎ x 1) = ΞΎ, from take ΞΎ : NatTrans (Y_ob C x) (Y_ob C y), NatTrans.eq (take a : C, funext (take f: Hom C a x, begin rewrite Y_hom_ob, rewrite -Y_ob_hom, transitivity (Y_ob C y f ∘ ΞΎ x) 1, { reflexivity }, { rewrite [NatTrans.comm, ↑Type_, Y_ob_hom, Category.id_comp] } end)) } end end category
d8834230cca1915659446ac51f99974b3211ef58
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/tensor_product.lean
fe3a5edcf8001b53cd4a4e67fbd28035922f1eb5
[ "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
39,076
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin -/ import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import linear_algebra.direct_sum.finsupp /-! # The tensor product of R-algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `R` be a (semi)ring and `A` an `R`-algebra. In this file we: - Define the `A`-module structure on `A βŠ— M`, for an `R`-module `M`. - Define the `R`-algebra structure on `A βŠ— B`, for another `R`-algebra `B`. and provide the structure isomorphisms * `R βŠ—[R] A ≃ₐ[R] A` * `A βŠ—[R] R ≃ₐ[R] A` * `A βŠ—[R] B ≃ₐ[R] B βŠ—[R] A` * `((A βŠ—[R] B) βŠ—[R] C) ≃ₐ[R] (A βŠ—[R] (B βŠ—[R] C))` ## Main declaration - `linear_map.base_change A f` is the `A`-linear map `A βŠ— f`, for an `R`-linear map `f`. ## Implementation notes The heterobasic definitions below such as: * `tensor_product.algebra_tensor_module.curry` * `tensor_product.algebra_tensor_module.uncurry` * `tensor_product.algebra_tensor_module.lcurry` * `tensor_product.algebra_tensor_module.lift` * `tensor_product.algebra_tensor_module.lift.equiv` * `tensor_product.algebra_tensor_module.mk` * `tensor_product.algebra_tensor_module.assoc` are just more general versions of the definitions already in `linear_algebra/tensor_product`. We could thus consider replacing the less general definitions with these ones. If we do this, we probably should still implement the less general ones as abbreviations to the more general ones with fewer type arguments. -/ universes u v₁ vβ‚‚ v₃ vβ‚„ open_locale tensor_product open tensor_product namespace tensor_product variables {R A M N P : Type*} /-! ### The `A`-module structure on `A βŠ—[R] M` -/ open linear_map open algebra (lsmul) namespace algebra_tensor_module section semiring variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables [add_comm_monoid N] [module R N] variables [add_comm_monoid P] [module R P] [module A P] [is_scalar_tower R A P] lemma smul_eq_lsmul_rtensor (a : A) (x : M βŠ—[R] N) : a β€’ x = (lsmul R M a).rtensor N x := rfl /-- Heterobasic version of `tensor_product.curry`: Given a linear map `M βŠ—[R] N β†’[A] P`, compose it with the canonical bilinear map `M β†’[A] N β†’[R] M βŠ—[R] N` to form a bilinear map `M β†’[A] N β†’[R] P`. -/ @[simps] def curry (f : (M βŠ—[R] N) β†’β‚—[A] P) : M β†’β‚—[A] (N β†’β‚—[R] P) := { to_fun := curry (f.restrict_scalars R), map_smul' := Ξ» c x, linear_map.ext $ Ξ» y, f.map_smul c (x βŠ—β‚œ y), .. curry (f.restrict_scalars R) } lemma restrict_scalars_curry (f : (M βŠ—[R] N) β†’β‚—[A] P) : restrict_scalars R (curry f) = curry (f.restrict_scalars R) := rfl /-- Just as `tensor_product.ext` is marked `ext` instead of `tensor_product.ext'`, this is a better `ext` lemma than `tensor_product.algebra_tensor_module.ext` below. See note [partially-applied ext lemmas]. -/ @[ext] lemma curry_injective : function.injective (curry : (M βŠ— N β†’β‚—[A] P) β†’ (M β†’β‚—[A] N β†’β‚—[R] P)) := Ξ» x y h, linear_map.restrict_scalars_injective R $ curry_injective $ (congr_arg (linear_map.restrict_scalars R) h : _) theorem ext {g h : (M βŠ—[R] N) β†’β‚—[A] P} (H : βˆ€ x y, g (x βŠ—β‚œ y) = h (x βŠ—β‚œ y)) : g = h := curry_injective $ linear_map.extβ‚‚ H end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables [add_comm_monoid N] [module R N] variables [add_comm_monoid P] [module R P] [module A P] [is_scalar_tower R A P] /-- Heterobasic version of `tensor_product.lift`: Constructing a linear map `M βŠ—[R] N β†’[A] P` given a bilinear map `M β†’[A] N β†’[R] P` with the property that its composition with the canonical bilinear map `M β†’[A] N β†’[R] M βŠ—[R] N` is the given bilinear map `M β†’[A] N β†’[R] P`. -/ @[simps] def lift (f : M β†’β‚—[A] (N β†’β‚—[R] P)) : (M βŠ—[R] N) β†’β‚—[A] P := { map_smul' := Ξ» c, show βˆ€ x : M βŠ—[R] N, (lift (f.restrict_scalars R)).comp (lsmul R _ c) x = (lsmul R _ c).comp (lift (f.restrict_scalars R)) x, from ext_iff.1 $ tensor_product.ext' $ Ξ» x y, by simp only [comp_apply, algebra.lsmul_coe, smul_tmul', lift.tmul, coe_restrict_scalars_eq_coe, f.map_smul, smul_apply], .. lift (f.restrict_scalars R) } @[simp] lemma lift_tmul (f : M β†’β‚—[A] (N β†’β‚—[R] P)) (x : M) (y : N) : lift f (x βŠ—β‚œ y) = f x y := rfl variables (R A M N P) /-- Heterobasic version of `tensor_product.uncurry`: Linearly constructing a linear map `M βŠ—[R] N β†’[A] P` given a bilinear map `M β†’[A] N β†’[R] P` with the property that its composition with the canonical bilinear map `M β†’[A] N β†’[R] M βŠ—[R] N` is the given bilinear map `M β†’[A] N β†’[R] P`. -/ @[simps] def uncurry : (M β†’β‚—[A] (N β†’β‚—[R] P)) β†’β‚—[A] ((M βŠ—[R] N) β†’β‚—[A] P) := { to_fun := lift, map_add' := Ξ» f g, ext $ Ξ» x y, by simp only [lift_tmul, add_apply], map_smul' := Ξ» c f, ext $ Ξ» x y, by simp only [lift_tmul, smul_apply, ring_hom.id_apply] } /-- Heterobasic version of `tensor_product.lcurry`: Given a linear map `M βŠ—[R] N β†’[A] P`, compose it with the canonical bilinear map `M β†’[A] N β†’[R] M βŠ—[R] N` to form a bilinear map `M β†’[A] N β†’[R] P`. -/ @[simps] def lcurry : ((M βŠ—[R] N) β†’β‚—[A] P) β†’β‚—[A] (M β†’β‚—[A] (N β†’β‚—[R] P)) := { to_fun := curry, map_add' := Ξ» f g, rfl, map_smul' := Ξ» c f, rfl } /-- Heterobasic version of `tensor_product.lift.equiv`: A linear equivalence constructing a linear map `M βŠ—[R] N β†’[A] P` given a bilinear map `M β†’[A] N β†’[R] P` with the property that its composition with the canonical bilinear map `M β†’[A] N β†’[R] M βŠ—[R] N` is the given bilinear map `M β†’[A] N β†’[R] P`. -/ def lift.equiv : (M β†’β‚—[A] (N β†’β‚—[R] P)) ≃ₗ[A] ((M βŠ—[R] N) β†’β‚—[A] P) := linear_equiv.of_linear (uncurry R A M N P) (lcurry R A M N P) (linear_map.ext $ Ξ» f, ext $ Ξ» x y, lift_tmul _ x y) (linear_map.ext $ Ξ» f, linear_map.ext $ Ξ» x, linear_map.ext $ Ξ» y, lift_tmul f x y) variables (R A M N P) /-- Heterobasic version of `tensor_product.mk`: The canonical bilinear map `M β†’[A] N β†’[R] M βŠ—[R] N`. -/ @[simps] def mk : M β†’β‚—[A] N β†’β‚—[R] M βŠ—[R] N := { map_smul' := Ξ» c x, rfl, .. mk R M N } local attribute [ext] tensor_product.ext /-- Heterobasic version of `tensor_product.assoc`: Linear equivalence between `(M βŠ—[A] N) βŠ—[R] P` and `M βŠ—[A] (N βŠ—[R] P)`. -/ def assoc : ((M βŠ—[A] P) βŠ—[R] N) ≃ₗ[A] (M βŠ—[A] (P βŠ—[R] N)) := linear_equiv.of_linear (lift $ tensor_product.uncurry A _ _ _ $ comp (lcurry R A _ _ _) $ tensor_product.mk A M (P βŠ—[R] N)) (tensor_product.uncurry A _ _ _ $ comp (uncurry R A _ _ _) $ by { apply tensor_product.curry, exact (mk R A _ _) }) (by { ext, refl, }) (by { ext, simp only [curry_apply, tensor_product.curry_apply, mk_apply, tensor_product.mk_apply, uncurry_apply, tensor_product.uncurry_apply, id_apply, lift_tmul, comprβ‚‚_apply, restrict_scalars_apply, function.comp_app, to_fun_eq_coe, lcurry_apply, linear_map.comp_apply] }) end comm_semiring end algebra_tensor_module end tensor_product namespace linear_map open tensor_product /-! ### The base-change of a linear map of `R`-modules to a linear map of `A`-modules -/ section semiring variables {R A B M N : Type*} [comm_semiring R] variables [semiring A] [algebra R A] [semiring B] [algebra R B] variables [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] variables (r : R) (f g : M β†’β‚—[R] N) variables (A) /-- `base_change A f` for `f : M β†’β‚—[R] N` is the `A`-linear map `A βŠ—[R] M β†’β‚—[A] A βŠ—[R] N`. -/ def base_change (f : M β†’β‚—[R] N) : A βŠ—[R] M β†’β‚—[A] A βŠ—[R] N := { to_fun := f.ltensor A, map_add' := (f.ltensor A).map_add, map_smul' := Ξ» a x, show (f.ltensor A) (rtensor M (linear_map.mul R A a) x) = (rtensor N ((linear_map.mul R A) a)) ((ltensor A f) x), by { rw [← comp_apply, ← comp_apply], simp only [ltensor_comp_rtensor, rtensor_comp_ltensor] } } variables {A} @[simp] lemma base_change_tmul (a : A) (x : M) : f.base_change A (a βŠ—β‚œ x) = a βŠ—β‚œ (f x) := rfl lemma base_change_eq_ltensor : (f.base_change A : A βŠ— M β†’ A βŠ— N) = f.ltensor A := rfl @[simp] lemma base_change_add : (f + g).base_change A = f.base_change A + g.base_change A := by { ext, simp [base_change_eq_ltensor], } @[simp] lemma base_change_zero : base_change A (0 : M β†’β‚—[R] N) = 0 := by { ext, simp [base_change_eq_ltensor], } @[simp] lemma base_change_smul : (r β€’ f).base_change A = r β€’ (f.base_change A) := by { ext, simp [base_change_tmul], } variables (R A M N) /-- `base_change` as a linear map. -/ @[simps] def base_change_hom : (M β†’β‚—[R] N) β†’β‚—[R] A βŠ—[R] M β†’β‚—[A] A βŠ—[R] N := { to_fun := base_change A, map_add' := base_change_add, map_smul' := base_change_smul } end semiring section ring variables {R A B M N : Type*} [comm_ring R] variables [ring A] [algebra R A] [ring B] [algebra R B] variables [add_comm_group M] [module R M] [add_comm_group N] [module R N] variables (f g : M β†’β‚—[R] N) @[simp] lemma base_change_sub : (f - g).base_change A = f.base_change A - g.base_change A := by { ext, simp [base_change_eq_ltensor], } @[simp] lemma base_change_neg : (-f).base_change A = -(f.base_change A) := by { ext, simp [base_change_eq_ltensor], } end ring end linear_map namespace algebra namespace tensor_product section semiring variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type vβ‚‚} [semiring B] [algebra R B] /-! ### The `R`-algebra structure on `A βŠ—[R] B` -/ /-- (Implementation detail) The multiplication map on `A βŠ—[R] B`, for a fixed pure tensor in the first argument, as an `R`-linear map. -/ def mul_aux (a₁ : A) (b₁ : B) : (A βŠ—[R] B) β†’β‚—[R] (A βŠ—[R] B) := tensor_product.map (linear_map.mul_left R a₁) (linear_map.mul_left R b₁) @[simp] lemma mul_aux_apply (a₁ aβ‚‚ : A) (b₁ bβ‚‚ : B) : (mul_aux a₁ b₁) (aβ‚‚ βŠ—β‚œ[R] bβ‚‚) = (a₁ * aβ‚‚) βŠ—β‚œ[R] (b₁ * bβ‚‚) := rfl /-- (Implementation detail) The multiplication map on `A βŠ—[R] B`, as an `R`-bilinear map. -/ def mul : (A βŠ—[R] B) β†’β‚—[R] (A βŠ—[R] B) β†’β‚—[R] (A βŠ—[R] B) := tensor_product.lift $ linear_map.mkβ‚‚ R mul_aux (Ξ» x₁ xβ‚‚ y, tensor_product.ext' $ Ξ» x' y', by simp only [mul_aux_apply, linear_map.add_apply, add_mul, add_tmul]) (Ξ» c x y, tensor_product.ext' $ Ξ» x' y', by simp only [mul_aux_apply, linear_map.smul_apply, smul_tmul', smul_mul_assoc]) (Ξ» x y₁ yβ‚‚, tensor_product.ext' $ Ξ» x' y', by simp only [mul_aux_apply, linear_map.add_apply, add_mul, tmul_add]) (Ξ» c x y, tensor_product.ext' $ Ξ» x' y', by simp only [mul_aux_apply, linear_map.smul_apply, smul_tmul, smul_tmul', smul_mul_assoc]) @[simp] lemma mul_apply (a₁ aβ‚‚ : A) (b₁ bβ‚‚ : B) : mul (a₁ βŠ—β‚œ[R] b₁) (aβ‚‚ βŠ—β‚œ[R] bβ‚‚) = (a₁ * aβ‚‚) βŠ—β‚œ[R] (b₁ * bβ‚‚) := rfl lemma mul_assoc' (mul : (A βŠ—[R] B) β†’β‚—[R] (A βŠ—[R] B) β†’β‚—[R] (A βŠ—[R] B)) (h : βˆ€ (a₁ aβ‚‚ a₃ : A) (b₁ bβ‚‚ b₃ : B), mul (mul (a₁ βŠ—β‚œ[R] b₁) (aβ‚‚ βŠ—β‚œ[R] bβ‚‚)) (a₃ βŠ—β‚œ[R] b₃) = mul (a₁ βŠ—β‚œ[R] b₁) (mul (aβ‚‚ βŠ—β‚œ[R] bβ‚‚) (a₃ βŠ—β‚œ[R] b₃))) : βˆ€ (x y z : A βŠ—[R] B), mul (mul x y) z = mul x (mul y z) := begin intros, apply tensor_product.induction_on x, { simp only [linear_map.map_zero, linear_map.zero_apply], }, apply tensor_product.induction_on y, { simp only [linear_map.map_zero, forall_const, linear_map.zero_apply], }, apply tensor_product.induction_on z, { simp only [linear_map.map_zero, forall_const], }, { intros, simp only [h], }, { intros, simp only [linear_map.map_add, *], }, { intros, simp only [linear_map.map_add, *, linear_map.add_apply], }, { intros, simp only [linear_map.map_add, *, linear_map.add_apply], }, end protected lemma mul_assoc (x y z : A βŠ—[R] B) : mul (mul x y) z = mul x (mul y z) := mul_assoc' mul (by { intros, simp only [mul_apply, mul_assoc], }) x y z protected lemma one_mul (x : A βŠ—[R] B) : mul (1 βŠ—β‚œ 1) x = x := begin apply tensor_product.induction_on x; simp {contextual := tt}, end protected lemma mul_one (x : A βŠ—[R] B) : mul x (1 βŠ—β‚œ 1) = x := begin apply tensor_product.induction_on x; simp {contextual := tt}, end instance : has_one (A βŠ—[R] B) := { one := 1 βŠ—β‚œ 1 } instance : add_monoid_with_one (A βŠ—[R] B) := add_monoid_with_one.unary instance : semiring (A βŠ—[R] B) := { zero := 0, add := (+), one := 1, mul := Ξ» a b, mul a b, one_mul := algebra.tensor_product.one_mul, mul_one := algebra.tensor_product.mul_one, mul_assoc := algebra.tensor_product.mul_assoc, zero_mul := by simp, mul_zero := by simp, left_distrib := by simp, right_distrib := by simp, .. (by apply_instance : add_monoid_with_one (A βŠ—[R] B)), .. (by apply_instance : add_comm_monoid (A βŠ—[R] B)) }. lemma one_def : (1 : A βŠ—[R] B) = (1 : A) βŠ—β‚œ (1 : B) := rfl @[simp] lemma tmul_mul_tmul (a₁ aβ‚‚ : A) (b₁ bβ‚‚ : B) : (a₁ βŠ—β‚œ[R] b₁) * (aβ‚‚ βŠ—β‚œ[R] bβ‚‚) = (a₁ * aβ‚‚) βŠ—β‚œ[R] (b₁ * bβ‚‚) := rfl @[simp] lemma tmul_pow (a : A) (b : B) (k : β„•) : (a βŠ—β‚œ[R] b)^k = (a^k) βŠ—β‚œ[R] (b^k) := begin induction k with k ih, { simp [one_def], }, { simp [pow_succ, ih], } end /-- The ring morphism `A β†’+* A βŠ—[R] B` sending `a` to `a βŠ—β‚œ 1`. -/ @[simps] def include_left_ring_hom : A β†’+* A βŠ—[R] B := { to_fun := Ξ» a, a βŠ—β‚œ 1, map_zero' := by simp, map_add' := by simp [add_tmul], map_one' := rfl, map_mul' := by simp } variables {S : Type*} -- we want `is_scalar_tower_right` to take priority since it's better for unification elsewhere @[priority 100] instance is_scalar_tower_right [monoid S] [distrib_mul_action S A] [is_scalar_tower S A A] [smul_comm_class R S A] : is_scalar_tower S (A βŠ—[R] B) (A βŠ—[R] B) := { smul_assoc := Ξ» r x y, begin change (r β€’ x) * y = r β€’ (x * y), apply tensor_product.induction_on y, { simp [smul_zero], }, { apply tensor_product.induction_on x, { simp [smul_zero] }, { intros a b a' b', dsimp, rw [tensor_product.smul_tmul', tensor_product.smul_tmul', tmul_mul_tmul, smul_mul_assoc], }, { intros, simp [smul_add, add_mul, *], } }, { intros, simp [smul_add, mul_add, *], }, end } -- we want `algebra.to_smul_comm_class` to take priority since it's better for unification elsewhere @[priority 100] instance smul_comm_class_right [monoid S] [distrib_mul_action S A] [smul_comm_class S A A] [smul_comm_class R S A] : smul_comm_class S (A βŠ—[R] B) (A βŠ—[R] B) := { smul_comm := Ξ» r x y, begin change r β€’ (x * y) = x * r β€’ y, apply tensor_product.induction_on y, { simp [smul_zero], }, { apply tensor_product.induction_on x, { simp [smul_zero] }, { intros a b a' b', dsimp, rw [tensor_product.smul_tmul', tensor_product.smul_tmul', tmul_mul_tmul, mul_smul_comm], }, { intros, simp [smul_add, add_mul, *], } }, { intros, simp [smul_add, mul_add, *], }, end } variables [comm_semiring S] [algebra S A] instance left_algebra [smul_comm_class R S A] : algebra S (A βŠ—[R] B) := { commutes' := Ξ» r x, begin dsimp only [ring_hom.to_fun_eq_coe, ring_hom.comp_apply, include_left_ring_hom_apply], rw [algebra_map_eq_smul_one, ←smul_tmul', ←one_def, mul_smul_comm, smul_mul_assoc, mul_one, one_mul], end, smul_def' := Ξ» r x, begin dsimp only [ring_hom.to_fun_eq_coe, ring_hom.comp_apply, include_left_ring_hom_apply], rw [algebra_map_eq_smul_one, ←smul_tmul', smul_mul_assoc, ←one_def, one_mul], end, .. tensor_product.include_left_ring_hom.comp (algebra_map S A), .. (by apply_instance : module S (A βŠ—[R] B)) }. -- This is for the `undergrad.yaml` list. /-- The tensor product of two `R`-algebras is an `R`-algebra. -/ instance : algebra R (A βŠ—[R] B) := infer_instance @[simp] lemma algebra_map_apply [smul_comm_class R S A] (r : S) : (algebra_map S (A βŠ—[R] B)) r = ((algebra_map S A) r) βŠ—β‚œ 1 := rfl variables {C : Type v₃} [semiring C] [algebra R C] @[ext] theorem ext {g h : (A βŠ—[R] B) →ₐ[R] C} (H : βˆ€ a b, g (a βŠ—β‚œ b) = h (a βŠ—β‚œ b)) : g = h := begin apply @alg_hom.to_linear_map_injective R (A βŠ—[R] B) C _ _ _ _ _ _ _ _, ext, simp [H], end -- TODO: with `smul_comm_class R S A` we can have this as an `S`-algebra morphism /-- The `R`-algebra morphism `A →ₐ[R] A βŠ—[R] B` sending `a` to `a βŠ—β‚œ 1`. -/ def include_left : A →ₐ[R] A βŠ—[R] B := { commutes' := by simp, ..include_left_ring_hom } @[simp] lemma include_left_apply (a : A) : (include_left : A →ₐ[R] A βŠ—[R] B) a = a βŠ—β‚œ 1 := rfl /-- The algebra morphism `B →ₐ[R] A βŠ—[R] B` sending `b` to `1 βŠ—β‚œ b`. -/ def include_right : B →ₐ[R] A βŠ—[R] B := { to_fun := Ξ» b, 1 βŠ—β‚œ b, map_zero' := by simp, map_add' := by simp [tmul_add], map_one' := rfl, map_mul' := by simp, commutes' := Ξ» r, begin simp only [algebra_map_apply], transitivity r β€’ ((1 : A) βŠ—β‚œ[R] (1 : B)), { rw [←tmul_smul, algebra.smul_def], simp, }, { simp [algebra.smul_def], }, end, } @[simp] lemma include_right_apply (b : B) : (include_right : B →ₐ[R] A βŠ—[R] B) b = 1 βŠ—β‚œ b := rfl lemma include_left_comp_algebra_map {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] [algebra R S] [algebra R T] : (include_left.to_ring_hom.comp (algebra_map R S) : R β†’+* S βŠ—[R] T) = include_right.to_ring_hom.comp (algebra_map R T) := by { ext, simp } end semiring section ring variables {R : Type u} [comm_ring R] variables {A : Type v₁} [ring A] [algebra R A] variables {B : Type vβ‚‚} [ring B] [algebra R B] instance : ring (A βŠ—[R] B) := { .. (by apply_instance : add_comm_group (A βŠ—[R] B)), .. (by apply_instance : semiring (A βŠ—[R] B)) }. end ring section comm_ring variables {R : Type u} [comm_ring R] variables {A : Type v₁} [comm_ring A] [algebra R A] variables {B : Type vβ‚‚} [comm_ring B] [algebra R B] instance : comm_ring (A βŠ—[R] B) := { mul_comm := Ξ» x y, begin apply tensor_product.induction_on x, { simp, }, { intros a₁ b₁, apply tensor_product.induction_on y, { simp, }, { intros aβ‚‚ bβ‚‚, simp [mul_comm], }, { intros aβ‚‚ bβ‚‚ ha hb, simp [mul_add, add_mul, ha, hb], }, }, { intros x₁ xβ‚‚ h₁ hβ‚‚, simp [mul_add, add_mul, h₁, hβ‚‚], }, end .. (by apply_instance : ring (A βŠ—[R] B)) }. section right_algebra /-- `S βŠ—[R] T` has a `T`-algebra structure. This is not a global instance or else the action of `S` on `S βŠ—[R] S` would be ambiguous. -/ @[reducible] def right_algebra : algebra B (A βŠ—[R] B) := (algebra.tensor_product.include_right.to_ring_hom : B β†’+* A βŠ—[R] B).to_algebra local attribute [instance] tensor_product.right_algebra instance right_is_scalar_tower : is_scalar_tower R B (A βŠ—[R] B) := is_scalar_tower.of_algebra_map_eq (Ξ» r, (algebra.tensor_product.include_right.commutes r).symm) end right_algebra end comm_ring /-- Verify that typeclass search finds the ring structure on `A βŠ—[β„€] B` when `A` and `B` are merely rings, by treating both as `β„€`-algebras. -/ example {A : Type v₁} [ring A] {B : Type vβ‚‚} [ring B] : ring (A βŠ—[β„€] B) := by apply_instance /-- Verify that typeclass search finds the comm_ring structure on `A βŠ—[β„€] B` when `A` and `B` are merely comm_rings, by treating both as `β„€`-algebras. -/ example {A : Type v₁} [comm_ring A] {B : Type vβ‚‚} [comm_ring B] : comm_ring (A βŠ—[β„€] B) := by apply_instance /-! We now build the structure maps for the symmetric monoidal category of `R`-algebras. -/ section monoidal section variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type vβ‚‚} [semiring B] [algebra R B] variables {C : Type v₃} [semiring C] [algebra R C] variables {D : Type vβ‚„} [semiring D] [algebra R D] /-- Build an algebra morphism from a linear map out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_hom_of_linear_map_tensor_product (f : A βŠ—[R] B β†’β‚—[R] C) (w₁ : βˆ€ (a₁ aβ‚‚ : A) (b₁ bβ‚‚ : B), f ((a₁ * aβ‚‚) βŠ—β‚œ (b₁ * bβ‚‚)) = f (a₁ βŠ—β‚œ b₁) * f (aβ‚‚ βŠ—β‚œ bβ‚‚)) (wβ‚‚ : βˆ€ r, f ((algebra_map R A) r βŠ—β‚œ[R] 1) = (algebra_map R C) r): A βŠ—[R] B →ₐ[R] C := { map_one' := by rw [←(algebra_map R C).map_one, ←wβ‚‚, (algebra_map R A).map_one]; refl, map_zero' := by rw [linear_map.to_fun_eq_coe, map_zero], map_mul' := Ξ» x y, by { rw linear_map.to_fun_eq_coe, apply tensor_product.induction_on x, { rw [zero_mul, map_zero, zero_mul] }, { intros a₁ b₁, apply tensor_product.induction_on y, { rw [mul_zero, map_zero, mul_zero] }, { intros aβ‚‚ bβ‚‚, rw [tmul_mul_tmul, w₁] }, { intros x₁ xβ‚‚ h₁ hβ‚‚, rw [mul_add, map_add, map_add, mul_add, h₁, hβ‚‚] } }, { intros x₁ xβ‚‚ h₁ hβ‚‚, rw [add_mul, map_add, map_add, add_mul, h₁, hβ‚‚] } }, commutes' := Ξ» r, by rw [linear_map.to_fun_eq_coe, algebra_map_apply, wβ‚‚], .. f } @[simp] lemma alg_hom_of_linear_map_tensor_product_apply (f w₁ wβ‚‚ x) : (alg_hom_of_linear_map_tensor_product f w₁ wβ‚‚ : A βŠ—[R] B →ₐ[R] C) x = f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_tensor_product (f : A βŠ—[R] B ≃ₗ[R] C) (w₁ : βˆ€ (a₁ aβ‚‚ : A) (b₁ bβ‚‚ : B), f ((a₁ * aβ‚‚) βŠ—β‚œ (b₁ * bβ‚‚)) = f (a₁ βŠ—β‚œ b₁) * f (aβ‚‚ βŠ—β‚œ bβ‚‚)) (wβ‚‚ : βˆ€ r, f ((algebra_map R A) r βŠ—β‚œ[R] 1) = (algebra_map R C) r): A βŠ—[R] B ≃ₐ[R] C := { .. alg_hom_of_linear_map_tensor_product (f : A βŠ—[R] B β†’β‚—[R] C) w₁ wβ‚‚, .. f } @[simp] lemma alg_equiv_of_linear_equiv_tensor_product_apply (f w₁ wβ‚‚ x) : (alg_equiv_of_linear_equiv_tensor_product f w₁ wβ‚‚ : A βŠ—[R] B ≃ₐ[R] C) x = f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a triple tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_triple_tensor_product (f : ((A βŠ—[R] B) βŠ—[R] C) ≃ₗ[R] D) (w₁ : βˆ€ (a₁ aβ‚‚ : A) (b₁ bβ‚‚ : B) (c₁ cβ‚‚ : C), f ((a₁ * aβ‚‚) βŠ—β‚œ (b₁ * bβ‚‚) βŠ—β‚œ (c₁ * cβ‚‚)) = f (a₁ βŠ—β‚œ b₁ βŠ—β‚œ c₁) * f (aβ‚‚ βŠ—β‚œ bβ‚‚ βŠ—β‚œ cβ‚‚)) (wβ‚‚ : βˆ€ r, f (((algebra_map R A) r βŠ—β‚œ[R] (1 : B)) βŠ—β‚œ[R] (1 : C)) = (algebra_map R D) r) : (A βŠ—[R] B) βŠ—[R] C ≃ₐ[R] D := { to_fun := f, map_mul' := Ξ» x y, begin apply tensor_product.induction_on x, { simp only [map_zero, zero_mul] }, { intros ab₁ c₁, apply tensor_product.induction_on y, { simp only [map_zero, mul_zero] }, { intros abβ‚‚ cβ‚‚, apply tensor_product.induction_on ab₁, { simp only [zero_tmul, map_zero, zero_mul] }, { intros a₁ b₁, apply tensor_product.induction_on abβ‚‚, { simp only [zero_tmul, map_zero, mul_zero] }, { intros, simp only [tmul_mul_tmul, w₁] }, { intros x₁ xβ‚‚ h₁ hβ‚‚, simp only [tmul_mul_tmul] at h₁ hβ‚‚, simp only [tmul_mul_tmul, mul_add, add_tmul, map_add, h₁, hβ‚‚] } }, { intros x₁ xβ‚‚ h₁ hβ‚‚, simp only [tmul_mul_tmul] at h₁ hβ‚‚, simp only [tmul_mul_tmul, add_mul, add_tmul, map_add, h₁, hβ‚‚] } }, { intros x₁ xβ‚‚ h₁ hβ‚‚, simp only [tmul_mul_tmul, map_add, mul_add, add_mul, h₁, hβ‚‚], }, }, { intros x₁ xβ‚‚ h₁ hβ‚‚, simp only [tmul_mul_tmul, map_add, mul_add, add_mul, h₁, hβ‚‚], } end, commutes' := Ξ» r, by simp [wβ‚‚], .. f } @[simp] lemma alg_equiv_of_linear_equiv_triple_tensor_product_apply (f w₁ wβ‚‚ x) : (alg_equiv_of_linear_equiv_triple_tensor_product f w₁ wβ‚‚ : (A βŠ—[R] B) βŠ—[R] C ≃ₐ[R] D) x = f x := rfl end variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type vβ‚‚} [semiring B] [algebra R B] variables {C : Type v₃} [semiring C] [algebra R C] variables {D : Type vβ‚„} [semiring D] [algebra R D] section variables (R A) /-- The base ring is a left identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def lid : R βŠ—[R] A ≃ₐ[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.lid R A) (by simp [mul_smul]) (by simp [algebra.smul_def]) @[simp] theorem lid_tmul (r : R) (a : A) : (tensor_product.lid R A : (R βŠ— A β†’ A)) (r βŠ—β‚œ a) = r β€’ a := by simp [tensor_product.lid] /-- The base ring is a right identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def rid : A βŠ—[R] R ≃ₐ[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.rid R A) (by simp [mul_smul]) (by simp [algebra.smul_def]) @[simp] theorem rid_tmul (r : R) (a : A) : (tensor_product.rid R A : (A βŠ— R β†’ A)) (a βŠ—β‚œ r) = r β€’ a := by simp [tensor_product.rid] section variables (R A B) /-- The tensor product of R-algebras is commutative, up to algebra isomorphism. -/ protected def comm : A βŠ—[R] B ≃ₐ[R] B βŠ—[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.comm R A B) (by simp) (Ξ» r, begin transitivity r β€’ ((1 : B) βŠ—β‚œ[R] (1 : A)), { rw [←tmul_smul, algebra.smul_def], simp, }, { simp [algebra.smul_def], }, end) @[simp] theorem comm_tmul (a : A) (b : B) : (tensor_product.comm R A B : (A βŠ—[R] B β†’ B βŠ—[R] A)) (a βŠ—β‚œ b) = (b βŠ—β‚œ a) := by simp [tensor_product.comm] lemma adjoin_tmul_eq_top : adjoin R {t : A βŠ—[R] B | βˆƒ a b, a βŠ—β‚œ[R] b = t} = ⊀ := top_le_iff.mp $ (top_le_iff.mpr $ span_tmul_eq_top R A B).trans (span_le_adjoin R _) end section variables {R A B C} lemma assoc_aux_1 (a₁ aβ‚‚ : A) (b₁ bβ‚‚ : B) (c₁ cβ‚‚ : C) : (tensor_product.assoc R A B C) (((a₁ * aβ‚‚) βŠ—β‚œ[R] (b₁ * bβ‚‚)) βŠ—β‚œ[R] (c₁ * cβ‚‚)) = (tensor_product.assoc R A B C) ((a₁ βŠ—β‚œ[R] b₁) βŠ—β‚œ[R] c₁) * (tensor_product.assoc R A B C) ((aβ‚‚ βŠ—β‚œ[R] bβ‚‚) βŠ—β‚œ[R] cβ‚‚) := rfl lemma assoc_aux_2 (r : R) : (tensor_product.assoc R A B C) (((algebra_map R A) r βŠ—β‚œ[R] 1) βŠ—β‚œ[R] 1) = (algebra_map R (A βŠ— (B βŠ— C))) r := rfl variables (R A B C) /-- The associator for tensor product of R-algebras, as an algebra isomorphism. -/ protected def assoc : ((A βŠ—[R] B) βŠ—[R] C) ≃ₐ[R] (A βŠ—[R] (B βŠ—[R] C)) := alg_equiv_of_linear_equiv_triple_tensor_product (tensor_product.assoc.{u v₁ vβ‚‚ v₃} R A B C : (A βŠ— B βŠ— C) ≃ₗ[R] (A βŠ— (B βŠ— C))) (@algebra.tensor_product.assoc_aux_1.{u v₁ vβ‚‚ v₃} R _ A _ _ B _ _ C _ _) (@algebra.tensor_product.assoc_aux_2.{u v₁ vβ‚‚ v₃} R _ A _ _ B _ _ C _ _) variables {R A B C} @[simp] theorem assoc_tmul (a : A) (b : B) (c : C) : ((tensor_product.assoc R A B C) : (A βŠ—[R] B) βŠ—[R] C β†’ A βŠ—[R] (B βŠ—[R] C)) ((a βŠ—β‚œ b) βŠ—β‚œ c) = a βŠ—β‚œ (b βŠ—β‚œ c) := rfl end variables {R A B C D} /-- The tensor product of a pair of algebra morphisms. -/ def map (f : A →ₐ[R] B) (g : C →ₐ[R] D) : A βŠ—[R] C →ₐ[R] B βŠ—[R] D := alg_hom_of_linear_map_tensor_product (tensor_product.map f.to_linear_map g.to_linear_map) (by simp) (by simp [alg_hom.commutes]) @[simp] theorem map_tmul (f : A →ₐ[R] B) (g : C →ₐ[R] D) (a : A) (c : C) : map f g (a βŠ—β‚œ c) = f a βŠ—β‚œ g c := rfl @[simp] lemma map_comp_include_left (f : A →ₐ[R] B) (g : C →ₐ[R] D) : (map f g).comp include_left = include_left.comp f := alg_hom.ext $ by simp @[simp] lemma map_comp_include_right (f : A →ₐ[R] B) (g : C →ₐ[R] D) : (map f g).comp include_right = include_right.comp g := alg_hom.ext $ by simp lemma map_range (f : A →ₐ[R] B) (g : C →ₐ[R] D) : (map f g).range = (include_left.comp f).range βŠ” (include_right.comp g).range := begin apply le_antisymm, { rw [←map_top, ←adjoin_tmul_eq_top, ←adjoin_image, adjoin_le_iff], rintros _ ⟨_, ⟨a, b, rfl⟩, rfl⟩, rw [map_tmul, ←_root_.mul_one (f a), ←_root_.one_mul (g b), ←tmul_mul_tmul], exact mul_mem_sup (alg_hom.mem_range_self _ a) (alg_hom.mem_range_self _ b) }, { rw [←map_comp_include_left f g, ←map_comp_include_right f g], exact sup_le (alg_hom.range_comp_le_range _ _) (alg_hom.range_comp_le_range _ _) }, end /-- Construct an isomorphism between tensor products of R-algebras from isomorphisms between the tensor factors. -/ def congr (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) : A βŠ—[R] C ≃ₐ[R] B βŠ—[R] D := alg_equiv.of_alg_hom (map f g) (map f.symm g.symm) (ext $ Ξ» b d, by simp) (ext $ Ξ» a c, by simp) @[simp] lemma congr_apply (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) (x) : congr f g x = (map (f : A →ₐ[R] B) (g : C →ₐ[R] D)) x := rfl @[simp] lemma congr_symm_apply (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) (x) : (congr f g).symm x = (map (f.symm : B →ₐ[R] A) (g.symm : D →ₐ[R] C)) x := rfl end end monoidal section variables {R A B S : Type*} [comm_semiring R] [semiring A] [semiring B] [comm_semiring S] variables [algebra R A] [algebra R B] [algebra R S] variables (f : A →ₐ[R] S) (g : B →ₐ[R] S) variables (R) /-- `linear_map.mul'` is an alg_hom on commutative rings. -/ def lmul' : S βŠ—[R] S →ₐ[R] S := alg_hom_of_linear_map_tensor_product (linear_map.mul' R S) (Ξ» a₁ aβ‚‚ b₁ bβ‚‚, by simp only [linear_map.mul'_apply, mul_mul_mul_comm]) (Ξ» r, by simp only [linear_map.mul'_apply, _root_.mul_one]) variables {R} lemma lmul'_to_linear_map : (lmul' R : _ →ₐ[R] S).to_linear_map = linear_map.mul' R S := rfl @[simp] lemma lmul'_apply_tmul (a b : S) : lmul' R (a βŠ—β‚œ[R] b) = a * b := rfl @[simp] lemma lmul'_comp_include_left : (lmul' R : _ →ₐ[R] S).comp include_left = alg_hom.id R S := alg_hom.ext $ _root_.mul_one @[simp] lemma lmul'_comp_include_right : (lmul' R : _ →ₐ[R] S).comp include_right = alg_hom.id R S := alg_hom.ext $ _root_.one_mul /-- If `S` is commutative, for a pair of morphisms `f : A →ₐ[R] S`, `g : B →ₐ[R] S`, We obtain a map `A βŠ—[R] B →ₐ[R] S` that commutes with `f`, `g` via `a βŠ— b ↦ f(a) * g(b)`. -/ def product_map : A βŠ—[R] B →ₐ[R] S := (lmul' R).comp (tensor_product.map f g) @[simp] lemma product_map_apply_tmul (a : A) (b : B) : product_map f g (a βŠ—β‚œ b) = f a * g b := by { unfold product_map lmul', simp } lemma product_map_left_apply (a : A) : product_map f g ((include_left : A →ₐ[R] A βŠ— B) a) = f a := by simp @[simp] lemma product_map_left : (product_map f g).comp include_left = f := alg_hom.ext $ by simp lemma product_map_right_apply (b : B) : product_map f g (include_right b) = g b := by simp @[simp] lemma product_map_right : (product_map f g).comp include_right = g := alg_hom.ext $ by simp lemma product_map_range : (product_map f g).range = f.range βŠ” g.range := by rw [product_map, alg_hom.range_comp, map_range, map_sup, ←alg_hom.range_comp, ←alg_hom.range_comp, ←alg_hom.comp_assoc, ←alg_hom.comp_assoc, lmul'_comp_include_left, lmul'_comp_include_right, alg_hom.id_comp, alg_hom.id_comp] end section variables {R A A' B S : Type*} variables [comm_semiring R] [comm_semiring A] [semiring A'] [semiring B] [comm_semiring S] variables [algebra R A] [algebra R A'] [algebra A A'] [is_scalar_tower R A A'] [algebra R B] variables [algebra R S] [algebra A S] [is_scalar_tower R A S] /-- If `A`, `B` are `R`-algebras, `A'` is an `A`-algebra, then the product map of `f : A' →ₐ[A] S` and `g : B →ₐ[R] S` is an `A`-algebra homomorphism. -/ @[simps] def product_left_alg_hom (f : A' →ₐ[A] S) (g : B →ₐ[R] S) : A' βŠ—[R] B →ₐ[A] S := { commutes' := Ξ» r, by { dsimp, simp }, ..(product_map (f.restrict_scalars R) g).to_ring_hom } end section basis variables {k : Type*} [comm_ring k] (R : Type*) [ring R] [algebra k R] {M : Type*} [add_comm_monoid M] [module k M] {ΞΉ : Type*} (b : basis ΞΉ k M) /-- Given a `k`-algebra `R` and a `k`-basis of `M,` this is a `k`-linear isomorphism `R βŠ—[k] M ≃ (ΞΉ β†’β‚€ R)` (which is in fact `R`-linear). -/ noncomputable def basis_aux : R βŠ—[k] M ≃ₗ[k] (ΞΉ β†’β‚€ R) := (_root_.tensor_product.congr (finsupp.linear_equiv.finsupp_unique k R punit).symm b.repr) β‰ͺ≫ₗ (finsupp_tensor_finsupp k R k punit ΞΉ).trans (finsupp.lcongr (equiv.unique_prod ΞΉ punit) (_root_.tensor_product.rid k R)) variables {R} lemma basis_aux_tmul (r : R) (m : M) : basis_aux R b (r βŠ—β‚œ m) = r β€’ (finsupp.map_range (algebra_map k R) (map_zero _) (b.repr m)) := begin ext, simp [basis_aux, ←algebra.commutes, algebra.smul_def], end lemma basis_aux_map_smul (r : R) (x : R βŠ—[k] M) : basis_aux R b (r β€’ x) = r β€’ basis_aux R b x := tensor_product.induction_on x (by simp) (Ξ» x y, by simp only [tensor_product.smul_tmul', basis_aux_tmul, smul_assoc]) (Ξ» x y hx hy, by simp [hx, hy]) variables (R) /-- Given a `k`-algebra `R`, this is the `R`-basis of `R βŠ—[k] M` induced by a `k`-basis of `M`. -/ noncomputable def basis : basis ΞΉ R (R βŠ—[k] M) := { repr := { map_smul' := basis_aux_map_smul b, .. basis_aux R b } } variables {R} @[simp] lemma basis_repr_tmul (r : R) (m : M) : (basis R b).repr (r βŠ—β‚œ m) = r β€’ (finsupp.map_range (algebra_map k R) (map_zero _) (b.repr m)) := basis_aux_tmul _ _ _ @[simp] lemma basis_repr_symm_apply (r : R) (i : ΞΉ) : (basis R b).repr.symm (finsupp.single i r) = r βŠ—β‚œ b.repr.symm (finsupp.single i 1) := by simp [basis, equiv.unique_prod_symm_apply, basis_aux] end basis end tensor_product end algebra namespace module variables {R M N : Type*} [comm_semiring R] variables [add_comm_monoid M] [add_comm_monoid N] variables [module R M] [module R N] /-- The algebra homomorphism from `End M βŠ— End N` to `End (M βŠ— N)` sending `f βŠ—β‚œ g` to the `tensor_product.map f g`, the tensor product of the two maps. -/ def End_tensor_End_alg_hom : (End R M) βŠ—[R] (End R N) →ₐ[R] End R (M βŠ—[R] N) := begin refine algebra.tensor_product.alg_hom_of_linear_map_tensor_product (hom_tensor_hom_map R M N M N) _ _, { intros f₁ fβ‚‚ g₁ gβ‚‚, simp only [hom_tensor_hom_map_apply, tensor_product.map_mul] }, { intro r, simp only [hom_tensor_hom_map_apply], ext m n, simp [smul_tmul] } end lemma End_tensor_End_alg_hom_apply (f : End R M) (g : End R N) : End_tensor_End_alg_hom (f βŠ—β‚œ[R] g) = tensor_product.map f g := by simp only [End_tensor_End_alg_hom, algebra.tensor_product.alg_hom_of_linear_map_tensor_product_apply, hom_tensor_hom_map_apply] end module lemma subalgebra.finite_dimensional_sup {K L : Type*} [field K] [comm_ring L] [algebra K L] (E1 E2 : subalgebra K L) [finite_dimensional K E1] [finite_dimensional K E2] : finite_dimensional K β†₯(E1 βŠ” E2) := begin rw [←E1.range_val, ←E2.range_val, ←algebra.tensor_product.product_map_range], exact (algebra.tensor_product.product_map E1.val E2.val).to_linear_map.finite_dimensional_range, end namespace tensor_product.algebra variables {R A B M : Type*} variables [comm_semiring R] [add_comm_monoid M] [module R M] variables [semiring A] [semiring B] [module A M] [module B M] variables [algebra R A] [algebra R B] variables [is_scalar_tower R A M] [is_scalar_tower R B M] /-- An auxiliary definition, used for constructing the `module (A βŠ—[R] B) M` in `tensor_product.algebra.module` below. -/ def module_aux : A βŠ—[R] B β†’β‚—[R] M β†’β‚—[R] M := tensor_product.lift { to_fun := Ξ» a, a β€’ (algebra.lsmul R M : B →ₐ[R] module.End R M).to_linear_map, map_add' := Ξ» r t, by { ext, simp only [add_smul, linear_map.add_apply] }, map_smul' := Ξ» n r, by { ext, simp only [ring_hom.id_apply, linear_map.smul_apply, smul_assoc] } } lemma module_aux_apply (a : A) (b : B) (m : M) : module_aux (a βŠ—β‚œ[R] b) m = a β€’ b β€’ m := rfl variables [smul_comm_class A B M] /-- If `M` is a representation of two different `R`-algebras `A` and `B` whose actions commute, then it is a representation the `R`-algebra `A βŠ—[R] B`. An important example arises from a semiring `S`; allowing `S` to act on itself via left and right multiplication, the roles of `R`, `A`, `B`, `M` are played by `β„•`, `S`, `Sᡐᡒᡖ`, `S`. This example is important because a submodule of `S` as a `module` over `S βŠ—[β„•] Sᡐᡒᡖ` is a two-sided ideal. NB: This is not an instance because in the case `B = A` and `M = A βŠ—[R] A` we would have a diamond of `smul` actions. Furthermore, this would not be a mere definitional diamond but a true mathematical diamond in which `A βŠ—[R] A` had two distinct scalar actions on itself: one from its multiplication, and one from this would-be instance. Arguably we could live with this but in any case the real fix is to address the ambiguity in notation, probably along the lines outlined here: https://leanprover.zulipchat.com/#narrow/stream/144837-PR-reviews/topic/.234773.20base.20change/near/240929258 -/ protected def module : module (A βŠ—[R] B) M := { smul := Ξ» x m, module_aux x m, zero_smul := Ξ» m, by simp only [map_zero, linear_map.zero_apply], smul_zero := Ξ» x, by simp only [map_zero], smul_add := Ξ» x m₁ mβ‚‚, by simp only [map_add], add_smul := Ξ» x y m, by simp only [map_add, linear_map.add_apply], one_smul := Ξ» m, by simp only [module_aux_apply, algebra.tensor_product.one_def, one_smul], mul_smul := Ξ» x y m, begin apply tensor_product.induction_on x; apply tensor_product.induction_on y, { simp only [mul_zero, map_zero, linear_map.zero_apply], }, { intros a b, simp only [zero_mul, map_zero, linear_map.zero_apply], }, { intros z w hz hw, simp only [zero_mul, map_zero, linear_map.zero_apply], }, { intros a b, simp only [mul_zero, map_zero, linear_map.zero_apply], }, { intros a₁ b₁ aβ‚‚ bβ‚‚, simp only [module_aux_apply, mul_smul, smul_comm a₁ bβ‚‚, algebra.tensor_product.tmul_mul_tmul, linear_map.mul_apply], }, { intros z w hz hw a b, simp only at hz hw, simp only [mul_add, hz, hw, map_add, linear_map.add_apply], }, { intros z w hz hw, simp only [mul_zero, map_zero, linear_map.zero_apply], }, { intros a b z w hz hw, simp only at hz hw, simp only [map_add, add_mul, linear_map.add_apply, hz, hw], }, { intros u v hu hv z w hz hw, simp only at hz hw, simp only [add_mul, hz, hw, map_add, linear_map.add_apply], }, end } local attribute [instance] tensor_product.algebra.module lemma smul_def (a : A) (b : B) (m : M) : (a βŠ—β‚œ[R] b) β€’ m = a β€’ b β€’ m := rfl end tensor_product.algebra
a63ea9a8302f07cd56ae17c52d175927a644fcd9
56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3
/src/tools/get_module_info.lean
db6b132e746c742e82fc57119ef29024b2839d81
[ "Apache-2.0" ]
permissive
DyeKuu/lean-tpe-public
3a9968f286ca182723ef7e7d97e155d8cb6b1e70
750ade767ab28037e80b7a80360d213a875038f8
refs/heads/master
1,682,842,633,115
1,621,330,793,000
1,621,330,793,000
368,475,816
0
0
Apache-2.0
1,621,330,745,000
1,621,330,744,000
null
UTF-8
Lean
false
false
1,356
lean
import ..utils.util import all section main open tactic meta def list.drop_until {Ξ±} [decidable_eq Ξ±] : list Ξ± β†’ (Ξ± β†’ bool) β†’ list Ξ± | arg@(x::xs) y := if (bnot $ y x) then list.drop_until xs y else arg | [] _ := [] meta def get_top_level_module_name (decl_nm : name) : tactic string := do { env ← tactic.get_env, xs ← (string.split (Ξ» c, c = '/')) <$> env.decl_olean decl_nm, (xs.drop_until $ (Ξ» x, x = "src" ∨ x = "library")).nth 1 } meta def main : io unit := do { args ← io.cmdline_args, (some decls_file) ← (pure $ args.nth 0) | io.fail' format!"MUST SUPPLY decls_file AS FIRST ARGUMENT", (some dest) ← (pure $ args.nth 1) | io.fail' format!"MUST SUPPLY dest AS SECOND ARGUMENT", nm_strs ← (io.mk_file_handle decls_file io.mode.read >>= Ξ» f, (string.split (Ξ» c, c = '\n') <$> buffer.to_string <$> io.fs.read_to_end f)), (nms : list (name Γ— list name)) ← (nm_strs.filter $ Ξ» nm_str, string.length nm_str > 0).mmap $ Ξ» nm_str, do { ((io.run_tactic' ∘ parse_decl_nm_and_open_ns) $ nm_str) }, f ← io.mk_file_handle dest io.mode.write, for_ nms $ Ξ» ⟨nm, _⟩, do { m_nm ← io.run_tactic' $ (get_top_level_module_name nm) <|> pure "none", io.fs.put_str_ln f $ format.to_string $ format!"{nm} {m_nm}", io.put_str_ln' format!"PROCESSED DECL: {nm}" } } end main
52dffa0da5066cef6a852490d8177c198958577c
1901b51268d21ec7361af7d3534abd9a8fa5cf52
/src/graph_theory/pushforward.lean
dec2da5ac51b7ab40853e4e568dd313f66b9001b
[]
no_license
vbeffara/lean
b9ea4107deeaca6f4da98e5de029b62e4861ab40
0004b1d502ac3f4ccd213dbd23589d4c4f9fece8
refs/heads/main
1,652,050,034,756
1,651,610,858,000
1,651,610,858,000
225,244,535
6
1
null
null
null
null
UTF-8
Lean
false
false
9,461
lean
import combinatorics.simple_graph.basic combinatorics.simple_graph.connectivity data.set.basic import graph_theory.basic open function set classical variables {V V' V'' : Type*} {x y z : V} {x' y' z' : V'} {f : V β†’ V'} {g : V' β†’ V''} variables {G G₁ Gβ‚‚ : simple_graph V} {G' G'₁ G'β‚‚ : simple_graph V'} {G'' : simple_graph V''} namespace simple_graph def pull (f : V β†’ V') (G' : simple_graph V') : simple_graph V := { adj := G'.adj on f, symm := Ξ» _ _ h, G'.symm h, loopless := Ξ» _, G'.loopless _ } namespace pull lemma comp : pull (g ∘ f) = pull f ∘ pull g := by { ext x y, exact iff.rfl } def to_iso (f : V ≃ V') (G' : simple_graph V') : pull f G' ≃g G' := ⟨f,Ξ» x y, iff.rfl⟩ lemma from_iso (Ο† : G ≃g G') : pull Ο† G' = G := by { ext x y, have := Ο†.map_rel_iff', exact this } lemma mono : monotone (pull f) := by { intros G'₁ G'β‚‚ h x' y', apply h } end pull -- TODO: this is an alternative definition for pull def pull' (f : V β†’ V') (G' : simple_graph V') : simple_graph V := { adj := Ξ» x y, x β‰  y ∧ (f x = f y ∨ G'.adj (f x) (f y)), symm := Ξ» x y ⟨h₁,hβ‚‚βŸ©, by { refine ⟨h₁.symm,_⟩, cases hβ‚‚, left, exact hβ‚‚.symm, right, exact hβ‚‚.symm }, loopless := Ξ» x, by { push_neg, intro, contradiction } } namespace pull' lemma comp : pull' (g ∘ f) = pull' f ∘ pull' g := begin ext G'' x y, split, { rintros ⟨h₁,hβ‚‚βŸ©, refine ⟨h₁,_⟩, by_cases f x = f y, { left, exact h }, { right, exact ⟨h,hβ‚‚βŸ© } }, { rintros ⟨h₁,hβ‚‚βŸ©, refine ⟨h₁,_⟩, cases hβ‚‚, { left, convert congr_arg g hβ‚‚ }, { rcases hβ‚‚ with ⟨h₃,hβ‚„βŸ©, cases hβ‚„, left, exact hβ‚„, right, exact hβ‚„ } } end lemma iff_pull_of_inj (hf : injective f) : pull f G' = pull' f G' := begin ext x y, split, { intro h₁, refine ⟨simple_graph.ne_of_adj _ h₁,_⟩, right, exact h₁ }, { rintros ⟨h₁,hβ‚‚βŸ©, cases hβ‚‚, have := hf hβ‚‚, contradiction, exact hβ‚‚ } end def to_iso (f : V ≃ V') (G' : simple_graph V') : pull' f G' ≃g G' := by { rewrite ← iff_pull_of_inj f.injective, apply pull.to_iso } lemma from_iso (Ο† : G ≃g G') : pull' Ο† G' = G := by { rewrite ← iff_pull_of_inj Ο†.injective, apply pull.from_iso } lemma mono : monotone (pull' f) := by { rintros G H h x y ⟨h₁,hβ‚‚βŸ©, refine ⟨h₁,_⟩, cases hβ‚‚, left, exact hβ‚‚, right, exact h hβ‚‚ } end pull' @[ext] def map (f : V β†’ V') (G : simple_graph V) : simple_graph V' := { adj := ne βŠ“ relation.map G.adj f f, symm := Ξ» x y ⟨h₁,u,v,hβ‚‚,h₃,hβ‚„βŸ©, ⟨h₁.symm,v,u,hβ‚‚.symm,hβ‚„,hβ‚ƒβŸ©, loopless := Ξ» _ ⟨h,_⟩, h rfl } namespace map noncomputable instance : decidable_rel (map f G).adj := by { classical, apply_instance } @[simp] lemma id : map id G = G := begin ext : 1, simp only [map, relation.map, id.def, exists_eq_right_right, exists_eq_right, inf_eq_right], apply ne_of_adj, end lemma adj (f : V β†’ V') : G.adj x y β†’ f x = f y ∨ (map f G).adj (f x) (f y) := by { intro h₁, by_cases f x = f y, left, exact h, right, refine ⟨h,x,y,h₁,rfl,rfl⟩ } lemma comp : map (g ∘ f) = map g ∘ map f := begin ext G x'' y'', split, { rintro ⟨h₁,u,v,hβ‚‚,rfl,rfl⟩, exact ⟨h₁,f u,f v,⟨ne_of_apply_ne _ h₁,u,v,hβ‚‚,rfl,rfl⟩,rfl,rfl⟩ }, { rintro ⟨h₁,x',y',⟨hβ‚‚,x,y,h₃,rfl,rfl⟩,rfl,rfl⟩, exact ⟨h₁,x,y,h₃,rfl,rfl⟩ } end lemma left_inverse_of_injective (h : injective f) : left_inverse (pull f) (map f) := begin intro G, ext x y, split, { rintro ⟨h₁,u,v,hβ‚‚,h₃,hβ‚„βŸ©, rw [←h h₃, ←h hβ‚„], exact hβ‚‚ }, { intro h₁, exact ⟨h.ne (G.ne_of_adj h₁),x,y,h₁,rfl,rfl⟩ } end lemma left_inverse_of_injective' (h : injective f) : left_inverse (pull' f) (map f) := begin intro G, ext x y, split, { rintro ⟨h₁,hβ‚‚βŸ©, cases hβ‚‚, have := h hβ‚‚, contradiction, rcases hβ‚‚ with ⟨hβ‚‚,x',y',h₃,hβ‚„,hβ‚…βŸ©, rwa [←h hβ‚„, ←h hβ‚…] }, { intro h₁, refine ⟨G.ne_of_adj h₁, _⟩, by_cases hβ‚‚ : f x = f y, left, exact hβ‚‚, right, exact ⟨hβ‚‚,x,y,h₁,rfl,rfl⟩ } end lemma right_inverse_of_surjective (h : surjective f) : right_inverse (pull f) (map f) := begin intro G', ext x' y', split, { rintro ⟨-,x,y,hβ‚‚,rfl,rfl⟩, exact hβ‚‚ }, { intro h₁, cases h x' with x, cases h y' with y, substs x' y', exact ⟨G'.ne_of_adj h₁,x,y,h₁,rfl,rfl⟩ } end lemma right_inverse_of_surjective' (h : surjective f) : right_inverse (pull' f) (map f) := begin intro G', ext x' y', split, { rintro ⟨h₁,x,y,⟨-,hβ‚ƒβŸ©,rfl,rfl⟩, cases h₃, contradiction, exact h₃ }, { intro h₁, cases h x' with x, cases h y' with y, substs x' y', refine ⟨G'.ne_of_adj h₁,x,y,_,rfl,rfl⟩, refine ⟨_,_⟩, intro hβ‚‚, exact G'.ne_of_adj h₁ (congr_arg f hβ‚‚), right, exact h₁ } end def to_iso (f : V ≃ V') (G : simple_graph V) : G ≃g map f G := by { convert ← pull.to_iso f _, apply left_inverse_of_injective f.left_inv.injective } lemma from_iso (Ο† : G ≃g G') : G' = map Ο† G := by { convert ← congr_arg _ (pull.from_iso Ο†), apply right_inverse_of_surjective Ο†.right_inv.surjective } lemma mono : monotone (map f) := by { rintros G₁ Gβ‚‚ h₁ x' y' ⟨hβ‚‚,x,y,h₃,rfl,rfl⟩, exact ⟨hβ‚‚,x,y,h₁ h₃,rfl,rfl⟩ } lemma le {Ο† : G β†’g G'} : map Ο† G ≀ G' := by { rintros x' y' ⟨-,x,y,hβ‚‚,rfl,rfl⟩, exact Ο†.map_rel hβ‚‚ } end map def merge_edge [decidable_eq V] {G : simple_graph V} (e : G.dart) : V β†’ V := update id e.snd e.fst def contract_edge (G : simple_graph V) [decidable_eq V] (e : G.dart) := G.map (merge_edge e) infix ` / ` := contract_edge noncomputable instance {G : simple_graph V} [decidable_eq V] {e : G.dart} : decidable_rel (G/e).adj := by { classical, apply_instance } namespace contract_edge variables [fintype V] [decidable_eq V] [decidable_eq V'] [decidable_rel G.adj] @[reducible] def preserved (f : V β†’ V') (G : simple_graph V) : Type* := {e : G.dart // f e.fst β‰  f e.snd} def proj_edge (e : G.dart) : preserved (merge_edge e) G β†’ (G/e).dart := Ξ» ⟨⟨⟨x,y⟩,hxy⟩,hβ‚βŸ©, ⟨(merge_edge e x, merge_edge e y), ⟨h₁,x,y,hxy,rfl,rfl⟩⟩ lemma proj_edge_surj {e : G.dart} : surjective (proj_edge e) := begin rintro ⟨⟨x',y'⟩,⟨h₁,⟨x,y,hβ‚‚,h₃,hβ‚„βŸ©βŸ©βŸ©, refine ⟨⟨⟨(x,y),hβ‚‚βŸ©,_⟩,_⟩, { rw [h₃,hβ‚„], exact h₁ }, { simp only [proj_edge, prod.mk.inj_iff], exact ⟨h₃,hβ‚„βŸ© } end lemma fewer_edges {e : G.dart} [decidable_rel (G/e).adj] : fintype.card (G/e).dart < fintype.card G.dart := calc fintype.card (G/e).dart ≀ fintype.card (preserved (merge_edge e) G) : fintype.card_le_of_surjective _ proj_edge_surj ... < fintype.card (G.dart) : by { apply fintype.card_lt_of_injective_of_not_mem _ subtype.coe_injective, swap, exact e, simp [merge_edge,update] } end contract_edge def select (P : V β†’ Prop) (G : simple_graph V) : simple_graph (subtype P) := pull subtype.val G namespace select variables {P : V β†’ Prop} {P' : V' β†’ Prop} lemma mono {P : V β†’ Prop} : monotone (select P) := by { apply pull.mono } def fmap (f : V β†’ V') (P' : V' β†’ Prop) : {x : V // P' (f x)} β†’ {x' : V' // P' x'} := Ξ» x, ⟨f x, x.prop⟩ def push_walk (p : walk G x y) (hp : βˆ€ z ∈ p.support, P z) : walk (select P G) ⟨x, hp x (walk.start_mem_support p)⟩ ⟨y, hp y (walk.end_mem_support p)⟩ := begin induction p with a a b c h₁ p ih, refl, have hp' : βˆ€ z ∈ p.support, P z := by { intros z hz, apply hp, right, exact hz }, refine walk.cons _ (ih hp'), exact h₁ end lemma mem_push_walk {p : G.walk x y} {hp : βˆ€ z ∈ p.support, P z} {z' : subtype P} : z' ∈ (push_walk p hp).support ↔ z'.val ∈ p.support := begin induction p with a a b c h₁ p ih, { simp [push_walk, subtype.ext_iff, subtype.coe_mk] }, { split, { rintro (h|h), left, subst h, right, exact ih.mp h }, { rintro (h|h), left, subst h, simp, right, exact ih.mpr h } } end def pull_walk {x y} (p : walk (select P G) x y) : walk G x.val y.val := by { induction p with a a b c h₁ p ih, refl, refine walk.cons h₁ ih } lemma pull_walk_spec {x y} (p : walk (select P G) x y) : βˆ€ z ∈ (pull_walk p).support, P z := begin induction p with a a b c h₁ p ih, { intros z hz, cases hz, rw hz, exact a.prop, cases hz }, { intros z hz, cases hz, rw hz, exact a.prop, exact ih z hz } end end select namespace is_smaller lemma select_left {pred : V β†’ Prop} : G β‰Όs G' -> select pred G β‰Όs G' := Ξ» ⟨⟨f,hβ‚βŸ©,hβ‚‚βŸ©, let g : {x // pred x} -> V' := f ∘ subtype.val in ⟨⟨g,Ξ» a b,hβ‚βŸ©,hβ‚‚.comp subtype.val_injective⟩ end is_smaller def embed (f : V β†’ V') : simple_graph V β†’ simple_graph (range f) := select (range f) ∘ map f namespace embed noncomputable def iso (f_inj : injective f) : G ≃g embed f G := let Ο† : V β†’ range f := Ξ» x, ⟨f x, x, rfl⟩, ψ : range f β†’ V := Ξ» y, some y.prop in { to_fun := Ο†, inv_fun := ψ, left_inv := Ξ» x, f_inj (some_spec (subtype.prop (Ο† x))), right_inv := Ξ» y, subtype.ext (some_spec y.prop), map_rel_iff' := Ξ» a b, by { dsimp only [Ο†], split, { rintros ⟨-,x,y,hβ‚‚,h₃,hβ‚„βŸ©, rwa [←f_inj h₃, ←f_inj hβ‚„] }, { intro h₁, refine ⟨f_inj.ne (G.ne_of_adj h₁),a,b,h₁,rfl,rfl⟩ } } } lemma le_select {f : G β†’g G'} (f_inj : injective f) : embed f G ≀ select (range f) G' := select.mono map.le end embed end simple_graph